1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MS\PHPMD\Rule\CleanCode; |
4
|
|
|
|
5
|
|
|
use PHPMD\AbstractNode; |
6
|
|
|
use PHPMD\AbstractRule; |
7
|
|
|
use PHPMD\Node\MethodNode; |
8
|
|
|
use PHPMD\Rule\MethodAware; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class MethodOneTryCatch |
12
|
|
|
* |
13
|
|
|
* Methods should only have one try statement. If not, swap out the try statement in an extra method. It increase the readability. |
14
|
|
|
* |
15
|
|
|
* @package MS\PHPMD\Rule\CleanCode |
16
|
|
|
*/ |
17
|
|
|
class MethodOneTryCatch extends AbstractRule implements MethodAware |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @param AbstractNode|MethodNode $node |
21
|
|
|
*/ |
22
|
3 |
|
public function apply(AbstractNode $node) |
23
|
|
|
{ |
24
|
3 |
|
$countTry = count($node->findChildrenOfType('TryStatement')); |
25
|
|
|
|
26
|
3 |
|
if (1 < $countTry) { |
27
|
1 |
|
$this->addViolation($node); |
28
|
1 |
|
} |
29
|
|
|
|
30
|
3 |
|
if (1 === $countTry && true === $this->hasNotAllowedChildren($node)) { |
|
|
|
|
31
|
1 |
|
$this->addViolation($node); |
32
|
1 |
|
} |
33
|
3 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param MethodNode $node |
37
|
|
|
* |
38
|
|
|
* @return bool |
39
|
|
|
*/ |
40
|
2 |
|
private function hasNotAllowedChildren(MethodNode $node) |
41
|
|
|
{ |
42
|
2 |
|
$children = $node->findChildrenOfType('ScopeStatement'); |
43
|
|
|
|
44
|
2 |
|
$allowedChildren = explode( |
45
|
2 |
|
$this->getStringProperty('delimiter'), |
46
|
2 |
|
$this->getStringProperty('allowedChildren') |
47
|
2 |
|
); |
48
|
|
|
|
49
|
|
|
/** @var AbstractNode $child */ |
50
|
2 |
|
foreach ($children as $child) { |
51
|
2 |
|
if (true === in_array($child->getImage(), $allowedChildren) || true === $this->isChildOfTry($child)) { |
52
|
2 |
|
continue; |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
return true; |
56
|
1 |
|
} |
57
|
|
|
|
58
|
1 |
|
return false; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param AbstractNode $node |
63
|
|
|
* |
64
|
|
|
* @return bool |
65
|
|
|
*/ |
66
|
1 |
|
private function isChildOfTry(AbstractNode $node) |
67
|
|
|
{ |
68
|
1 |
|
$parent = $node->getParent(); |
69
|
|
|
|
70
|
1 |
|
while (is_object($parent)) { |
71
|
1 |
|
if ($parent->isInstanceOf('TryStatement')) { |
72
|
1 |
|
return true; |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
$parent = $parent->getParent(); |
76
|
1 |
|
} |
77
|
|
|
|
78
|
1 |
|
return false; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.
Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.