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 |
||
15 | class ApiKeyAuthenticator extends AbstractGuardAuthenticator |
||
16 | { |
||
17 | /** |
||
18 | * @var ManagerRegistry |
||
19 | */ |
||
20 | private $registry; |
||
21 | |||
22 | /** |
||
23 | * @param ManagerRegistry $registry |
||
24 | */ |
||
25 | 86 | public function __construct(ManagerRegistry $registry) |
|
29 | |||
30 | /** |
||
31 | * @inheritdoc |
||
32 | */ |
||
33 | public function getCredentials(Request $request) |
||
34 | { |
||
35 | if (!$token = $request->headers->get('API-Key-Token')) { |
||
36 | return null; |
||
37 | } |
||
38 | |||
39 | return array( |
||
40 | 'token' => $token, |
||
41 | ); |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * @inheritdoc |
||
46 | */ |
||
47 | public function getUser($credentials, UserProviderInterface $userProvider) |
||
48 | { |
||
49 | $apiKey = $credentials['token']; |
||
50 | |||
51 | $user = $this->registry->getRepository('AppBundle:User') |
||
52 | ->findOneBy(['apiKey' => $apiKey]); |
||
53 | |||
54 | return $user; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @inheritdoc |
||
59 | */ |
||
60 | public function checkCredentials($credentials, UserInterface $user) |
||
61 | { |
||
62 | return true; |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * @inheritdoc |
||
67 | */ |
||
68 | public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) |
||
69 | { |
||
70 | return null; |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * @inheritdoc |
||
75 | */ |
||
76 | View Code Duplication | public function onAuthenticationFailure(Request $request, AuthenticationException $exception) |
|
|
|||
77 | { |
||
78 | $data = [ |
||
79 | 'code' => '403', |
||
80 | 'message' => 'Forbidden. You don\'t have necessary permissions for the resource' |
||
81 | ]; |
||
82 | |||
83 | return new JsonResponse($data, Response::HTTP_FORBIDDEN); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * @inheritdoc |
||
88 | */ |
||
89 | View Code Duplication | public function start(Request $request, AuthenticationException $authException = null) |
|
90 | { |
||
91 | $data = [ |
||
92 | 'code' => '401', |
||
93 | 'message' => 'Authentication required' |
||
94 | ]; |
||
95 | |||
96 | return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * @inheritdoc |
||
101 | */ |
||
102 | public function supportsRememberMe() |
||
106 | } |
||
107 |
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.