Completed
Push — master ( 7cb383...bf8a98 )
by Alexander
02:20
created

FunctionCommentSniff::processParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 6
rs 9.9666
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 34 and the first side effect is on line 17.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * CodingStandard_Sniffs_Commenting_FunctionCommentSniff.
4
 *
5
 * PHP version 5
6
 *
7
 * @category PHP
8
 * @package  PHP_CodeSniffer
9
 * @author   Greg Sherwood <[email protected]>
10
 * @author   Alexander Obuhovich <[email protected]>
11
 * @license  https://github.com/aik099/CodingStandard/blob/master/LICENSE BSD 3-Clause
12
 * @link     https://github.com/aik099/CodingStandard
13
 */
14
15
// @codeCoverageIgnoreStart
16
if (class_exists('Squiz_Sniffs_Commenting_FunctionCommentSniff', true) === false) {
17
    $error = 'Class Squiz_Sniffs_Commenting_FunctionCommentSniff not found';
18
    throw new PHP_CodeSniffer_Exception($error);
19
}
20
// @codeCoverageIgnoreEnd
21
22
/**
23
 * Parses and verifies the doc comments for functions.
24
 *
25
 * Same as the Squiz standard, but adds support for API tags.
26
 *
27
 * @category PHP
28
 * @package  PHP_CodeSniffer
29
 * @author   Greg Sherwood <[email protected]>
30
 * @author   Alexander Obuhovich <[email protected]>
31
 * @license  https://github.com/aik099/CodingStandard/blob/master/LICENSE BSD 3-Clause
32
 * @link     https://github.com/aik099/CodingStandard
33
 */
34
class CodingStandard_Sniffs_Commenting_FunctionCommentSniff extends Squiz_Sniffs_Commenting_FunctionCommentSniff
0 ignored issues
show
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
35
{
36
37
38
    /**
39
     * Processes this test, when one of its tokens is encountered.
40
     *
41
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
42
     * @param int                  $stackPtr  The position of the current token
43
     *                                        in the stack passed in $tokens.
44
     *
45
     * @return void
46
     */
47
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
48
    {
49
        parent::process($phpcsFile, $stackPtr);
50
51
        $tokens = $phpcsFile->getTokens();
52
        $find   = PHP_CodeSniffer_Tokens::$methodPrefixes;
53
        $find[] = T_WHITESPACE;
54
55
        $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true);
56
        if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG) {
57
            return;
58
        }
59
60
        $commentStart = $tokens[$commentEnd]['comment_opener'];
61
62
        $empty = array(
63
                  T_DOC_COMMENT_WHITESPACE,
64
                  T_DOC_COMMENT_STAR,
65
                 );
66
67
        $short = $phpcsFile->findNext($empty, ($commentStart + 1), $commentEnd, true);
0 ignored issues
show
Bug introduced by
It seems like $commentEnd defined by $phpcsFile->findPrevious...ackPtr - 1, null, true) on line 55 can also be of type boolean; however, PHP_CodeSniffer_File::findNext() does only seem to accept integer|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
68
        if ($short === false || $tokens[$short]['code'] !== T_DOC_COMMENT_STRING) {
69
            return;
70
        }
71
72
        if ($this->isInheritDoc($phpcsFile, $commentStart) === true) {
73
            return;
74
        }
75
76
        $this->checkShort($phpcsFile, $stackPtr, $tokens[$short]['content'], $short);
77
78
    }//end process()
79
80
    /**
81
     * Process the function parameter comments.
82
     *
83
     * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
84
     * @param int                  $stackPtr     The position of the current token
85
     *                                           in the stack passed in $tokens.
86
     * @param int                  $commentStart The position in the stack where the comment started.
87
     *
88
     * @return void
89
     */
