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 |
||
7 | final class GridContext |
||
8 | { |
||
9 | private $options; |
||
10 | private $classFqn; |
||
11 | |||
12 | public function __construct(string $classFqn, array $options) |
||
13 | { |
||
14 | $this->classFqn = $classFqn; |
||
15 | $defaults = [ |
||
16 | 'page_size' => 50, |
||
17 | 'page' => 1, |
||
18 | 'orderings' => [], |
||
19 | 'filter' => [], |
||
20 | 'variant' => null, |
||
21 | ]; |
||
22 | |||
23 | // check for invalid keys |
||
24 | View Code Duplication | if ($diff = array_diff(array_keys($options), array_keys($defaults))) { |
|
|
|||
25 | throw new \InvalidArgumentException(sprintf( |
||
26 | 'Invalid grid context options "%s". Valid options: "%s"', |
||
27 | implode('", "', $diff), implode('", "', array_keys($defaults)) |
||
28 | )); |
||
29 | } |
||
30 | |||
31 | // set defaults |
||
32 | $options = array_merge($defaults, $options); |
||
33 | |||
34 | // normalize the orderings |
||
35 | $options['orderings'] = array_map(function ($order) { |
||
36 | $order = strtolower($order); |
||
37 | |||
38 | if (false === in_array($order, ['asc', 'desc'])) { |
||
39 | throw new \InvalidArgumentException(sprintf( |
||
40 | 'Order must be either "asc" or "desc" got "%s"', |
||
41 | $order |
||
42 | )); |
||
43 | } |
||
44 | |||
45 | return $order; |
||
46 | }, $options['orderings']); |
||
47 | |||
48 | // cast integer values where applicable |
||
49 | foreach (['page', 'page_size'] as $key) { |
||
50 | $options[$key] = $options[$key] !== null ? (int) $options[$key] : null; |
||
51 | } |
||
52 | |||
53 | // ensure current page is > 0 |
||
54 | if ($options['page'] < 1) { |
||
55 | $options['page'] = 1; |
||
56 | } |
||
57 | |||
58 | $this->options = $options; |
||
59 | } |
||
60 | |||
61 | public function getCurrentPage(): int |
||
65 | |||
66 | public function isPaginated() |
||
70 | |||
71 | public function getPageSize(): int |
||
75 | |||
76 | public function getPageOffset(): int |
||
80 | |||
81 | public function getOrderings(): array |
||
85 | |||
86 | public function getVariant() |
||
90 | |||
91 | public function getFilter() |
||
95 | |||
96 | public function getUrlParameters(): array |
||
102 | |||
103 | public function getClassFqn() |
||
107 | } |
||
108 |
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.