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 EloquentPageRepository extends EloquentBaseRepository implements PageRepository |
||
13 | { |
||
14 | /** |
||
15 | * Find the page set as homepage |
||
16 | * @return object |
||
17 | */ |
||
18 | 2 | public function findHomepage() |
|
22 | |||
23 | /** |
||
24 | * Count all records |
||
25 | * @return int |
||
26 | */ |
||
27 | public function countAll() |
||
31 | |||
32 | /** |
||
33 | * @param mixed $data |
||
34 | * @return object |
||
35 | */ |
||
36 | 3 | View Code Duplication | public function create($data) |
|
|||
37 | { |
||
38 | 3 | if (array_get($data, 'is_home') === '1') { |
|
39 | 1 | $this->removeOtherHomepage(); |
|
40 | } |
||
41 | 3 | $page = $this->model->create($data); |
|
42 | |||
43 | 3 | event(new PageWasCreated($page->id, $data)); |
|
44 | |||
45 | 3 | $page->setTags(array_get($data, 'tags', [])); |
|
46 | |||
47 | 3 | return $page; |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param $model |
||
52 | * @param array $data |
||
53 | * @return object |
||
54 | */ |
||
55 | 1 | View Code Duplication | public function update($model, $data) |
56 | { |
||
57 | 1 | if (array_get($data, 'is_home') === '1') { |
|
58 | $this->removeOtherHomepage($model->id); |
||
59 | } |
||
60 | 1 | $model->update($data); |
|
61 | |||
62 | 1 | event(new PageWasUpdated($model->id, $data)); |
|
63 | |||
64 | 1 | $model->setTags(array_get($data, 'tags', [])); |
|
65 | |||
66 | 1 | return $model; |
|
67 | } |
||
68 | |||
69 | public function destroy($page) |
||
77 | |||
78 | /** |
||
79 | * @param $slug |
||
80 | * @param $locale |
||
81 | * @return object |
||
82 | */ |
||
83 | public function findBySlugInLocale($slug, $locale) |
||
84 | { |
||
85 | if (method_exists($this->model, 'translations')) { |
||
86 | return $this->model->whereHas('translations', function (Builder $q) use ($slug, $locale) { |
||
87 | $q->where('slug', $slug); |
||
88 | $q->where('locale', $locale); |
||
89 | })->with('translations')->first(); |
||
90 | } |
||
91 | |||
92 | return $this->model->where('slug', $slug)->where('locale', $locale)->first(); |
||
93 | } |
||
94 | |||
95 | /** |
||
96 | * Set the current page set as homepage to 0 |
||
97 | * @param null $pageId |
||
98 | */ |
||
99 | 1 | private function removeOtherHomepage($pageId = null) |
|
112 | } |
||
113 |
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.