1<?php 2 3namespace Elastica\Aggregation; 4 5use Elastica\Exception\InvalidException; 6use Elastica\NameableInterface; 7use Elastica\Param; 8 9abstract class AbstractAggregation extends Param implements NameableInterface 10{ 11 /** 12 * @var string The name of this aggregation 13 */ 14 protected $_name; 15 16 /** 17 * @var array Subaggregations belonging to this aggregation 18 */ 19 protected $_aggs = []; 20 21 /** 22 * @param string $name the name of this aggregation 23 */ 24 public function __construct(string $name) 25 { 26 $this->setName($name); 27 } 28 29 /** 30 * Set the name of this aggregation. 31 * 32 * @param string $name 33 * 34 * @return $this 35 */ 36 public function setName(string $name): NameableInterface 37 { 38 $this->_name = $name; 39 40 return $this; 41 } 42 43 /** 44 * Retrieve the name of this aggregation. 45 * 46 * @return string 47 */ 48 public function getName(): string 49 { 50 return $this->_name; 51 } 52 53 /** 54 * Retrieve all subaggregations belonging to this aggregation. 55 * 56 * @return array 57 */ 58 public function getAggs(): array 59 { 60 return $this->_aggs; 61 } 62 63 /** 64 * Add a sub-aggregation. 65 * 66 * @param AbstractAggregation $aggregation 67 * 68 * @throws \Elastica\Exception\InvalidException 69 * 70 * @return $this 71 */ 72 public function addAggregation(AbstractAggregation $aggregation): self 73 { 74 if ($aggregation instanceof GlobalAggregation) { 75 throw new InvalidException('Global aggregators can only be placed as top level aggregators'); 76 } 77 78 $this->_aggs[] = $aggregation; 79 80 return $this; 81 } 82 83 /** 84 * @return array 85 */ 86 public function toArray(): array 87 { 88 $array = parent::toArray(); 89 90 if (\array_key_exists('global_aggregation', $array)) { 91 // compensate for class name GlobalAggregation 92 $array = ['global' => new \stdClass()]; 93 } 94 if (\sizeof($this->_aggs)) { 95 $array['aggs'] = $this->_convertArrayable($this->_aggs); 96 } 97 98 return $array; 99 } 100} 101