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 declare(strict_types=1); |
||
16 | abstract class AbstractResource implements ResourceInterface, Serializable |
||
17 | { |
||
18 | /** |
||
19 | * The JSON key that indicates how the API nests singular resources. For example, when |
||
20 | * performing a GET, it could respond with ``{"server": {"id": "12345"}}``. In this case, |
||
21 | * "server" is the resource key, since the essential state of the server is nested inside. |
||
22 | * |
||
23 | * @var string |
||
24 | */ |
||
25 | protected $resourceKey; |
||
26 | |||
27 | /** |
||
28 | * An array of aliases that will be checked when the resource is being populated. For example, |
||
29 | * |
||
30 | * 'FOO_BAR' => 'fooBar' |
||
31 | * |
||
32 | * will extract FOO_BAR from the response, and save it as 'fooBar' in the resource. |
||
33 | * |
||
34 | * @var array |
||
35 | */ |
||
36 | protected $aliases = []; |
||
37 | |||
38 | /** |
||
39 | * Populates the current resource from a response object. |
||
40 | * |
||
41 | * @param ResponseInterface $response |
||
42 | * |
||
43 | * @return AbstractResource |
||
44 | */ |
||
45 | public function populateFromResponse(ResponseInterface $response): self |
||
56 | |||
57 | /** |
||
58 | * Populates the current resource from a data array. |
||
59 | * |
||
60 | * @param array $array |
||
61 | * |
||
62 | * @return mixed|void |
||
63 | 74 | */ |
|
64 | public function populateFromArray(array $array): self |
||
83 | |||
84 | 133 | /** |
|
85 | * Constructs alias objects |
||
86 | 133 | * |
|
87 | 133 | * @return Alias[] |
|
88 | */ |
||
89 | 133 | protected function getAliases(): array |
|
99 | 128 | ||
100 | 2 | /** |
|
101 | 128 | * Internal method which retrieves the values of provided keys. |
|
102 | 6 | * |
|
103 | 6 | * @param array $keys |
|
104 | 6 | * |
|
105 | 6 | * @return array |
|
106 | 6 | */ |
|
107 | 128 | protected function getAttrs(array $keys) |
|
119 | 124 | ||
120 | 124 | View Code Duplication | public function model(string $class, $data = null): ResourceInterface |
138 | 3 | ||
139 | public function serialize(): \stdClass |
||
162 | } |
||
163 |
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.