GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 699b70...879176 )
by Chris
13:23
created

NoIsNullSniff::process()   F

Complexity

Conditions 31
Paths 16401

Size

Total Lines 111
Code Lines 67

Duplication

Lines 20
Ratio 18.02 %

Importance

Changes 0
Metric Value
cc 31
eloc 67
nc 16401
nop 2
dl 20
loc 111
rs 2
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
namespace PSR2R\Sniffs\PHP;
4
5
use PHP_CodeSniffer_File;
6
use PHP_CodeSniffer_Tokens;
7
8
/**
9
 * is_null() should be replaced by === null check.
10
 *
11
 * @author Mark Scherer
12
 * @license MIT
13
 */
14
class NoIsNullSniff extends \PSR2R\Tools\AbstractSniff {
15
16
	/**
17
	 * @inheritDoc
18
	 */
19
	public function register() {
20
		return [T_STRING];
21
	}
22
23
	/**
24
	 * @inheritDoc
25
	 */
26
	public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) {
27
		$wrongTokens = [T_FUNCTION, T_OBJECT_OPERATOR, T_NEW, T_DOUBLE_COLON];
28
29
		$tokens = $phpcsFile->getTokens();
30
31
		$tokenContent = $tokens[$stackPtr]['content'];
32
		if (strtolower($tokenContent) !== 'is_null') {
33
			return;
34
		}
35
36
		$previous = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
37
		if (!$previous || in_array($tokens[$previous]['code'], $wrongTokens)) {
38
			return;
39
		}
40
41
		$openingBraceIndex = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
42
		if (!$openingBraceIndex || $tokens[$openingBraceIndex]['type'] !== 'T_OPEN_PARENTHESIS') {
0 ignored issues
show
Bug Best Practice introduced by
The expression $openingBraceIndex of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
43
			return;
44
		}
45
46
		$closingBraceIndex = $tokens[$openingBraceIndex]['parenthesis_closer'];
47
48
		$error = $tokenContent . '() found, should be strict === null check.';
49
50
		$possibleCastIndex = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
51
		$negated = false;
52
		if ($possibleCastIndex && $tokens[$possibleCastIndex]['code'] === T_BOOLEAN_NOT) {
53
			$negated = true;
54
		}
55
		// We dont want to fix double !!
56
		if ($negated) {
57
			$anotherPossibleCastIndex = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($possibleCastIndex - 1), null, true);
58
			if ($tokens[$anotherPossibleCastIndex]['code'] === T_BOOLEAN_NOT) {
59
				$phpcsFile->addError($error, $stackPtr);
60
				return;
61
			}
62
		}
63
64
		// We don't want to fix stuff with bad inline assignment
65
		if ($this->contains($phpcsFile, 'T_EQUAL', $openingBraceIndex + 1, $closingBraceIndex - 1)) {
66
			$phpcsFile->addError($error, $stackPtr);
67
			return;
68
		}
69
70
		$beginningIndex = $negated ? $possibleCastIndex : $stackPtr;
71
		$endIndex = $closingBraceIndex;
72
73
		$fix = $phpcsFile->addFixableError($error, $stackPtr);
