Completed
Push — master ( ce2ac5...a32632 )
by Juliette
10s
created

ForbiddenNamesAsDeclaredSniff   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 160
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 3
dl 10
loc 160
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 11 1
D process() 10 96 25

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * PHPCompatibility_Sniffs_PHP_ForbiddenNamesAsDeclaredClassSniff.
4
 *
5
 * PHP version 7
6
 *
7
 * @category PHP
8
 * @package  PHPCompatibility
9
 * @author   Juliette Reinders Folmer <[email protected]>
10
 */
11
12
/**
13
 * PHPCompatibility_Sniffs_PHP_ForbiddenNamesAsDeclaredClassSniff.
14
 *
15
 * Prohibits the use of some reserved keywords to name a class, interface, trait or namespace.
16
 *
17
 * @see http://php.net/manual/en/reserved.other-reserved-words.php
18
 *
19
 * PHP version 7
20
 *
21
 * @category PHP
22
 * @package  PHPCompatibility
23
 * @author   Juliette Reinders Folmer <[email protected]>
24
 */
25
class PHPCompatibility_Sniffs_PHP_ForbiddenNamesAsDeclaredSniff extends PHPCompatibility_Sniff
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
26
{
27
28
    /**
29
     * List of tokens which can not be used as class, interface, trait names or as part of a namespace.
30
     *
31
     * @var array
32
     */
33
    protected $forbiddenTokens = array(
34
        T_NULL  => '7.0',
35
        T_TRUE  => '7.0',
36
        T_FALSE => '7.0'
37
    );
38
39
    /**
40
     * T_STRING keywords to recognize as forbidden names.
41
     *
42
     * @var array
43
     */
44
    protected $forbiddenNames = array(
45
        'null'     => '7.0',
46
        'true'     => '7.0',
47
        'false'    => '7.0',
48
        'bool'     => '7.0',
49
        'int'      => '7.0',
50
        'float'    => '7.0',
51
        'string'   => '7.0',
52
        'resource' => '7.0',
53
        'object'   => '7.0',
54
        'mixed'    => '7.0',
55
        'numeric'  => '7.0',
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
        return array(
67
            T_CLASS,
68
            T_INTERFACE,
69
            T_NAMESPACE,
70
            T_TRAIT,
71
            T_STRING, // Compat for PHPCS 1.x and PHP < 5.3.
72
        );
73
74
    }//end register()
75
76
77
    /**
78
     * Processes this test, when one of its tokens is encountered.
79
     *
80
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
81
     * @param int                  $stackPtr  The position of the current token in the
82
     *                                        stack passed in $tokens.
83
     *
84
     * @return void
85
     */
86
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
87
    {
88
        $tokens         = $phpcsFile->getTokens();
89
        $tokenCode      = $tokens[$stackPtr]['code'];
90
        $tokenContentLc = strtolower($tokens[$stackPtr]['content']);
91
92
        // For string tokens we only care about 'trait' and 'namespace' as those are
93
        // the only ones which may not be correctly recognized as it's own token.
94
        // This only happens in older versions of PHP where the token doesn't exist yet as a keyword.
95
        if ($tokenCode === T_STRING && ($tokenContentLc !== 'trait' && $tokenContentLc !== 'namespace')) {
96
            return;
97
        }
98
99
        if (in_array($tokenCode, array(T_CLASS, T_INTERFACE, T_TRAIT), true)) {
100
            // Check for the declared name being a name which is not tokenized as T_STRING.
101
            $nextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
102
            if ($nextNonEmpty !== false && isset($this->forbiddenTokens[$tokens[$nextNonEmpty]['code']]) === true) {
103
                $name = $tokens[$nextNonEmpty]['content'];
104
            } else {
105
                // Get the declared name if it's a T_STRING.
106
                $name = $phpcsFile->getDeclarationName($stackPtr);
107
            }
108
            unset($nextNonEmpty);
109
110
            if (isset($name) === false || is_string($name) === false || $name === '') {
111
                return;
112
            }
113
114
            $nameLc = strtolower($name);
115
            if (isset($this->forbiddenNames[$nameLc]) === false) {
116
                return;
117
            }
118
119
        } else if ($tokenCode === T_NAMESPACE) {
120
            $namespaceName = $this->getDeclaredNamespaceName($phpcsFile, $stackPtr);
121
122
            if ($namespaceName === false || $namespaceName === '') {
123
                return;
124
            }
125
126
            $namespaceParts = explode('\\', $namespaceName);
127
            foreach ($namespaceParts as $namespacePart) {
128
                $partLc = strtolower($namespacePart);
129
                if (isset($this->forbiddenNames[$partLc]) === true) {
130
                    $name   = $namespacePart;
131
                    $nameLc = $partLc;
132
                    break;
133
                }
134
            }
135
        } else if ($tokenCode === T_STRING) {
136
            // Traits and namespaces which are not yet tokenized as T_TRAIT/T_NAMESPACE.
137
            $nextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
138
            if ($nextNonEmpty === false) {
139
                return;
140
            }
141
142
            $nextNonEmptyCode = $tokens[$nextNonEmpty]['code'];
143
144
			if ($nextNonEmptyCode !== T_STRING && isset($this->forbiddenTokens[$nextNonEmptyCode]) === true) {
145
                $name   = $tokens[$nextNonEmpty]['content'];
146
                $nameLc = strtolower($tokens[$nextNonEmpty]['content']);
147
            } else if ($nextNonEmptyCode === T_STRING) {
148
				$endOfStatement = $phpcsFile->findNext(array(T_SEMICOLON, T_OPEN_CURLY_BRACKET), ($stackPtr + 1));
149
150
				do {
151
					$nextNonEmptyLc = strtolower($tokens[$nextNonEmpty]['content']);
152
153
	                if (isset($this->forbiddenNames[$nextNonEmptyLc]) === true) {
154
	                    $name   = $tokens[$nextNonEmpty]['content'];
155
	                    $nameLc = $nextNonEmptyLc;
156
	                    break;
157
	                }
158
	                
159
	                $nextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($nextNonEmpty + 1), $endOfStatement, true);
0 ignored issues
show
Security Bug introduced by
It seems like $endOfStatement defined by $phpcsFile->findNext(arr...RACKET), $stackPtr + 1) on line 148 can also be of type false; however, PHP_CodeSniffer_File::findNext() does only seem to accept integer|null, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
160
				} while ($nextNonEmpty !== false);
161
            }
162
            unset($nextNonEmptyCode, $nextNonEmptyLc, $endOfStatement);
163
        }
164
165
        if (isset($name, $nameLc) === false) {
166
            return;
167
        }
168
169
        // Still here, so this is one of the reserved words.
170
        $version = $this->forbiddenNames[$nameLc];
0 ignored issues
show
Bug introduced by
The variable $nameLc does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
171 View Code Duplication
        if ($this->supportsAbove($version) === true) {
1 ignored issue
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...
172
            $error = "'%s' is a reserved keyword as of PHP version %s and cannot be used to name a class, interface or trait or as part of a namespace (%s)";
173
            $data  = array(
174
                $nameLc,
175
                $version,
176
                $tokens[$stackPtr]['type'],
177
            );
178
179
            $phpcsFile->addError($error, $stackPtr, 'Found', $data);
180
        }
181
    }//end process()
182
183
184
}//end class
185