Completed
Push — master ( b20aa8...624e97 )
by Alexander
01:58
created

FunctionCommentSniff::checkShort()   C

Complexity

Conditions 12
Paths 36

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 12
Metric Value
dl 0
loc 32
ccs 26
cts 26
cp 1
rs 5.1612
cc 12
eloc 20
nc 36
nop 4
crap 12

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 1
        $return = null;
63 1
        foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
64 1
            if ($tokens[$tag]['content'] === '@return') {
65 1
                $return = $tag;
66 1
                break;
67
            }
68 1
        }
69
70 1
        if ($return !== null) {
71 1
            $returnType = $tokens[($return + 2)]['content'];
72 1
            if ($returnType === '$this') {
73 1
                $error = 'Function return type "%s" is invalid, please use "static" or "self" instead';
74 1
                $data  = array($returnType);
75 1
                $phpcsFile->addError($error, $return, 'InvalidThisReturn', $data);
76 1
            }
77 1
        }
78
79
        $empty = array(
80 1
                  T_DOC_COMMENT_WHITESPACE,
81 1
                  T_DOC_COMMENT_STAR,
82 1
                 );
83
84 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...
85 1
        if ($short === false || $tokens[$short]['code'] !== T_DOC_COMMENT_STRING) {
86 1
            return;
87
        }
88
89 1
        $this->checkShort($phpcsFile, $stackPtr, $tokens[$short]['content'], $short);
90
91 1
    }//end process()
92
93
94
    /**
95
     * Process the short description of a function comment.
96
     *
97
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
98
     * @param int                  $stackPtr  The position of the function token
99
     *                                        in the stack passed in $tokens.
100
     * @param string               $short     The content of the short description.
101
     * @param int                  $errorPos  The position where an error should be thrown.
102
     *
103
     * @return void
104
     */
105 1
    public function checkShort(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $short, $errorPos)
106
    {
107 1
        $tokens = $phpcsFile->getTokens();
108
109 1
        $classToken = null;
110 1
        foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condition) {
111 1
            if ($condition === T_CLASS || $condition === T_INTERFACE || $condition === T_TRAIT) {
112 1
                $classToken = $condPtr;
113 1
                break;
114
            }
115 1
        }
116
117 1
        $isEvent = false;
118 1
        if ($classToken !== null) {
119 1
            $className = $phpcsFile->getDeclarationName($classToken);
120 1
            if (strpos($className, 'EventHandler') !== false) {
121 1
                $methodName = $phpcsFile->getDeclarationName($stackPtr);
122 1
                if (substr($methodName, 0, 2) === 'On') {
123 1
                    $isEvent = true;
124 1
                }
125 1
            }
126 1
        }
127
128 1
        if ($isEvent === true && preg_match('/(\p{Lu}|\[)/u', $short[0]) === 0) {
129 1
            $error = 'Event comment short description must start with a capital letter or an [';
130 1
            $phpcsFile->addError($error, $errorPos, 'EventShortNotCapital');
131 1
        } else if ($isEvent === false && preg_match('/\p{Lu}/u', $short[0]) === 0) {
132 1
            $error = 'Doc comment short description must start with a capital letter';
133 1
            $phpcsFile->addError($error, $errorPos, 'NonEventShortNotCapital');
134 1
        }
135
136 1
    }//end checkShort()
137
138
139
    /**
140
     * Process any throw tags that this function comment has.
141
     *
142
     * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
143
     * @param int                  $stackPtr     The position of the current token
144
     *                                           in the stack passed in $tokens.
145
     * @param int                  $commentStart The position in the stack where the comment started.
146
     *
147
     * @return void
148
     */
149 1
    protected function processThrows(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
150
    {
151 1
        parent::processThrows($phpcsFile, $stackPtr, $commentStart);
152
153 1
        $tokens = $phpcsFile->getTokens();
154
155 1
        foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
156 1
            if ($tokens[$tag]['content'] !== '@throws') {
157 1
                continue;
158
            }
159
160 1
            $throwPtr = $phpcsFile->findNext(
161 1
                T_THROW,
162 1
                $tokens[$stackPtr]['scope_opener'],
163 1
                $tokens[$stackPtr]['scope_closer']
164 1
            );
165
166 1
            if ($throwPtr !== false) {
167 1
                break;
168
            }
169
170 1
            $throwsWithString = null;
171 1
            $error            = '@throws tag found, but no exceptions are thrown by the function';
172
173 1
            if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
174 1
                $throwsWithString = true;
175 1
            } elseif ($tokens[($tag + 1)]['code'] === T_DOC_COMMENT_WHITESPACE
176 1
                && $tokens[($tag + 1)]['content'] === $phpcsFile->eolChar
177 1
            ) {
178 1
                $throwsWithString = false;
179 1
            }
180
181 1
            if ($tokens[($tag - 2)]['code'] === T_DOC_COMMENT_STAR && isset($throwsWithString) === true) {
182 1
                $fix = $phpcsFile->addFixableError($error, $tag, 'ExcessiveThrows');
183
184 1
                if ($fix === true) {
185 1
                    $phpcsFile->fixer->beginChangeset();
186
187 1
                    $removeEndPtr = $throwsWithString === true ? ($tag + 3) : ($tag + 1);
188
189 1
                    for ($i = ($tag - 4); $i < $removeEndPtr; $i++) {
190 1
                        $phpcsFile->fixer->replaceToken($i, '');
191 1
                    }
192
193 1
                    $phpcsFile->fixer->endChangeset();
194 1
                }
195 1
            } else {
196
                $phpcsFile->addError($error, $tag, 'ExcessiveThrows');
197
            }
198 1
        }//end foreach
199
200 1
    }//end processThrows()
201
202
}//end class
203