ScriptFields.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Elastica\Script;
  3. use Elastica\Exception\InvalidException;
  4. use Elastica\Param;
  5. /**
  6. * Container for scripts as fields.
  7. *
  8. * @author Sebastien Lavoie <github@lavoie.sl>
  9. *
  10. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
  11. */
  12. class ScriptFields extends Param
  13. {
  14. /**
  15. * @param \Elastica\Script\Script[]|array $scripts OPTIONAL
  16. */
  17. public function __construct(array $scripts = [])
  18. {
  19. if ($scripts) {
  20. $this->setScripts($scripts);
  21. }
  22. }
  23. /**
  24. * @param string $name Name of the Script field
  25. * @param \Elastica\Script\AbstractScript $script
  26. *
  27. * @throws \Elastica\Exception\InvalidException
  28. *
  29. * @return $this
  30. */
  31. public function addScript($name, AbstractScript $script)
  32. {
  33. if (!is_string($name) || !strlen($name)) {
  34. throw new InvalidException('The name of a Script is required and must be a string');
  35. }
  36. $this->setParam($name, $script);
  37. return $this;
  38. }
  39. /**
  40. * @param \Elastica\Script\Script[]|array $scripts Associative array of string => Elastica\Script\Script
  41. *
  42. * @return $this
  43. */
  44. public function setScripts(array $scripts)
  45. {
  46. $this->_params = [];
  47. foreach ($scripts as $name => $script) {
  48. $this->addScript($name, $script);
  49. }
  50. return $this;
  51. }
  52. /**
  53. * @return array
  54. */
  55. public function toArray()
  56. {
  57. return $this->_convertArrayable($this->_params);
  58. }
  59. }