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 Generate extends Command |
||
13 | { |
||
14 | use ValidatesSamplingSize; |
||
15 | |||
16 | protected $phash; |
||
17 | |||
18 | public function __construct(PHash $phash) |
||
19 | { |
||
20 | $this->phash = $phash; |
||
21 | |||
22 | parent::__construct(); |
||
23 | } |
||
24 | |||
25 | View Code Duplication | protected function configure() |
|
|
|||
26 | { |
||
27 | $this->setName('generate') |
||
28 | ->setDescription('Generates the pHash of given image') |
||
29 | ->addArgument('file', InputArgument::REQUIRED, 'Pass the file.') |
||
30 | ->addOption('size', 's', InputOption::VALUE_REQUIRED, 'Sampling size.', 8) |
||
31 | ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format [hex,bin,ascii].', 'hex'); |
||
32 | } |
||
33 | |||
34 | protected function execute(InputInterface $input, OutputInterface $output) |
||
35 | { |
||
36 | try { |
||
37 | $this->validate($input); |
||
38 | } catch (\InvalidArgumentException $e) { |
||
39 | $output->writeln("<error>{$e->getMessage()}</error>"); |
||
40 | |||
41 | return Command::FAILURE; |
||
42 | } |
||
43 | |||
44 | $bits = $this->phash->hash( |
||
45 | new \SplFileInfo($input->getArgument('file')), |
||
46 | $input->getOption('size') |
||
47 | ); |
||
48 | |||
49 | $this->display($output, $input->getOption('format'), $bits, $input->getOption('size')); |
||
50 | |||
51 | return Command::SUCCESS; |
||
52 | } |
||
53 | |||
54 | protected function validate(InputInterface $input) |
||
66 | |||
67 | protected function display(OutputInterface $output, string $format, string $bits, int $size) |
||
95 | } |
||
96 |
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.