74
		if ($fix) {
75
			$needsBrackets = $this->needsBrackets($phpcsFile, $openingBraceIndex, $closingBraceIndex);
76
			$leadingComparison = $this->hasLeadingComparison($phpcsFile, $beginningIndex);
0 ignored issues
show
Bug introduced by
It seems like $beginningIndex defined by $negated ? $possibleCastIndex : $stackPtr on line 70 can also be of type boolean or double; however, PSR2R\Sniffs\PHP\NoIsNul...:hasLeadingComparison() does only seem to accept integer, 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...
77
			$trailingComparison = $this->hasTrailingComparison($phpcsFile, $closingBraceIndex);
78
79 View Code Duplication
			if ($leadingComparison) {
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...
80
				$possibleBeginningIndex = $this->findUnnecessaryLeadingComparisonStart($phpcsFile, $beginningIndex);
0 ignored issues
show
Bug introduced by
It seems like $beginningIndex defined by $negated ? $possibleCastIndex : $stackPtr on line 70 can also be of type boolean or double; however, PSR2R\Sniffs\PHP\NoIsNul...eadingComparisonStart() does only seem to accept integer, 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...
81
				if ($possibleBeginningIndex !== null) {
82
					$beginningIndex = $possibleBeginningIndex;
83
					$leadingComparison = false;
84
					if ($tokens[$beginningIndex]['code'] === T_FALSE) {
85
						$negated = !$negated;
86
					}
87
				}
88
			}
89
90 View Code Duplication
			if ($trailingComparison) {
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...
91
				$possibleEndIndex = $this->findUnnecessaryLeadingComparisonStart($phpcsFile, $endIndex);
92
				if ($possibleEndIndex !== null) {
93
					$endIndex = $possibleEndIndex;
94
					$trailingComparison = false;
95
					if ($tokens[$endIndex]['code'] === T_FALSE) {
96
						$negated = !$negated;
97
					}
98
				}
99
			}
100
101
			if (!$needsBrackets && ($leadingComparison || $this->leadRequiresBrackets($phpcsFile, $beginningIndex))) {
0 ignored issues
show
Bug introduced by
It seems like $beginningIndex can also be of type boolean or double; however, PSR2R\Sniffs\PHP\NoIsNul...:leadRequiresBrackets() does only seem to accept integer, 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...
102
				$needsBrackets = true;
103
			}
104
			if (!$needsBrackets && $trailingComparison) {
105
				$needsBrackets = true;
106
			}
107
108
			$comparisonString = ' ' . ($negated ? '!' : '=') . '== null';
109
110
			$phpcsFile->fixer->beginChangeset();
111
112
			if ($negated) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
113
				//$phpcsFile->fixer->replaceToken($possibleCastIndex, '');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
114
			}
115
			if ($beginningIndex !== $stackPtr) {
116
				for ($i = $beginningIndex; $i < $stackPtr; $i++) {
117
					$phpcsFile->fixer->replaceToken($i, '');
0 ignored issues
show
Bug introduced by
It seems like $i defined by $i++ on line 116 can also be of type boolean or double; however, PHP_CodeSniffer_Fixer::replaceToken() does only seem to accept integer, 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...
118
				}
119
			}
120
			if ($endIndex !== $closingBraceIndex) {
121
				for ($i = $endIndex; $i > $closingBraceIndex; $i--) {
122
					$phpcsFile->fixer->replaceToken($i, '');
0 ignored issues
show
Bug introduced by
It seems like $i defined by $i-- on line 121 can also be of type boolean or double; however, PHP_CodeSniffer_Fixer::replaceToken() does only seem to accept integer, 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...
123
				}
124
			}
125
126
			$phpcsFile->fixer->replaceToken($stackPtr, '');
127
			if (!$needsBrackets) {
128
				$phpcsFile->fixer->replaceToken($openingBraceIndex, '');
129
				$phpcsFile->fixer->replaceToken($closingBraceIndex, $comparisonString);
130
			} else {
131
				$phpcsFile->fixer->replaceToken($closingBraceIndex, $comparisonString . ')');
132
			}
133
134
			$phpcsFile->fixer->endChangeset();
135
		}
136
	}
137
138
	/**
139
	 * @param \PHP_CodeSniffer_File $phpcsFile
140
	 * @param int $index
141
	 * @return bool
142
	 */
143
	protected function leadRequiresBrackets(PHP_CodeSniffer_File $phpcsFile, $index) {
144
		$tokens = $phpcsFile->getTokens();
145
146
		$previous = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($index - 1), null, true);
147
		if ($this->isCast($phpcsFile, $previous)) {
0 ignored issues
show
Bug introduced by
It seems like $previous defined by $phpcsFile->findPrevious...$index - 1, null, true) on line 146 can also be of type boolean; however, PSR2R\Sniffs\PHP\NoIsNullSniff::isCast() does only seem to accept integer, 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...
148
			return true;
149
		}
150
		if (in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$arithmeticTokens)) {
151
			return true;
152
		}
153
154
		return false;
155
	}
156
157
	/**
158
	 * @param \PHP_CodeSniffer_File $phpcsFile
159
	 * @param int $index
160
	 * @return bool
161
	 */
162
	protected function isCast(PHP_CodeSniffer_File $phpcsFile, $index) {
163
		$tokens = $phpcsFile->getTokens();
0 ignored issues
show
Unused Code introduced by
$tokens is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
164
165
		return in_array($index, PHP_CodeSniffer_Tokens::$castTokens);
166
	}