90
    protected function processParams(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
91
    {
92
        if ($this->isInheritDoc($phpcsFile, $commentStart) === true) {
93
            return;
94
        }
95
96
        parent::processParams($phpcsFile, $stackPtr, $commentStart);
97
98
    }//end processParams()
99
100
101
    /**
102
     * Process the return comment of this function comment.
103
     *
104
     * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
105
     * @param int                  $stackPtr     The position of the current token
106
     *                                           in the stack passed in $tokens.
107
     * @param int                  $commentStart The position in the stack where the comment started.
108
     *
109
     * @return void
110
     */
111
    protected function processReturn(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
112
    {
113
        if ($this->isInheritDoc($phpcsFile, $commentStart) === true) {
114
            return;
115
        }
116
117
        parent::processReturn($phpcsFile, $stackPtr, $commentStart);
118
119
        $return = null;
120
        $tokens = $phpcsFile->getTokens();
121
122
        foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
123
            if ($tokens[$tag]['content'] === '@return') {
124
                $return = $tag;
125
                break;
126
            }
127
        }
128
129
        if ($return !== null) {
130
            $returnType = $tokens[($return + 2)]['content'];
131
            if ($returnType === '$this') {
132
                $error = 'Function return type "%s" is invalid, please use "static" or "self" instead';
133
                $data  = array($returnType);
134
                $phpcsFile->addError($error, $return, 'InvalidThisReturn', $data);
135
            }
136
        }
137
138
    }//end processReturn()
139
140
    /**
141
     * Process the short description of a function comment.
142
     *
143
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
144
     * @param int                  $stackPtr  The position of the function token
145
     *                                        in the stack passed in $tokens.
146
     * @param string               $short     The content of the short description.
147
     * @param int                  $errorPos  The position where an error should be thrown.
148
     *
149
     * @return void
150
     */
151
    public function checkShort(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $short, $errorPos)
152
    {
153
        $tokens = $phpcsFile->getTokens();
154
155
        $classToken = null;
156
        foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condition) {
157
            if ($condition === T_CLASS || $condition === T_INTERFACE || $condition === T_TRAIT) {
158
                $classToken = $condPtr;
159
                break;
160
            }
161
        }
162
163
        $isEvent = false;
164
        if ($classToken !== null) {
165
            $className = $phpcsFile->getDeclarationName($classToken);
166
            if (strpos($className, 'EventHandler') !== false) {
167
                $methodName = $phpcsFile->getDeclarationName($stackPtr);
168
                if (substr($methodName, 0, 2) === 'On') {
169
                    $isEvent = true;
170
                }
171
            }
172
        }
173
174
        if ($isEvent === true && preg_match('/(\p{Lu}|\[)/u', $short[0]) === 0) {
175
            $error = 'Event comment short description must start with a capital letter or an [';
176
            $phpcsFile->addError($error, $errorPos, 'EventShortNotCapital');
177
        } else if ($isEvent === false && preg_match('/\p{Lu}/u', $short[0]) === 0) {
178
            $error = 'Doc comment short description must start with a capital letter';
179
            $phpcsFile->addError($error, $errorPos, 'NonEventShortNotCapital');
180
        }
181
182
    }//end checkShort()
183
184
185
    /**
186
     * Process any throw tags that this function comment has.
187
     *
188
     * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
189
     * @param int                  $stackPtr     The position of the current token
190
     *                                           in the stack passed in $tokens.
191
     * @param int                  $commentStart The position in the stack where the comment started.
192
     *
193
     * @return void
194
     */
195
    protected function processThrows(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
196
    {
197
        parent::processThrows($phpcsFile, $stackPtr, $commentStart);
198
199
        $tokens = $phpcsFile->getTokens();
200
201
        foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
202
            // Only process method with scope (e.g. non-abstract methods or methods on the interface).
203
            if ($tokens[$tag]['content'] !== '@throws' || isset($tokens[$stackPtr]['scope_opener']) === false) {
204
                continue;
205
            }
206
207
            $throwPtr = $phpcsFile->findNext(
208
                T_THROW,
209
                $tokens[$stackPtr]['scope_opener'],
210
                $tokens[$stackPtr]['scope_closer']
211
            );
212
213
            if ($throwPtr !== false) {
214
                break;
215
            }
216
217
            $throwsWithString = null;
218
            $error            = '@throws tag found, but no exceptions are thrown by the function';
219
220
            if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
221
                $throwsWithString = true;
222
            } elseif ($tokens[($tag + 1)]['code'] === T_DOC_COMMENT_WHITESPACE
223
                && $tokens[($tag + 1)]['content'] === $phpcsFile->eolChar
224
            ) {
225
                $throwsWithString = false;
226
            }
227
228
            if ($tokens[($tag - 2)]['code'] === T_DOC_COMMENT_STAR && isset($throwsWithString) === true) {
229
                $fix = $phpcsFile->addFixableError($error, $tag, 'ExcessiveThrows');
230
231
                if ($fix === true) {
232
                    $phpcsFile->fixer->beginChangeset();
233
234
                    $removeEndPtr = $throwsWithString === true ? ($tag + 3) : ($tag + 1);
235
236
                    for ($i = ($tag - 4); $i < $removeEndPtr; $i++) {
237
                        $phpcsFile->fixer->replaceToken($i, '');
238
                    }
239
240
                    $phpcsFile->fixer->endChangeset();
241
                }
242
            } else {
243
                $phpcsFile->addError($error, $tag, 'ExcessiveThrows');
244
            }
245
        }//end foreach
246
247
    }//end processThrows()
248
249
250
    /**
251
     * Is the comment an inheritdoc?
252
     *
253
     * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
254
     * @param int                  $commentStart The position in the stack where the comment started.
255
     *
256
     * @return bool
257
     */
258
    protected function isInheritDoc(PHP_CodeSniffer_File $phpcsFile, $commentStart)
259
    {
260
        $tokens = $phpcsFile->getTokens();
261
262
        $commentEnd = $tokens[$commentStart]['comment_closer'];
263
        $commentText = $phpcsFile->getTokensAsString($commentStart, ($commentEnd - $commentStart + 1));
264
265
        return stripos($commentText, '{@inheritdoc}') !== false;
266
267
    }// end isInheritDoc()
268
269
}//end class
270