1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Codor\Sniffs\Files; |
4
|
|
|
|
5
|
|
|
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff; |
6
|
|
|
use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File; |
7
|
|
|
|
8
|
|
|
class ReturnNullSniff implements PHP_CodeSniffer_Sniff |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Returns the token types that this sniff is interested in. |
13
|
|
|
* @return array |
14
|
|
|
*/ |
15
|
|
|
public function register(): array |
16
|
|
|
{ |
17
|
|
|
return [T_RETURN]; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Processes the tokens that this sniff is interested in. |
22
|
|
|
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found. |
23
|
|
|
* @param integer $stackPtr The position in the stack where |
24
|
|
|
* the token was found. |
25
|
|
|
* @return void |
26
|
|
|
*/ |
27
|
|
|
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
28
|
|
|
{ |
29
|
|
|
$tokens = $phpcsFile->getTokens(); |
30
|
|
|
$returnTokenIndex = $stackPtr; |
31
|
|
|
|
32
|
|
|
$scope = array_slice($tokens, $returnTokenIndex, null, true); |
33
|
|
|
$semicolons = array_filter($scope, function ($token) { |
34
|
|
|
return $token['type'] === 'T_SEMICOLON'; |
35
|
|
|
}); |
36
|
|
|
|
37
|
|
|
$returnValueIndex = key($semicolons) - 1; |
38
|
|
|
$comparisonIndex = key($semicolons) - 3; |
39
|
|
|
|
40
|
|
|
if ($scope[$returnValueIndex]['type'] === 'T_NULL' && $this->isComparisonType($scope[$comparisonIndex]['type']) === false) { |
41
|
|
|
$error = "Return null value found."; |
42
|
|
|
$phpcsFile->addError($error, $returnValueIndex, __CLASS__); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function isComparisonType(string $type) : bool |
47
|
|
|
{ |
48
|
|
|
return in_array($type, ['T_IS_NOT_IDENTICAL', 'T_IS_IDENTICAL', 'T_IS_NOT_EQUAL', 'T_IS_EQUAL'], true); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|