167
168
	/**
169
	 * @param \PHP_CodeSniffer_File $phpcsFile
170
	 * @param int $index
171
	 * @return int|null
172
	 */
173
	protected function findUnnecessaryLeadingComparisonStart(PHP_CodeSniffer_File $phpcsFile, $index) {
174
		$tokens = $phpcsFile->getTokens();
175
176
		$previous = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($index - 1), null, true);
177 View Code Duplication
		if (!in_array($tokens[$previous]['code'], [T_IS_IDENTICAL, T_IS_NOT_IDENTICAL])) {
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...
178
			return null;
179
		}
180
181
		$previous = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($previous - 1), null, true);
182 View Code Duplication
		if (!in_array($tokens[$previous]['code'], [T_TRUE, T_FALSE])) {
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...
183
			return null;
184
		}
185
186
		return $previous;
187
	}
188
189
	/**
190
	 * @param \PHP_CodeSniffer_File $phpcsFile
191
	 * @param int $index
192
	 * @return int|null
193
	 */
194
	protected function findUnnecessaryTrailingComparisonEnd(PHP_CodeSniffer_File $phpcsFile, $index) {
195
		$tokens = $phpcsFile->getTokens();
196
197
		$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($index + 1), null, true);
198 View Code Duplication
		if (!$next || !in_array($tokens[$next]['code'], [T_IS_IDENTICAL, T_IS_NOT_IDENTICAL])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $next of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
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...
199
			return null;
200
		}
201
202
		$prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($next - 1), null, true);
203 View Code Duplication
		if (!$prev || !in_array($tokens[$prev]['code'], [T_TRUE, T_FALSE])) {
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...
204
			return null;
205
		}
206
207
		return $next;
208
	}
209
210
	/**
211
	 * @param \PHP_CodeSniffer_File $phpcsFile
212
	 * @param int $stackPtr
213
	 * @return bool
214
	 */
215
	protected function hasLeadingComparison(PHP_CodeSniffer_File $phpcsFile, $stackPtr) {
216
		$previous = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
217
		return $this->isComparison($phpcsFile, $previous);
0 ignored issues
show
Bug introduced by
It seems like $previous defined by $phpcsFile->findPrevious...ackPtr - 1, null, true) on line 216 can also be of type boolean; however, PSR2R\Sniffs\PHP\NoIsNullSniff::isComparison() does only seem to accept integer, 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...
218
	}
219
220
	/**
221
	 * @param \PHP_CodeSniffer_File $phpcsFile
222
	 * @param int $stackPtr
223
	 * @return bool
224
	 */
225
	protected function hasTrailingComparison(PHP_CodeSniffer_File $phpcsFile, $stackPtr) {
226
		$tokens = $phpcsFile->getTokens();
0 ignored issues
show
Unused Code introduced by
$tokens is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
227
228
		$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
229
		return $this->isComparison($phpcsFile, $next);
0 ignored issues
show
Security Bug introduced by
It seems like $next defined by $phpcsFile->findNext(\PH...ackPtr + 1, null, true) on line 228 can also be of type false; however, PSR2R\Sniffs\PHP\NoIsNullSniff::isComparison() does only seem to accept integer, 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...
230
	}
231
232
	/**
233
	 * @param \PHP_CodeSniffer_File $phpcsFile
234
	 * @param int $index
235
	 * @return bool
236
	 */
237
	protected function isComparison(PHP_CodeSniffer_File $phpcsFile, $index) {
238
		$tokens = $phpcsFile->getTokens();
239
240
		$blacklistedCodes = [
241
			T_IS_NOT_EQUAL, T_IS_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_GREATER_OR_EQUAL, T_IS_SMALLER_OR_EQUAL
242
		];
243
		$blacklistedTypes = [
244
			'T_LESS_THAN', 'T_GREATER_THAN',
245
		];
246
		if (in_array($tokens[$index]['code'], $blacklistedCodes)) {
247
			return true;
248
		}
249
		if (in_array($tokens[$index]['type'], $blacklistedTypes)) {
250
			return true;
251
		}
252
253
		return false;
254
	}
255
256
}
257