1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Medvedev Alexandr https://github.com/lexty <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace PHPSA\Analyzer\Pass\Expression; |
7
|
|
|
|
8
|
|
|
use PhpParser\Node\Expr\BooleanNot; |
9
|
|
|
use PHPSA\Analyzer\Helper\DefaultMetadataPassTrait; |
10
|
|
|
use PHPSA\Analyzer\Pass\AnalyzerPassInterface; |
11
|
|
|
use PHPSA\Context; |
12
|
|
|
|
13
|
|
|
class LogicInversion implements AnalyzerPassInterface |
14
|
|
|
{ |
15
|
|
|
use DefaultMetadataPassTrait; |
16
|
|
|
|
17
|
|
|
const DESCRIPTION = 'Checks for Logic inversion like `if (!($a == $b))` and suggests the correct operator.'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $map = [ |
23
|
|
|
'Expr_BinaryOp_Equal' => ['!=', '=='], |
24
|
|
|
'Expr_BinaryOp_NotEqual' => ['==', '!='], |
25
|
|
|
'Expr_BinaryOp_Identical' => ['===', '!=='], |
26
|
|
|
'Expr_BinaryOp_NotIdentical' => ['!==', '==='], |
27
|
|
|
'Expr_BinaryOp_Greater' => ['>', '<='], |
28
|
|
|
'Expr_BinaryOp_GreaterOrEqual' => ['>=', '<'], |
29
|
|
|
'Expr_BinaryOp_Smaller' => ['<', '>='], |
30
|
|
|
'Expr_BinaryOp_SmallerOrEqual' => ['<=', '>'], |
31
|
|
|
]; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param BooleanNot $expr |
35
|
|
|
* @param Context $context |
36
|
|
|
* @return bool |
37
|
|
|
*/ |
38
|
|
|
public function pass(BooleanNot $expr, Context $context) |
39
|
|
|
{ |
40
|
|
|
if (!array_key_exists($expr->expr->getType(), $this->map)) { |
41
|
|
|
return false; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
list($use, $instead) = $this->map[$expr->expr->getType()]; |
45
|
|
|
$msg = sprintf('Use "a %s b" expression instead of "!(a %s b)".', $use, $instead); |
46
|
|
|
|
47
|
|
|
$context->notice('logic_inversion', $msg, $expr); |
48
|
|
|
|
49
|
|
|
return true; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @return array |
54
|
|
|
*/ |
55
|
|
|
public function getRegister() |
56
|
|
|
{ |
57
|
|
|
return [ |
58
|
|
|
BooleanNot::class, |
59
|
|
|
]; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|