Completed
Push — master ( c451af...7f12c1 )
by Alexander
02:26
created

FunctionCommentSniff::processParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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