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 |
||
28 | class PermissionManager extends Component implements PermissionsInterface, SingletonInterface |
||
29 | { |
||
30 | /** |
||
31 | * Roles associated with their permissions. |
||
32 | * |
||
33 | * @var array |
||
34 | */ |
||
35 | private $permissions = []; |
||
36 | |||
37 | /** |
||
38 | * @var RulesInterface |
||
39 | */ |
||
40 | private $rules = null; |
||
41 | |||
42 | /** |
||
43 | * @var Patternizer |
||
44 | */ |
||
45 | private $patternizer = null; |
||
46 | |||
47 | /** |
||
48 | * @param RulesInterface $rules |
||
49 | * @param Patternizer|null $patternizer |
||
50 | */ |
||
51 | public function __construct(RulesInterface $rules, Patternizer $patternizer) |
||
56 | |||
57 | /** |
||
58 | * {@inheritdoc} |
||
59 | */ |
||
60 | public function hasRole(string $role): bool |
||
64 | |||
65 | /** |
||
66 | * {@inheritdoc} |
||
67 | * |
||
68 | * @return $this |
||
69 | */ |
||
70 | View Code Duplication | public function addRole(string $role): PermissionManager |
|
82 | |||
83 | /** |
||
84 | * {@inheritdoc} |
||
85 | * |
||
86 | * @return $this |
||
87 | */ |
||
88 | View Code Duplication | public function removeRole(string $role): PermissionManager |
|
98 | |||
99 | /** |
||
100 | * {@inheritdoc} |
||
101 | */ |
||
102 | public function getRoles(): array |
||
106 | |||
107 | /** |
||
108 | * {@inheritdoc} |
||
109 | */ |
||
110 | public function getRule(string $role, string $permission): RuleInterface |
||
121 | |||
122 | /** |
||
123 | * {@inheritdoc} |
||
124 | * |
||
125 | * @return $this|self |
||
126 | */ |
||
127 | public function associate( |
||
144 | |||
145 | /** |
||
146 | * Associate role/permission with Forbid rule. |
||
147 | * |
||
148 | * @param string $role |
||
149 | * @param string $permission |
||
150 | * |
||
151 | * @return $this|self |
||
152 | * |
||
153 | * @throws RoleException |
||
154 | * @throws PermissionException |
||
155 | */ |
||
156 | public function deassociate(string $role, string $permission): PermissionManager |
||
160 | |||
161 | /** |
||
162 | * @param string $role |
||
163 | * @param string $permission |
||
164 | * |
||
165 | * @return string |
||
166 | * |
||
167 | * @throws PermissionException |
||
168 | */ |
||
169 | private function findRule(string $role, string $permission): string |
||
187 | } |
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.