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 |
||
11 | class PhpMdLoader implements FileChecker |
||
12 | { |
||
13 | /** |
||
14 | * @var string |
||
15 | */ |
||
16 | protected $file; |
||
17 | |||
18 | /** |
||
19 | * @var array |
||
20 | */ |
||
21 | protected $errors = []; |
||
22 | |||
23 | /** |
||
24 | * @var array |
||
25 | */ |
||
26 | protected $errorRanges = []; |
||
27 | |||
28 | /** |
||
29 | * PhpMdLoader constructor. |
||
30 | * @param string $file the path to the phpmd xml file |
||
31 | */ |
||
32 | public function __construct($file) |
||
33 | { |
||
34 | $this->file = $file; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * {@inheritdoc} |
||
39 | */ |
||
40 | public function getLines() |
||
41 | { |
||
42 | $this->errors = []; |
||
43 | $this->errorRanges = []; |
||
44 | $reader = new XMLReader; |
||
45 | $reader->open($this->file); |
||
46 | $currentFile = ""; |
||
47 | while ($reader->read()) { |
||
48 | $currentFile = $this->checkForNewFile($reader, $currentFile); |
||
49 | $this->checkForViolation($reader, $currentFile); |
||
50 | } |
||
51 | |||
52 | return $this->errors; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | public function isValidLine($file, $lineNumber) |
||
59 | { |
||
60 | $valid = true; |
||
61 | foreach ($this->errorRanges[$file] as $number => $errors) { |
||
62 | if (( |
||
63 | $errors['start'] <= $lineNumber && |
||
64 | $errors['end'] >= $lineNumber |
||
65 | )) { |
||
66 | //unset this error |
||
67 | unset($this->errorRanges[$file][$number]); |
||
68 | $valid = false; |
||
69 | } |
||
70 | } |
||
71 | |||
72 | return $valid; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * @param XMLReader $reader |
||
77 | * @param string $currentFile |
||
78 | */ |
||
79 | protected function checkForViolation(XMLReader $reader, $currentFile) |
||
104 | |||
105 | /** |
||
106 | * @param XMLReader $reader |
||
107 | * @param string $currentFile |
||
108 | * @return string the currentFileName |
||
109 | */ |
||
110 | protected function checkForNewFile(XMLReader $reader, $currentFile) |
||
123 | |||
124 | /** |
||
125 | * {@inheritdoc} |
||
126 | */ |
||
127 | public function handleNotFoundFile() |
||
131 | |||
132 | /** |
||
133 | * {@inheritdoc} |
||
134 | */ |
||
135 | public static function getDescription() |
||
141 | } |
||
142 |