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 |
||
14 | class StringFilter extends AbstractComparatorFilter |
||
15 | { |
||
16 | const TYPE_EQUAL = 'equal'; |
||
17 | const TYPE_EMPTY = 'empty'; |
||
18 | const TYPE_NOT_EMPTY = 'not_empty'; |
||
19 | const TYPE_CONTAINS = 'contains'; |
||
20 | const TYPE_NOT_CONTAINS = 'not_contains'; |
||
21 | const TYPE_STARTS_WITH = 'starts_with'; |
||
22 | const TYPE_ENDS_WITH = 'ends_with'; |
||
23 | const TYPE_IN = 'in'; |
||
24 | const TYPE_NOT_IN = 'not_in'; |
||
25 | |||
26 | private static $comparatorMap = [ |
||
27 | self::TYPE_EQUAL => Comparison::EQUALS, |
||
28 | self::TYPE_EMPTY => Comparison::NULL, |
||
29 | self::TYPE_NOT_EMPTY => Comparison::NOT_NULL, |
||
30 | self::TYPE_CONTAINS => Comparison::CONTAINS, |
||
31 | self::TYPE_NOT_CONTAINS => Comparison::NOT_CONTAINS, |
||
32 | self::TYPE_STARTS_WITH => Comparison::CONTAINS, |
||
33 | self::TYPE_ENDS_WITH => Comparison::CONTAINS, |
||
34 | self::TYPE_IN => Comparison::IN, |
||
35 | self::TYPE_NOT_IN => Comparison::NOT_IN, |
||
36 | ]; |
||
37 | |||
38 | /** |
||
39 | * {@inheritdoc} |
||
40 | */ |
||
41 | public function buildForm(FormBuilderInterface $builder, array $options) |
||
49 | |||
50 | /** |
||
51 | * {@inheritdoc} |
||
52 | */ |
||
53 | View Code Duplication | public function getExpression(string $fieldName, array $data): Expression |
|
|
|||
54 | { |
||
55 | $comparator = $data['comparator'] ?: self::TYPE_EQUAL; |
||
56 | |||
57 | return Query::comparison( |
||
58 | self::$comparatorMap[$comparator], |
||
59 | $fieldName, |
||
60 | $this->getValue($comparator, $data['value']) |
||
61 | ); |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * {@inheritdoc} |
||
66 | */ |
||
67 | public function configureOptions(OptionsResolver $options) |
||
71 | |||
72 | /** |
||
73 | * {@inheritdoc} |
||
74 | */ |
||
75 | public function isApplicable(array $filterData): bool |
||
79 | |||
80 | protected function getComparatorMap(): array |
||
84 | |||
85 | private function getValue($comparator, $value) |
||
110 | } |
||
111 |
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.