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 |
||
12 | class FileSerializedResourcePersistenceHandler implements PersistenceHandlerInterface |
||
13 | { |
||
14 | /** |
||
15 | * @var string the path where all spider results should be persisted. |
||
16 | * The results will be grouped in a directory by spider ID. |
||
17 | */ |
||
18 | private $path = ''; |
||
19 | |||
20 | private $spiderId = ''; |
||
21 | |||
22 | private $totalSizePersisted = 0; |
||
23 | |||
24 | /** @var \Iterator */ |
||
25 | private $iterator; |
||
26 | |||
27 | /** @var Finder */ |
||
28 | private $finder; |
||
29 | |||
30 | /** |
||
31 | * @param string $path the path where all spider results should be persisted. |
||
32 | * The results will be grouped in a directory by spider ID. |
||
33 | */ |
||
34 | public function __construct($path) |
||
38 | |||
39 | View Code Duplication | public function setSpiderId($spiderId) |
|
|
|||
40 | { |
||
41 | $this->spiderId = $spiderId; |
||
42 | |||
43 | // create the path |
||
44 | if (!file_exists($this->getResultPath())) { |
||
45 | mkdir($this->getResultPath(), 0700, true); |
||
46 | } |
||
47 | } |
||
48 | |||
49 | public function count() |
||
53 | |||
54 | private function getResultPath() |
||
58 | |||
59 | public function persist(Resource $resource) |
||
65 | |||
66 | View Code Duplication | private function getFinder() |
|
67 | { |
||
68 | if (!$this->finder instanceof Finder) { |
||
69 | $this->finder = Finder::create()->files()->in($this->getResultPath()); |
||
70 | } |
||
71 | return $this->finder; |
||
72 | } |
||
73 | |||
74 | private function getIterator() |
||
81 | |||
82 | /** |
||
83 | * @return Resource |
||
84 | */ |
||
85 | public function current() |
||
89 | |||
90 | /** |
||
91 | * @return void |
||
92 | */ |
||
93 | public function next() |
||
97 | |||
98 | /** |
||
99 | * @return int |
||
100 | */ |
||
101 | public function key() |
||
105 | |||
106 | /** |
||
107 | * @return boolean |
||
108 | */ |
||
109 | public function valid() |
||
113 | |||
114 | /** |
||
115 | * @return void |
||
116 | */ |
||
117 | public function rewind() |
||
121 | } |
||
122 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.