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