getNonVersionArrayKeys()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * \PHPCompatibility\Sniffs\PHP\RequiredOptionalFunctionParametersSniff.
4
 *
5
 * @category PHP
6
 * @package  PHPCompatibility
7
 * @author   Juliette Reinders Folmer <[email protected]>
8
 */
9
10
namespace PHPCompatibility\Sniffs\PHP;
11
12
use PHPCompatibility\AbstractComplexVersionSniff;
13
14
/**
15
 * \PHPCompatibility\Sniffs\PHP\RequiredOptionalFunctionParametersSniff.
16
 *
17
 * @category PHP
18
 * @package  PHPCompatibility
19
 * @author   Juliette Reinders Folmer <[email protected]>
20
 */
21
class RequiredOptionalFunctionParametersSniff extends AbstractComplexVersionSniff
22
{
23
24
    /**
25
     * A list of function parameters, which were required in older versions and became optional later on.
26
     *
27
     * The array lists : version number with true (required) and false (optional).
28
     *
29
     * The index is the location of the parameter in the parameter list, starting at 0 !
30
     * If's sufficient to list the last version in which the parameter was still required.
31
     *
32
     * @var array
33
     */
34
    protected $functionParameters = array(
35
        'bcscale' => array(
36
            0 => array(
37
                'name' => 'scale',
38
                '7.2'  => true,
39
                '7.3'  => false,
40
            ),
41
        ),
42
        'getenv' => array(
43
            0 => array(
44
                'name' => 'varname',
45
                '7.0'  => true,
46
                '7.1'  => false,
47
            ),
48
        ),
49
        'preg_match_all' => array(
50
            2 => array(
51
                'name' => 'matches',
52
                '5.3'  => true,
53
                '5.4'  => false,
54
            ),
55
        ),
56
        'stream_socket_enable_crypto' => array(
57
            2 => array(
58
                'name' => 'crypto_type',
59
                '5.5'  => true,
60
                '5.6'  => false,
61
            ),
62
        ),
63
    );
64
65
66
    /**
67
     * Returns an array of tokens this test wants to listen for.
68
     *
69
     * @return array
70
     */
71
    public function register()
72
    {
73
        // Handle case-insensitivity of function names.
74
        $this->functionParameters = $this->arrayKeysToLowercase($this->functionParameters);
75
76
        return array(T_STRING);
77
    }//end register()
78
79
    /**
80
     * Processes this test, when one of its tokens is encountered.
81
     *
82
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
83
     * @param int                   $stackPtr  The position of the current token in
84
     *                                         the stack passed in $tokens.
85
     *
86
     * @return void
87
     */
88
    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
89
    {
90
        $tokens = $phpcsFile->getTokens();
91
92
        $ignore = array(
93
            T_DOUBLE_COLON,
94
            T_OBJECT_OPERATOR,
95
            T_FUNCTION,
96
            T_CONST,
97
        );
98
99
        $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
100
        if (in_array($tokens[$prevToken]['code'], $ignore) === true) {
101
            // Not a call to a PHP function.
102
            return;
103
        }
104
105
        $function   = $tokens[$stackPtr]['content'];
106
        $functionLc = strtolower($function);
107
108
        if (isset($this->functionParameters[$functionLc]) === false) {
109
            return;
110
        }
111
112
        $parameterCount  = $this->getFunctionCallParameterCount($phpcsFile, $stackPtr);
113
        $openParenthesis = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
114
115
        // If the parameter count returned > 0, we know there will be valid open parenthesis.
116
        if ($parameterCount === 0 && $tokens[$openParenthesis]['code'] !== T_OPEN_PARENTHESIS) {
117
            return;
118
        }
119
120
        $parameterOffsetFound = $parameterCount - 1;
121
122
        foreach ($this->functionParameters[$functionLc] as $offset => $parameterDetails) {
123
            if ($offset > $parameterOffsetFound) {
124
                $itemInfo = array(
125
                    'name'   => $function,
126
                    'nameLc' => $functionLc,
127
                    'offset' => $offset,
128
                );
129
                $this->handleFeature($phpcsFile, $openParenthesis, $itemInfo);
130
            }
131
        }
132
133
    }//end process()
134
135
136
    /**
137
     * Determine whether an error/warning should be thrown for an item based on collected information.
138
     *
139
     * @param array $errorInfo Detail information about an item.
140
     *
141
     * @return bool
142
     */
143
    protected function shouldThrowError(array $errorInfo)
144
    {
145
        return ($errorInfo['requiredVersion'] !== '');
146
    }
147
148
149
    /**
150
     * Get the relevant sub-array for a specific item from a multi-dimensional array.
151
     *
152
     * @param array $itemInfo Base information about the item.
153
     *
154
     * @return array Version and other information about the item.
155
     */
156
    public function getItemArray(array $itemInfo)
157
    {
158
        return $this->functionParameters[$itemInfo['nameLc']][$itemInfo['offset']];
159
    }
160
161
162
    /**
163
     * Get an array of the non-PHP-version array keys used in a sub-array.
164
     *
165
     * @return array
166
     */
167
    protected function getNonVersionArrayKeys()
168
    {
169
        return array('name');
170
    }
171
172
173
    /**
174
     * Retrieve the relevant detail (version) information for use in an error message.
175
     *
176
     * @param array $itemArray Version and other information about the item.
177
     * @param array $itemInfo  Base information about the item.
178
     *
179
     * @return array
180
     */
181 View Code Duplication
    public function getErrorInfo(array $itemArray, array $itemInfo)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
    {
183
        $errorInfo = array(
184
            'paramName'       => '',
185
            'requiredVersion' => '',
186
        );
187
188
        $versionArray = $this->getVersionArray($itemArray);
189
190
        if (empty($versionArray) === false) {
191
            foreach ($versionArray as $version => $required) {
192
                if ($required === true && $this->supportsBelow($version) === true) {
193
                    $errorInfo['requiredVersion'] = $version;
194
                }
195
            }
196
        }
197
198
        $errorInfo['paramName'] = $itemArray['name'];
199
200
        return $errorInfo;
201
202
    }//end getErrorInfo()
203
204
205
    /**
206
     * Get the error message template for this sniff.
207
     *
208
     * @return string
209
     */
210
    protected function getErrorMsgTemplate()
211
    {
212
        return 'The "%s" parameter for function %s() is missing, but was required for PHP version %s and lower';
213
    }
214
215
216
    /**
217
     * Generates the error or warning for this item.
218
     *
219
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
220
     * @param int                   $stackPtr  The position of the relevant token in
221
     *                                         the stack.
222
     * @param array                 $itemInfo  Base information about the item.
223
     * @param array                 $errorInfo Array with detail (version) information
224
     *                                         relevant to the item.
225
     *
226
     * @return void
227
     */
228
    public function addError(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, array $itemInfo, array $errorInfo)
229
    {
230
        $error     = $this->getErrorMsgTemplate();
231
        $errorCode = $this->stringToErrorCode($itemInfo['name'].'_'.$errorInfo['paramName']).'Missing';
232
        $data      = array(
233
            $errorInfo['paramName'],
234
            $itemInfo['name'],
235
            $errorInfo['requiredVersion'],
236
        );
237
238
        $phpcsFile->addError($error, $stackPtr, $errorCode, $data);
239
240
    }//end addError()
241
242
243
}//end class
244