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 | use \Charcoal\Search\SearchLog; |
||
15 | |||
16 | /** |
||
17 | * Search widget to show the latest searched-for terms and their results. |
||
18 | */ |
||
19 | View Code Duplication | class TopSearchWidget extends AdminWidget |
|
|
|||
20 | { |
||
21 | /** |
||
22 | * @var DateTimeInterface $startDate |
||
23 | */ |
||
24 | private $startDate; |
||
25 | |||
26 | /** |
||
27 | * @var DateTimeInterface $endDate |
||
28 | */ |
||
29 | private $endDate; |
||
30 | |||
31 | private $collectionLoader; |
||
32 | private $topSearches; |
||
33 | |||
34 | public function setDependencies(Container $container) |
||
40 | |||
41 | /** |
||
42 | * @param string|DateTimeInterface|null $date The starting date-time. |
||
43 | * @throws InvalidArgumentException If the date format is not valid. |
||
44 | * @return TopSearchWidget Chainable |
||
45 | */ |
||
46 | public function setStartDate($date) |
||
63 | |||
64 | /** |
||
65 | * @return DateTimeInterface |
||
66 | */ |
||
67 | public function startDate() |
||
74 | |||
75 | /** |
||
76 | * @param string|DateTimeInterface|null $date The ending date-time. |
||
77 | * @throws InvalidArgumentException If the date format is not valid. |
||
78 | * @return TopSearchWidget Chainable |
||
79 | */ |
||
80 | public function setEndDate($date) |
||
81 | { |
||
82 | if ($date === null) { |
||
83 | $this->endDate = new DateTime('now'); |
||
84 | return $this; |
||
85 | } |
||
86 | if (is_string($date)) { |
||
87 | $date = new DateTime($date); |
||
88 | } |
||
89 | if (!($date instanceof DateTimeInterface)) { |
||
90 | throw new InvalidArgumentException( |
||
91 | 'Invalid "End Date" value. Must be a date/time string or a DateTimeInterface object.' |
||
92 | ); |
||
93 | } |
||
94 | $this->endDate = $date; |
||
95 | return $this; |
||
159 |
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.