AbstractSimpleAggregation.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Elastica\Aggregation;
  3. use Elastica\Exception\InvalidException;
  4. abstract class AbstractSimpleAggregation extends AbstractAggregation
  5. {
  6. /**
  7. * Set the field for this aggregation.
  8. *
  9. * @param string $field the name of the document field on which to perform this aggregation
  10. *
  11. * @return $this
  12. */
  13. public function setField($field)
  14. {
  15. return $this->setParam('field', $field);
  16. }
  17. /**
  18. * Set a script for this aggregation.
  19. *
  20. * @param string|\Elastica\Script\AbstractScript $script
  21. *
  22. * @return $this
  23. */
  24. public function setScript($script)
  25. {
  26. return $this->setParam('script', $script);
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function toArray()
  32. {
  33. if (!$this->hasParam('field') && !$this->hasParam('script')) {
  34. throw new InvalidException(
  35. 'Either the field param or the script param should be set'
  36. );
  37. }
  38. $array = parent::toArray();
  39. $baseName = $this->_getBaseName();
  40. if (isset($array[$baseName]['script']) && is_array($array[$baseName]['script'])) {
  41. $script = $array[$baseName]['script'];
  42. unset($array[$baseName]['script']);
  43. $array[$baseName] = array_merge($array[$baseName], $script);
  44. }
  45. return $array;
  46. }
  47. }