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 ImportCloseCommand extends Command |
||
14 | { |
||
15 | /** |
||
16 | * @var ManagerRegistry |
||
17 | */ |
||
18 | protected $doctrine; |
||
19 | |||
20 | /** |
||
21 | * @param ManagerRegistry $doctrine |
||
22 | */ |
||
23 | public function __construct(ManagerRegistry $doctrine) |
||
29 | |||
30 | /** |
||
31 | * @inheritdoc |
||
32 | */ |
||
33 | protected function configure() |
||
39 | |||
40 | /** |
||
41 | * @inheritdoc |
||
42 | */ |
||
43 | protected function execute(InputInterface $input, OutputInterface $output) |
||
44 | { |
||
45 | View Code Duplication | if (null === $import = $this->findImportById($input->getArgument('import'))) { |
|
46 | $output->writeln(sprintf('<error>Import %d does not exist</error>', $input->getArgument('import'))); |
||
47 | |||
48 | return 1; |
||
49 | } |
||
50 | |||
51 | // start import if it hasn't already |
||
52 | if (!$import->isStarted()) { |
||
53 | $output->writeln(sprintf('Starting import <comment>%d</comment> before closing it', $import->getId())); |
||
54 | $this->getRepository()->startImport($import); |
||
55 | } |
||
56 | |||
57 | if ($import->isFinished()) { |
||
58 | $output->writeln(sprintf('Import <comment>%d</comment> is already finished', $import->getId())); |
||
59 | |||
60 | return 1; |
||
61 | } |
||
62 | |||
63 | $output->writeln(sprintf('Closing import <comment>%d</comment>', $import->getId())); |
||
64 | |||
65 | if ($this->getRepository()->importHasUnfinishedParts($import)) { |
||
66 | $output->writeln('Closing unfinished parts first'); |
||
67 | |||
68 | foreach ($import->getParts() as $part) { |
||
69 | $output->writeln(sprintf('Closing part <comment>%d</comment>', $part->getPosition())); |
||
70 | |||
71 | if (!$part->isStarted()) { |
||
72 | $part->setProcess(0); |
||
73 | $this->getRepository()->startImportPart($part); |
||
74 | } |
||
75 | |||
76 | if (!$part->isFinished()) { |
||
77 | $this->getRepository()->finishImportPart($part); |
||
78 | } |
||
79 | } |
||
80 | } |
||
81 | |||
82 | $this->getRepository()->finishImport($import); |
||
83 | |||
84 | $output->writeln('<info>Import closed</info>'); |
||
85 | |||
86 | return 0; |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * @param int $id |
||
91 | * |
||
92 | * @return Import |
||
93 | */ |
||
94 | protected function findImportById($id) |
||
98 | |||
99 | /** |
||
100 | * @return ImportRepository |
||
101 | */ |
||
102 | protected function getRepository() |
||
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.