|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace MS\PHPMD\Rule\Design; |
|
4
|
|
|
|
|
5
|
|
|
use PHPMD\AbstractNode; |
|
6
|
|
|
use PHPMD\AbstractRule; |
|
7
|
|
|
use PHPMD\Node\MethodNode; |
|
8
|
|
|
use PHPMD\Rule\MethodAware; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Methods should only have one try statement. If not, swap out the try statement in an extra method. It increase the readability. |
|
12
|
|
|
*/ |
|
13
|
|
|
class TryStatement extends AbstractRule implements MethodAware |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @param AbstractNode|MethodNode $node |
|
17
|
|
|
*/ |
|
18
|
7 |
|
public function apply(AbstractNode $node) |
|
19
|
|
|
{ |
|
20
|
7 |
|
$countTry = count($node->findChildrenOfType('TryStatement')); |
|
21
|
|
|
|
|
22
|
7 |
|
if (1 < $countTry) { |
|
23
|
1 |
|
$this->addViolation($node); |
|
24
|
1 |
|
} |
|
25
|
|
|
|
|
26
|
7 |
|
if (1 === $countTry && true === $this->hasNotAllowedChildren($node)) { |
|
|
|
|
|
|
27
|
1 |
|
$this->addViolation($node); |
|
28
|
1 |
|
} |
|
29
|
7 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param MethodNode $node |
|
33
|
|
|
* |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
1 |
|
private function hasNotAllowedChildren(MethodNode $node) |
|
37
|
|
|
{ |
|
38
|
1 |
|
$children = $node->findChildrenOfType('ScopeStatement'); |
|
39
|
|
|
|
|
40
|
1 |
|
$allowedChildren = explode( |
|
41
|
1 |
|
$this->getStringProperty('delimiter'), |
|
42
|
1 |
|
$this->getStringProperty('allowedChildren') |
|
43
|
1 |
|
); |
|
44
|
|
|
|
|
45
|
|
|
/** @var AbstractNode $child */ |
|
46
|
1 |
|
foreach ($children as $child) { |
|
47
|
1 |
|
if (true === in_array($child->getImage(), $allowedChildren) || true === $this->isChildOfTry($child)) { |
|
48
|
1 |
|
continue; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
1 |
|
return true; |
|
52
|
1 |
|
} |
|
53
|
|
|
|
|
54
|
1 |
|
return false; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param AbstractNode $node |
|
59
|
|
|
* |
|
60
|
|
|
* @return bool |
|
61
|
|
|
*/ |
|
62
|
1 |
|
private function isChildOfTry(AbstractNode $node) |
|
63
|
|
|
{ |
|
64
|
1 |
|
$parent = $node->getParent(); |
|
65
|
|
|
|
|
66
|
1 |
|
while (is_object($parent)) { |
|
67
|
1 |
|
if ($parent->isInstanceOf('TryStatement')) { |
|
68
|
1 |
|
return true; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
1 |
|
$parent = $parent->getParent(); |
|
72
|
1 |
|
} |
|
73
|
|
|
|
|
74
|
1 |
|
return false; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
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.