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 |
||
12 | class Security |
||
13 | { |
||
14 | /** |
||
15 | * @var ContainerInterface |
||
16 | */ |
||
17 | protected $container; |
||
18 | |||
19 | public function __construct(ContainerInterface $container) |
||
20 | { |
||
21 | $this->container = $container; |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * @return TokenStorageInterface |
||
26 | */ |
||
27 | private function getStorage() |
||
28 | { |
||
29 | return $this->container->get('security.token_storage'); |
||
30 | } |
||
31 | |||
32 | /** |
||
33 | * @return AuthorizationCheckerInterface |
||
34 | */ |
||
35 | private function getAuthenChecker() |
||
36 | { |
||
37 | return $this->container->get('security.authorization_checker'); |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * @return null|TokenInterface |
||
42 | */ |
||
43 | public function getToken() |
||
44 | { |
||
45 | return $this->getStorage()->getToken(); |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * @return string|void |
||
50 | */ |
||
51 | public function getUsername() |
||
52 | { |
||
53 | $token = $this->getToken(); |
||
54 | |||
55 | if ($token instanceof TokenInterface) { |
||
56 | return $token->getUsername(); |
||
57 | } |
||
58 | |||
59 | return; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * @return UserInterface|void |
||
64 | */ |
||
65 | View Code Duplication | public function getUser() |
|
79 | |||
80 | /** |
||
81 | * @param $attributes |
||
82 | * @param null $object |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | public function isGranted($attributes, $object = null) |
||
87 | { |
||
88 | return $this->getAuthenChecker()->isGranted($attributes, $object); |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * @return bool |
||
93 | */ |
||
94 | public function isLoggedIn() |
||
98 | } |
||
99 |
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.