ValidMethodNameSniff::processTokenWithinScope()   C
last analyzed

Complexity

Conditions 14
Paths 12

Size

Total Lines 74
Code Lines 44

Duplication

Lines 9
Ratio 12.16 %

Importance

Changes 0
Metric Value
cc 14
eloc 44
nc 12
nop 3
dl 9
loc 74
rs 5.3785
c 0
b 0
f 0

How to fix   Long Method    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
2
/**
3
 * CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PHP_CodeSniffer
9
 * @author    Thomas Ernest <[email protected]>
10
 * @copyright 2010 Thomas Ernest
11
 * @license   http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
12
 * @link      http://pear.php.net/package/PHP_CodeSniffer
13
 */
14
/**
15
 * CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
16
 *
17
 * Ensures that class methods and functions areentirely lowercased and that
18
 * words are separated with an underscore, and not CamelCased.
19
 * Ensures that private class methods are prefixed with an underscore and that
20
 * all other methods are not prefixed with an underscored.
21
 * Ensures that names longer than 50 chars are prohibited. Likewise names longer
22
 * than 35 chars raise a warning.
23
 *
24
 * @todo Use a rule property or a configuration variable to allow users to set
25
 * their own maximum lengths for function and method names. Have a look at
26
 * CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff and application root.
27
 *
28
 * @category  PHP
29
 * @package   PHP_CodeSniffer
30
 * @author    Thomas Ernest <[email protected]>
31
 * @copyright 2010 Thomas Ernest
32
 * @license   http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
33
 * @link      http://pear.php.net/package/PHP_CodeSniffer
34
 */
35
36
namespace CodeIgniter\Sniffs\NamingConventions;
37
38
use PHP_CodeSniffer\Sniffs\AbstactScopeSniff;
39
use PHP_CodeSniffer\Files\File;
40
41
class ValidMethodNameSniff extends AbstractScopeSniff
42
{
43
    /**
44
     * A list of all PHP magic methods.
45
     *
46
     * @var array
47
     */
48
    protected static $magicMethods = array(
49
                               'construct',
50
                               'destruct',
51
                               'call',
52
                               'callStatic',
53
                               'get',
54
                               'set',
55
                               'isset',
56
                               'unset',
57
                               'sleep',
58
                               'wakeup',
59
                               'toString',
60
                               'set_state',
61
                               'clone',
62
                              );
63
64
    /**
65
     * Defines which token(s) in which scope(s) will be proceed.
66
     */
67
    public function __construct()
68
    {
69
        parent::__construct(array(T_CLASS, T_INTERFACE), array(T_FUNCTION), true);
70
71
    }//end __construct()
72
73
74
    /**
75
     * Processes the tokens within the scope.
76
     *
77
     * @param File $phpcsFile The file being processed.
78
     * @param int                  $stackPtr  The position where this token was
79
     *                                        found.
80
     * @param int                  $currScope The position of the current scope.
81
     *
82
     * @return void
83
     */
84
    protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope)
85
    {
86
        $methodName = $phpcsFile->getDeclarationName($stackPtr);
87
        if ($methodName === null) {
88
            // Ignore closures.
89
            return;
90
        }
91
92
        $className  = $phpcsFile->getDeclarationName($currScope);
93
94
        // Is this a magic method i.e. is prefixed with "__".
95
        if (0 === strcmp(substr($methodName, 0, 2), '__')) {
96
            $magicPart = substr($methodName, 2);
97
            if (in_array($magicPart, self::$magicMethods) === false) {
98
                 $error = "Method name \"$className::$methodName\" is invalid; only PHP magic methods should be prefixed with a double underscore";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
99
                 $phpcsFile->addError($error, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
100
            }
101
102
            return;
103
        }
104
105
        // PHP4 constructors are allowed to break our rules.
106
        if ($methodName === $className) {
107
            return;
108
        }
109
110
        // PHP4 destructors are allowed to break our rules.
111
        if ($methodName === '_'.$className) {
112
            return;
113
        }
114
115
        if (0 !== strcmp($methodName, strtolower($methodName))) {
116
            $uscrdMethodName = preg_replace('/([A-Z])/', '_${1}', $methodName);
117
            $expectedMethodName = strtolower($uscrdMethodName);
118
            $error = "Class methods should be entirely lowercased. Please consider \"$expectedMethodName\" instead of \"$methodName\".";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 136 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
119
            $phpcsFile->addError($error, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
120
            return;
121
        }
122
123
        $methodProps    = $phpcsFile->getMethodProperties($stackPtr);
124
        $scope          = $methodProps['scope'];
125
        $scopeSpecified = $methodProps['scope_specified'];
126
127
        // If it's a private method, it must have an underscore on the front.
128
        if ($scope === 'private' && $methodName{0} !== '_') {
129
            $error = "Private method name \"$className::$methodName\" must be prefixed with an underscore";
130
            $phpcsFile->addError($error, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
131
            return;
132
        }
133
134
        // If it's not a private method, it must not have an underscore on the front.
135 View Code Duplication
        if ($scope !== 'private' && $methodName{0} === '_') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
136
            if (true === $scopeSpecified) {
137
                $error = "Public method name \"$className::$methodName\" must not be prefixed with an underscore";
138
            } else {
139
                $error = ucfirst($scope)." method name \"$className::$methodName\" must not be prefixed with an underscore";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
140
            }
141
            $phpcsFile->addError($error, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
142
            return;
143
        }
144
145
        // If name is too verbose,
146
        // then either an error or a warning is displayed.
147
        $error_limit = 50;
148
        $warning_limit = 35;
149
        if (strlen($methodName) > $error_limit) {
150
            $error = "Overly long and verbose names are prohibited. Please find a name shorter than $error_limit chars.";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
151
            $phpcsFile->addError($error, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
152
            return;
153
        } else if (strlen($methodName) > $warning_limit) {
154
            $warning = "Try to avoid overly long and verbose names in finding a name shorter than $warning_limit chars.";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
155
            $phpcsFile->addWarning($warning, $stackPtr);
0 ignored issues
show
Bug introduced by
The call to addWarning() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
156
        }
157
    }//end processTokenWithinScope()
158
159
}//end class
160
161
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
162