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 ExportCacheClearCommand extends Command |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @var FeedExporter |
||
| 17 | */ |
||
| 18 | protected $exporter; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @param FeedExporter $exporter |
||
| 22 | */ |
||
| 23 | public function __construct(FeedExporter $exporter) |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @inheritdoc |
||
| 32 | */ |
||
| 33 | protected function configure() |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @inheritdoc |
||
| 42 | */ |
||
| 43 | protected function execute(InputInterface $input, OutputInterface $output) |
||
| 44 | { |
||
| 45 | $types = $this->getTypes($input->getArgument('type')); |
||
|
|
|||
| 46 | |||
| 47 | $output->writeln(sprintf('Clearing cache for types: <info>%s</info>', implode(', ', $input->getArgument('type')))); |
||
| 48 | |||
| 49 | foreach ($types as $type) { |
||
| 50 | $builder = $type->getQueryBuilder('x'); |
||
| 51 | if ($input->getOption('where')) { |
||
| 52 | $builder->andWhere($input->getOption('where')); |
||
| 53 | } |
||
| 54 | |||
| 55 | foreach ($builder->getQuery()->iterate() as list($item)) { |
||
| 56 | $output->writeln(sprintf('Clearing cache for <comment>%s</comment>', $this->itemToString($item))); |
||
| 57 | $this->exporter->clearCache($item, [$type]); |
||
| 58 | |||
| 59 | $builder->getEntityManager()->detach($item); |
||
| 60 | } |
||
| 61 | } |
||
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * @param array $types |
||
| 66 | * |
||
| 67 | * @return FeedTypeInterface[] |
||
| 68 | */ |
||
| 69 | View Code Duplication | protected function getTypes(array $types) |
|
| 70 | { |
||
| 71 | if (empty($types)) { |
||
| 72 | return $this->exporter->getTypes(); |
||
| 73 | } |
||
| 74 | |||
| 75 | $result = []; |
||
| 76 | foreach ($types as &$type) { |
||
| 77 | $result[] = $this->exporter->getType($type); |
||
| 78 | } |
||
| 79 | |||
| 80 | return $result; |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * @param object $item |
||
| 85 | * |
||
| 86 | * @return string |
||
| 87 | */ |
||
| 88 | private function itemToString($item) |
||
| 100 | } |
||
| 101 |
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.