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 |
||
5 | class LampagerColumnAccess |
||
6 | { |
||
7 | /** @var Model */ |
||
8 | protected $model; |
||
9 | |||
10 | public function __construct(Model $model) |
||
11 | { |
||
12 | 68 | $this->model = $model; |
|
13 | } |
||
14 | 68 | ||
15 | 68 | /** |
|
16 | * Return a value indicating whether the data has any value whose field mathes the column. |
||
17 | * |
||
18 | * @param array $data |
||
19 | * @param string $column |
||
20 | * @return bool |
||
21 | */ |
||
22 | public function has(array $data, $column) |
||
23 | { |
||
24 | 63 | if (strpos($column, '.')) { |
|
25 | list($model, $column) = explode('.', $column); |
||
26 | 63 | return isset($data[$model][$column]) || isset($data["{$model}.{$column}"]); |
|
27 | 47 | } |
|
28 | 47 | return isset($data[$this->model->alias][$column]) || isset($data["{$this->model->alias}.{$column}"]) || isset($data[$column]); |
|
29 | } |
||
30 | 16 | ||
31 | /** |
||
32 | * Get a value from the data by the column. |
||
33 | * |
||
34 | * @param array $data |
||
35 | * @param string $column |
||
36 | * @return mixed |
||
37 | */ |
||
38 | public function get(array $data, $column) |
||
57 | } |
||
58 | 2 | ||
59 | /** |
||
60 | * Create an associative array which has model as 1st dimensional key and column as 2nd dimensional key. |
||
61 | * |
||
62 | * @param string $column |
||
63 | * @param mixed $value |
||
64 | * @return mixed[][] |
||
65 | */ |
||
66 | public function with($column, $value) |
||
67 | { |
||
68 | 34 | if (strpos($column, '.')) { |
|
69 | list($model, $column) = explode('.', $column); |
||
70 | 34 | return [ |
|
71 | 33 | $model => [ |
|
72 | $column => $value, |
||
73 | ], |
||
74 | 33 | ]; |
|
75 | } |
||
76 | return [ |
||
77 | $this->model->alias => [ |
||
78 | $column => $value, |
||
79 | 1 | ], |
|
80 | 1 | ]; |
|
81 | } |
||
82 | |||
83 | /** |
||
84 | * Iterate through the data with flatten field name |
||
85 | * |
||
86 | * @param array $data |
||
87 | * @return \Generator |
||
88 | */ |
||
89 | public function iterate(array $data) |
||
98 | 33 | } |
|
99 | 33 | } |
|
100 | } |
||
101 | } |
||
102 |