1 | <?php |
||
22 | |||
23 | /** |
||
24 | * AbstractAggregation class. |
||
25 | */ |
||
26 | abstract class AbstractAggregation implements NamedBuilderInterface |
||
27 | { |
||
28 | use ParametersTrait; |
||
29 | |||
30 | use NameAwareTrait; |
||
31 | |||
32 | private ?string $field = null; |
||
|
|||
33 | |||
34 | private ?BuilderBag $aggregations = null; |
||
35 | |||
36 | abstract protected function supportsNesting(): bool; |
||
37 | |||
38 | abstract protected function getArray(): array | stdClass; |
||
39 | |||
40 | public function __construct(string $name) |
||
41 | { |
||
42 | $this->setName($name); |
||
43 | } |
||
44 | |||
45 | public function setField(?string $field): static |
||
46 | { |
||
47 | $this->field = $field; |
||
48 | |||
49 | return $this; |
||
50 | } |
||
51 | |||
52 | public function getField(): ?string |
||
53 | { |
||
54 | return $this->field; |
||
55 | } |
||
56 | |||
57 | public function addAggregation(AbstractAggregation $abstractAggregation): static |
||
58 | { |
||
59 | if (!$this->aggregations) { |
||
60 | $this->aggregations = $this->createBuilderBag(); |
||
61 | } |
||
62 | |||
63 | $this->aggregations->add($abstractAggregation); |
||
64 | |||
65 | return $this; |
||
66 | } |
||
67 | |||
68 | public function getAggregations(): array |
||
69 | { |
||
70 | if ($this->aggregations) { |
||
71 | return $this->aggregations->all(); |
||
72 | } |
||
73 | |||
74 | return []; |
||
75 | } |
||
76 | |||
77 | public function getAggregation(string $name): AbstractAggregation|BuilderInterface|null |
||
78 | { |
||
79 | if ($this->aggregations && $this->aggregations->has($name)) { |
||
80 | return $this->aggregations->get($name); |
||
81 | } |
||
82 | |||
83 | return null; |
||
84 | } |
||
85 | |||
86 | public function toArray(): array |
||
87 | { |
||
88 | $array = $this->getArray(); |
||
89 | $result = [ |
||
90 | $this->getType() => is_array($array) ? $this->processArray($array) : $array, |
||
91 | ]; |
||
92 | |||
93 | if ($this->supportsNesting()) { |
||
94 | $nestedResult = $this->collectNestedAggregations(); |
||
95 | |||
96 | if (!empty($nestedResult)) { |
||
97 | $result['aggregations'] = $nestedResult; |
||
98 | } |
||
99 | } |
||
100 | |||
101 | return $result; |
||
102 | } |
||
103 | |||
104 | protected function collectNestedAggregations(): array |
||
105 | { |
||
106 | $result = []; |
||
107 | /** @var AbstractAggregation $aggregation */ |
||
108 | foreach ($this->getAggregations() as $aggregation) { |
||
109 | $result[$aggregation->getName()] = $aggregation->toArray(); |
||
110 | } |
||
111 | |||
112 | return $result; |
||
113 | } |
||
114 | |||
115 | private function createBuilderBag(): BuilderBag |
||
116 | { |
||
117 | return new BuilderBag(); |
||
118 | } |
||
119 | } |
||
120 |