xref: /plugin/elasticsearch/vendor/ruflin/elastica/src/Node/Stats.php (revision d832d53af2a0f84c34c8d5f17c93ffaa85869e5d) !
1<?php
2
3namespace Elastica\Node;
4
5use Elastica\Node as BaseNode;
6use Elastica\Response;
7use Elasticsearch\Endpoints\Nodes\Stats as NodesStats;
8
9/**
10 * Elastica cluster node object.
11 *
12 * @author Nicolas Ruflin <spam@ruflin.com>
13 *
14 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-status.html
15 */
16class Stats
17{
18    /**
19     * Response.
20     *
21     * @var Response Response object
22     */
23    protected $_response;
24
25    /**
26     * Stats data.
27     *
28     * @var array stats data
29     */
30    protected $_data = [];
31
32    /**
33     * Node.
34     *
35     * @var BaseNode Node object
36     */
37    protected $_node;
38
39    /**
40     * Create new stats for node.
41     *
42     * @param BaseNode $node Elastica node object
43     */
44    public function __construct(BaseNode $node)
45    {
46        $this->_node = $node;
47        $this->refresh();
48    }
49
50    /**
51     * Returns all node stats as array based on the arguments.
52     *
53     * Several arguments can be use
54     * get('index', 'test', 'example')
55     *
56     * @return array|null Node stats for the given field or null if not found
57     */
58    public function get(...$args)
59    {
60        $data = $this->getData();
61
62        foreach ($args as $arg) {
63            if (isset($data[$arg])) {
64                $data = $data[$arg];
65            } else {
66                return null;
67            }
68        }
69
70        return $data;
71    }
72
73    /**
74     * Returns all stats data.
75     *
76     * @return array Data array
77     */
78    public function getData(): array
79    {
80        return $this->_data;
81    }
82
83    /**
84     * Returns node object.
85     *
86     * @return BaseNode Node object
87     */
88    public function getNode(): BaseNode
89    {
90        return $this->_node;
91    }
92
93    /**
94     * Returns response object.
95     *
96     * @return Response Response object
97     */
98    public function getResponse(): Response
99    {
100        return $this->_response;
101    }
102
103    /**
104     * Reloads all nodes information. Has to be called if informations changed.
105     *
106     * @return Response Response object
107     */
108    public function refresh(): Response
109    {
110        // TODO: Use only NodesStats when dropping support for elasticsearch/elasticsearch 7.x
111        $endpoint = \class_exists(NodesStats::class) ? new NodesStats() : new \Elasticsearch\Endpoints\Cluster\Nodes\Stats();
112        $endpoint->setNodeId($this->getNode()->getName());
113
114        $this->_response = $this->getNode()->getClient()->requestEndpoint($endpoint);
115        $data = $this->getResponse()->getData();
116        $this->_data = \reset($data['nodes']);
117
118        return $this->_response;
119    }
120}
121