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 |
||
| 22 | * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html |
||
| 23 | */ |
||
| 24 | class RangeQuery implements BuilderInterface |
||
| 25 | { |
||
| 26 | use ParametersTrait; |
||
| 27 | |||
| 28 | public const LT = 'lt'; |
||
| 29 | |||
| 30 | public const GT = 'gt'; |
||
| 31 | |||
| 32 | public const LTE = 'lte'; |
||
| 33 | |||
| 34 | public const GTE = 'gte'; |
||
| 35 | |||
| 36 | public function __construct(private string $field, array $parameters = []) |
||
|
|
|||
| 37 | { |
||
| 38 | $this->setParameters($parameters); |
||
| 39 | |||
| 40 | if ($this->hasParameter(self::GTE) && $this->hasParameter(self::GT)) { |
||
| 41 | unset($this->parameters[self::GT]); |
||
| 42 | } |
||
| 43 | |||
| 44 | if ($this->hasParameter(self::LTE) && $this->hasParameter(self::LT)) { |
||
| 45 | unset($this->parameters[self::LT]); |
||
| 46 | } |
||
| 47 | } |
||
| 48 | |||
| 49 | public function getType(): string |
||
| 50 | { |
||
| 51 | return 'range'; |
||
| 52 | } |
||
| 53 | |||
| 54 | public function toArray(): array |
||
| 55 | { |
||
| 56 | $output = [ |
||
| 57 | $this->field => $this->getParameters(), |
||
| 58 | ]; |
||
| 59 | |||
| 60 | return [$this->getType() => $output]; |
||
| 61 | } |
||
| 62 | } |
||
| 63 |