Completed
Push — master ( d3ac62...0cb203 )
by Federico
02:08
created

lib/Elastica/Script/ScriptFields.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Elastica\Script;
4
5
use Elastica\Exception\InvalidException;
6
use Elastica\Param;
7
8
/**
9
 * Container for scripts as fields.
10
 *
11
 * @author Sebastien Lavoie <[email protected]>
12
 *
13
 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
14
 */
15
class ScriptFields extends Param
16
{
17
    /**
18
     * @param \Elastica\Script\Script[]|array $scripts OPTIONAL
19
     */
20
    public function __construct(array $scripts = [])
21
    {
22
        if ($scripts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $scripts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
23
            $this->setScripts($scripts);
24
        }
25
    }
26
27
    /**
28
     * @param string                          $name   Name of the Script field
29
     * @param \Elastica\Script\AbstractScript $script
30
     *
31
     * @throws \Elastica\Exception\InvalidException
32
     *
33
     * @return $this
34
     */
35
    public function addScript($name, AbstractScript $script)
36
    {
37
        if (!is_string($name) || !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 \Elastica\Script\Script[]|array $scripts Associative array of string => Elastica\Script\Script
47
     *
48
     * @return $this
49
     */
50
    public function setScripts(array $scripts)
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()
64
    {
65
        return $this->_convertArrayable($this->_params);
66
    }
67
}
68