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 |
||
17 | trait AuthAwareTrait |
||
18 | { |
||
19 | /** |
||
20 | * @var Authenticator |
||
21 | */ |
||
22 | private $authenticator; |
||
23 | |||
24 | /** |
||
25 | * @var Authorizer |
||
26 | */ |
||
27 | private $authorizer; |
||
28 | |||
29 | /** |
||
30 | * @var string[] |
||
31 | */ |
||
32 | private $requiredAclPermissions = []; |
||
33 | |||
34 | /** |
||
35 | * @param Container $container The DI container. |
||
36 | * @return void |
||
37 | */ |
||
38 | protected function setAuthDependencies(Container $container) |
||
43 | |||
44 | /** |
||
45 | * Set the authentication service. |
||
46 | * |
||
47 | * @param Authenticator $authenticator The authentication service. |
||
48 | * @return AuthAwareInterface |
||
49 | */ |
||
50 | protected function setAuthenticator(Authenticator $authenticator) |
||
56 | |||
57 | /** |
||
58 | * Retrieve the authentication service. |
||
59 | * |
||
60 | * @throws RuntimeException If the authenticator was not previously set. |
||
61 | * @return Authenticator |
||
62 | */ |
||
63 | View Code Duplication | protected function authenticator() |
|
74 | |||
75 | /** |
||
76 | * Set the authorization service. |
||
77 | * |
||
78 | * @param Authorizer $authorizer The authorization service. |
||
79 | * @return AuthAwareInterface |
||
80 | */ |
||
81 | protected function setAuthorizer(Authorizer $authorizer) |
||
87 | |||
88 | /** |
||
89 | * Retrieve the authorization service. |
||
90 | * |
||
91 | * @throws RuntimeException If the authorizer was not previously set. |
||
92 | * @return Authorizer |
||
93 | */ |
||
94 | View Code Duplication | protected function authorizer() |
|
105 | |||
106 | /** |
||
107 | * @param string[]|string|null $permissions The list of required permissions. |
||
108 | * @throws InvalidArgumentException If the permissions are not an array or a comma-separated string. |
||
109 | * @return AuthAwareTrait Chainable |
||
110 | */ |
||
111 | protected function setRequiredAclPermissions($permissions) |
||
129 | |||
130 | /** |
||
131 | * @return string[] |
||
132 | */ |
||
133 | protected function requiredAclPermissions() |
||
137 | |||
138 | /** |
||
139 | * @return boolean |
||
140 | */ |
||
141 | public function isAuthorized() |
||
145 | |||
146 | /** |
||
147 | * @param array $permissions The list of required permissions to check. |
||
148 | * @return boolean |
||
149 | */ |
||
150 | public function hasPermissions(array $permissions) |
||
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.