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 array<string, AbstractScript> $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     *
30     * @throws InvalidException
31     *
32     * @return $this
33     */
34    public function addScript(string $name, AbstractScript $script): self
35    {
36        if (!\strlen($name)) {
37            throw new InvalidException('The name of a Script is required and must be a string');
38        }
39        $this->setParam($name, $script);
40
41        return $this;
42    }
43
44    /**
45     * @param array<string, AbstractScript> $scripts Associative array of string => Elastica\Script\Script
46     *
47     * @return $this
48     */
49    public function setScripts(array $scripts): self
50    {
51        $this->_params = [];
52        foreach ($scripts as $name => $script) {
53            $this->addScript($name, $script);
54        }
55
56        return $this;
57    }
58
59    public function toArray(): array
60    {
61        return $this->_convertArrayable($this->_params);
62    }
63}
64