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