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 |
||
13 | class CatchAll extends BaseHandler |
||
14 | { |
||
15 | protected $helpAvailable = false; |
||
16 | |||
17 | /** |
||
18 | * If this function returns true, the handle method will get called. |
||
19 | * |
||
20 | * @param \Spatie\SlashCommand\Request $request |
||
21 | * |
||
22 | * @return bool |
||
23 | */ |
||
24 | public function canHandle(Request $request): bool |
||
28 | |||
29 | /** |
||
30 | * Handle the given request. Remember that Slack expects a response |
||
31 | * within three seconds after the slash command was issued. If |
||
32 | * there is more time needed, dispatch a job. |
||
33 | * |
||
34 | * @param \Spatie\SlashCommand\Request $request |
||
35 | * |
||
36 | * @return \Spatie\SlashCommand\Response |
||
37 | */ |
||
38 | public function handle(Request $request): Response |
||
56 | |||
57 | protected function findAlternatives(string $command): Collection |
||
58 | { |
||
59 | // Number of characters to change |
||
60 | $threshold = 2; |
||
61 | |||
62 | $handlers = collect(config('laravel-slack-slash-command.handlers')) |
||
63 | ->map(function (string $handlerClassName) { |
||
64 | return new $handlerClassName($this->request); |
||
65 | }) |
||
66 | ->filter(function (HandlesSlashCommand $handler) { |
||
67 | return $handler instanceof SignatureHandler; |
||
68 | }) |
||
69 | View Code Duplication | ->filter(function (SignatureHandler $handler) { |
|
|
|||
70 | $signatureParts = new SignatureParts($handler->getSignature()); |
||
71 | return Str::is($signatureParts->getSlashCommandName(), $this->request->command); |
||
72 | }) |
||
73 | ->map(function(SignatureHandler $handler){ |
||
74 | if ($handler instanceof Help) { |
||
75 | $this->helpAvailable = true; |
||
76 | } |
||
77 | return $handler; |
||
78 | }) |
||
79 | ; |
||
80 | |||
81 | if (strpos($command, ':') !== false) { |
||
82 | $subHandlers = $this->findInNamespace($handlers, $command); |
||
83 | if (! $subHandlers->isEmpty()) { |
||
84 | return $subHandlers; |
||
85 | } |
||
86 | } |
||
87 | |||
88 | return $handlers->filter(function(SignatureHandler $handler) use($command, $threshold) { |
||
89 | return levenshtein($handler->getName(), $command) <= $threshold; |
||
90 | }); |
||
91 | } |
||
92 | |||
93 | protected function findInNamespace(Collection $handlers, string $command): Collection |
||
104 | |||
105 | View Code Duplication | protected function getCommandListAttachment(Collection $handlers): Attachment |
|
116 | } |
||
117 |
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.