Completed
Push — feature/isClassProperty-additi... ( 286703...879b22 )
by Juliette
01:45
created

RequiredOptionalFunctionParametersSniff::process()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 26
nc 6
nop 2
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
        'preg_match_all' => array(
43
            2 => array(
44
                'name' => 'matches',
45
                '5.3'  => true,
46
                '5.4'  => false,
47
            ),
48
        ),
49
        'stream_socket_enable_crypto' => array(
50
            2 => array(
51
                'name' => 'crypto_type',
52
                '5.5'  => true,
53
                '5.6'  => false,
54
            ),
55
        ),
56
    );
57
58
59
    /**
60
     * Returns an array of tokens this test wants to listen for.
61
     *
62
     * @return array
63
     */
64
    public function register()
65
    {
66
        // Handle case-insensitivity of function names.
67
        $this->functionParameters = $this->arrayKeysToLowercase($this->functionParameters);
68
69
        return array(T_STRING);
70
    }//end register()
71
72
    /**
73
     * Processes this test, when one of its tokens is encountered.
74
     *
75
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
76
     * @param int                   $stackPtr  The position of the current token in
77
     *                                         the stack passed in $tokens.
78
     *
79
     * @return void
80
     */
81
    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
82
    {
83
        $tokens = $phpcsFile->getTokens();
84
85
        $ignore = array(
86
            T_DOUBLE_COLON,
87
            T_OBJECT_OPERATOR,
88
            T_FUNCTION,
89
            T_CONST,
90
        );
91
92
        $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
93
        if (in_array($tokens[$prevToken]['code'], $ignore) === true) {
94
            // Not a call to a PHP function.
95
            return;
96
        }
97
98
        $function   = $tokens[$stackPtr]['content'];
99
        $functionLc = strtolower($function);
100
101
        if (isset($this->functionParameters[$functionLc]) === false) {
102
            return;
103
        }
104
105
        $parameterCount  = $this->getFunctionCallParameterCount($phpcsFile, $stackPtr);
106
        $openParenthesis = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
107
108
        // If the parameter count returned > 0, we know there will be valid open parenthesis.
109
        if ($parameterCount === 0 && $tokens[$openParenthesis]['code'] !== T_OPEN_PARENTHESIS) {
110
            return;
111
        }
112
113
        $parameterOffsetFound = $parameterCount - 1;
114
115
        foreach ($this->functionParameters[$functionLc] as $offset => $parameterDetails) {
116
            if ($offset > $parameterOffsetFound) {
117
                $itemInfo = array(
118
                    'name'   => $function,
119
                    'nameLc' => $functionLc,
120
                    'offset' => $offset,
121
                );
122
                $this->handleFeature($phpcsFile, $openParenthesis, $itemInfo);
123
            }
124
        }
125
126
    }//end process()
127
128
129
    /**
130
     * Determine whether an error/warning should be thrown for an item based on collected information.
131
     *
132
     * @param array $errorInfo Detail information about an item.
133
     *
134
     * @return bool
135
     */
136
    protected function shouldThrowError(array $errorInfo)
137
    {
138
        return ($errorInfo['requiredVersion'] !== '');
139
    }
140
141
142
    /**
143
     * Get the relevant sub-array for a specific item from a multi-dimensional array.
144
     *
145
     * @param array $itemInfo Base information about the item.
146
     *
147
     * @return array Version and other information about the item.
148
     */
149
    public function getItemArray(array $itemInfo)
150
    {
151
        return $this->functionParameters[$itemInfo['nameLc']][$itemInfo['offset']];
152
    }
153
154
155
    /**
156
     * Get an array of the non-PHP-version array keys used in a sub-array.
157
     *
158
     * @return array
159
     */
160
    protected function getNonVersionArrayKeys()
161
    {
162
        return array('name');
163
    }
164
165
166
    /**
167
     * Retrieve the relevant detail (version) information for use in an error message.
168
     *
169
     * @param array $itemArray Version and other information about the item.
170
     * @param array $itemInfo  Base information about the item.
171
     *
172
     * @return array
173
     */
174 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...
175
    {
176
        $errorInfo = array(
177
            'paramName'       => '',
178
            'requiredVersion' => '',
179
        );
180
181
        $versionArray = $this->getVersionArray($itemArray);
182
183
        if (empty($versionArray) === false) {
184
            foreach ($versionArray as $version => $required) {
185
                if ($required === true && $this->supportsBelow($version) === true) {
186
                    $errorInfo['requiredVersion'] = $version;
187
                }
188
            }
189
        }
190
191
        $errorInfo['paramName'] = $itemArray['name'];
192
193
        return $errorInfo;
194
195
    }//end getErrorInfo()
196
197
198
    /**
199
     * Get the error message template for this sniff.
200
     *
201
     * @return string
202
     */
203
    protected function getErrorMsgTemplate()
204
    {
205
        return 'The "%s" parameter for function %s() is missing, but was required for PHP version %s and lower';
206
    }
207
208
209
    /**
210
     * Generates the error or warning for this item.
211
     *
212
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
213
     * @param int                   $stackPtr  The position of the relevant token in
214
     *                                         the stack.
215
     * @param array                 $itemInfo  Base information about the item.
216
     * @param array                 $errorInfo Array with detail (version) information
217
     *                                         relevant to the item.
218
     *
219
     * @return void
220
     */
221
    public function addError(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, array $itemInfo, array $errorInfo)
222
    {
223
        $error     = $this->getErrorMsgTemplate();
224
        $errorCode = $this->stringToErrorCode($itemInfo['name'].'_'.$errorInfo['paramName']).'Missing';
225
        $data      = array(
226
            $errorInfo['paramName'],
227
            $itemInfo['name'],
228
            $errorInfo['requiredVersion'],
229
        );
230
231
        $phpcsFile->addError($error, $stackPtr, $errorCode, $data);
232
233
    }//end addError()
234
235
236
}//end class
237