Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
14 | abstract class AbstractApplyTest extends \PHPUnit_Framework_TestCase |
||
15 | { |
||
16 | /** |
||
17 | * close Mockery |
||
18 | */ |
||
19 | public function tearDown() |
||
23 | |||
24 | /** |
||
25 | * @param AbstractNode $node |
||
26 | * @param int $violationNumber |
||
27 | */ |
||
28 | protected function assertRule(AbstractNode $node, $violationNumber) |
||
29 | { |
||
30 | $rule = $this->getRule(); |
||
31 | $rule->setReport($this->getReport($violationNumber)); |
||
|
|||
32 | $rule->apply($node); |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * @param int $violationNumber |
||
37 | * |
||
38 | * @return \Mockery\MockInterface|Report |
||
39 | */ |
||
40 | protected function getReport($violationNumber) |
||
41 | { |
||
42 | $report = \Mockery::mock('PHPMD\Report'); |
||
43 | $report->shouldReceive('addRuleViolation')->times($violationNumber); |
||
44 | |||
45 | return $report; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * @param string $className |
||
50 | * @param string $methodName |
||
51 | * @param array $findChildrenOfType |
||
52 | * |
||
53 | * @return \Mockery\MockInterface |
||
54 | */ |
||
55 | protected function getMethodNode($className, $methodName, array $findChildrenOfType = []) |
||
56 | { |
||
57 | $methodNode = \Mockery::mock('PHPMD\Node\MethodNode'); |
||
58 | $methodNode->shouldReceive('getImage')->andReturn($methodName); |
||
59 | $methodNode->shouldReceive('getParentName')->andReturn($className); |
||
60 | $methodNode->shouldReceive('getName')->andReturn($methodName); |
||
61 | |||
62 | foreach ($findChildrenOfType as $argument => $return) { |
||
63 | $methodNode->shouldReceive('findChildrenOfType')->with($argument)->andReturn($return); |
||
64 | } |
||
65 | |||
66 | return $methodNode; |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param string $name |
||
71 | * |
||
72 | * @return \Mockery\MockInterface |
||
73 | */ |
||
74 | View Code Duplication | protected function getNode($name) |
|
75 | { |
||
76 | $node = \Mockery::mock('PHPMD\AbstractNode'); |
||
77 | $node->shouldReceive('getName')->andReturn($name); |
||
78 | $node->shouldReceive('getImage')->andReturn($name); |
||
79 | |||
80 | return $node; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @return AbstractRule |
||
85 | */ |
||
86 | abstract protected function getRule(); |
||
87 | } |
||
88 |
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.