|
1
|
|
|
<?php declare(strict_types = 1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Codor\Sniffs\Syntax; |
|
4
|
|
|
|
|
5
|
|
|
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff; |
|
6
|
|
|
use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File; |
|
7
|
|
|
|
|
8
|
|
|
class NullCoalescingSniff 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_ISSET]; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* The PHP Code Sniffer file. |
|
22
|
|
|
* @var PHP_CodeSniffer_File |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $phpcsFile; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Processes the tokens that this sniff is interested in. |
|
28
|
|
|
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found. |
|
29
|
|
|
* @param integer $stackPtr The position in the stack where |
|
30
|
|
|
* the token was found. |
|
31
|
|
|
* @return void |
|
32
|
|
|
*/ |
|
33
|
|
|
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->phpcsFile = $phpcsFile; |
|
36
|
|
|
$tokens = $phpcsFile->getTokens(); |
|
37
|
|
|
$index = $stackPtr; |
|
38
|
|
|
|
|
39
|
|
|
if ($this->couldBeNullCoalescing($tokens, $index)) { |
|
40
|
|
|
$phpcsFile->addError("Ternary found where Null Coalescing operator will work.", $stackPtr, __CLASS__); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Determines if the current line has a ternary |
|
46
|
|
|
* operator that could be converted to a |
|
47
|
|
|
* null coalescing operator. |
|
48
|
|
|
* @param array $tokens Tokens. |
|
49
|
|
|
* @param integer $index Current index. |
|
50
|
|
|
* @return boolean |
|
51
|
|
|
*/ |
|
52
|
|
|
protected function couldBeNullCoalescing($tokens, $index): bool |
|
53
|
|
|
{ |
|
54
|
|
|
$questionMarkFound = false; |
|
55
|
|
|
$semiColinFound = false; |
|
56
|
|
|
|
|
57
|
|
|
while (true) { |
|
58
|
|
|
if ($tokens[$index]['type'] == 'T_SEMICOLON') { |
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if ($tokens[$index]['type'] == 'T_INLINE_THEN') { |
|
63
|
|
|
$questionMarkFound = true; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if ($tokens[$index]['type'] == 'T_INLINE_ELSE') { |
|
67
|
|
|
$semiColinFound = true; |
|
68
|
|
|
} |
|
69
|
|
|
$index++; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return $questionMarkFound && $semiColinFound; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|