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