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-geo-shape-query.html |
||
| 23 | */ |
||
| 24 | class GeoShapeQuery implements BuilderInterface |
||
| 25 | { |
||
| 26 | use ParametersTrait; |
||
| 27 | |||
| 28 | public const INTERSECTS = 'intersects'; |
||
| 29 | |||
| 30 | public const DISJOINT = 'disjoint'; |
||
| 31 | |||
| 32 | public const WITHIN = 'within'; |
||
| 33 | |||
| 34 | public const CONTAINS = 'contains'; |
||
| 35 | |||
| 36 | private array $fields = []; |
||
|
|
|||
| 37 | |||
| 38 | public function __construct(array $parameters = []) |
||
| 39 | { |
||
| 40 | $this->setParameters($parameters); |
||
| 41 | } |
||
| 42 | |||
| 43 | public function getType(): string |
||
| 44 | { |
||
| 45 | return 'geo_shape'; |
||
| 46 | } |
||
| 47 | |||
| 48 | public function addShape( |
||
| 49 | string $field, |
||
| 50 | string $type, |
||
| 51 | array $coordinates, |
||
| 52 | string $relation = self::INTERSECTS, |
||
| 53 | array $parameters = [] |
||
| 54 | ): void { |
||
| 55 | $filter = array_merge( |
||
| 56 | $parameters, |
||
| 57 | [ |
||
| 58 | 'type' => $type, |
||
| 59 | 'coordinates' => $coordinates, |
||
| 60 | ] |
||
| 61 | ); |
||
| 62 | |||
| 63 | $this->fields[$field] = [ |
||
| 64 | 'shape' => $filter, |
||
| 65 | 'relation' => $relation, |
||
| 66 | ]; |
||
| 67 | } |
||
| 68 | |||
| 69 | public function addPreIndexedShape( |
||
| 70 | string $field, |
||
| 71 | string $id, |
||
| 72 | string $type, |
||
| 73 | string $index, |
||
| 74 | string $path, |
||
| 75 | string $relation = self::INTERSECTS, |
||
| 76 | array $parameters = [] |
||
| 77 | ): void { |
||
| 78 | $filter = array_merge( |
||
| 79 | $parameters, |
||
| 80 | [ |
||
| 81 | 'id' => $id, |
||
| 82 | 'type' => $type, |
||
| 83 | 'index' => $index, |
||
| 84 | 'path' => $path, |
||
| 85 | ] |
||
| 86 | ); |
||
| 87 | |||
| 88 | $this->fields[$field] = [ |
||
| 89 | 'indexed_shape' => $filter, |
||
| 90 | 'relation' => $relation, |
||
| 91 | ]; |
||
| 92 | } |
||
| 93 | |||
| 94 | public function toArray(): array |
||
| 95 | { |
||
| 96 | $output = $this->processArray($this->fields); |
||
| 97 | |||
| 98 | return [$this->getType() => $output]; |
||
| 99 | } |
||
| 100 | } |
||
| 101 |