| #0 | Elasticsearch\ConnectionPool\StaticNoPingConnectionPool->nextConnection() /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php (72) <?php
namespace Elasticsearch;
use Elasticsearch\Common\Exceptions;
use Elasticsearch\ConnectionPool\AbstractConnectionPool;
use Elasticsearch\Connections\Connection;
use Elasticsearch\Connections\ConnectionInterface;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
use Psr\Log\LoggerInterface;
/**
* Class Transport
*
* @category Elasticsearch
* @package Elasticsearch
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Transport
{
/**
* @var AbstractConnectionPool
*/
public $connectionPool;
/**
* @var LoggerInterface
*/
private $log;
/** @var int */
public $retryAttempts = 0;
/** @var Connection */
public $lastConnection;
/** @var int */
public $retries;
/**
* Transport class is responsible for dispatching requests to the
* underlying cluster connections
*
* @param $retries
* @param bool $sniffOnStart
* @param ConnectionPool\AbstractConnectionPool $connectionPool
* @param \Psr\Log\LoggerInterface $log Monolog logger object
*/
public function __construct($retries, $sniffOnStart = false, AbstractConnectionPool $connectionPool, LoggerInterface $log)
{
$this->log = $log;
$this->connectionPool = $connectionPool;
$this->retries = $retries;
if ($sniffOnStart === true) {
$this->log->notice('Sniff on Start.');
$this->connectionPool->scheduleCheck();
}
}
/**
* Returns a single connection from the connection pool
* Potentially performs a sniffing step before returning
*
* @return ConnectionInterface Connection
*/
public function getConnection()
{
return $this->connectionPool->nextConnection();
}
/**
* Perform a request to the Cluster
*
* @param string $method HTTP method to use
* @param string $uri HTTP URI to send request to
* @param null $params Optional query parameters
* @param null $body Optional query body
* @param array $options
*
* @throws Common\Exceptions\NoNodesAvailableException|\Exception
* @return FutureArrayInterface
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [])
{
try {
$connection = $this->getConnection();
} catch (Exceptions\NoNodesAvailableException $exception) {
$this->log->critical('No alive nodes found in cluster');
throw $exception;
}
$response = array();
$caughtException = null;
$this->lastConnection = $connection;
$future = $connection->performRequest(
$method,
$uri,
$params,
$body,
$options,
$this
);
$future->promise()->then(
//onSuccess
function ($response) {
$this->retryAttempts = 0;
// Note, this could be a 4xx or 5xx error
},
//onFailure
function ($response) {
//some kind of real faiure here, like a timeout
$this->connectionPool->scheduleCheck();
// log stuff
});
return $future;
}
/**
* @param FutureArrayInterface $result Response of a request (promise)
* @param array $options Options for transport
*
* @return callable|array
*/
public function resultOrFuture($result, $options = [])
{
$response = null;
$async = isset($options['client']['future']) ? $options['client']['future'] : null;
if (is_null($async) || $async === false) {
do {
$result = $result->wait();
} while ($result instanceof FutureArrayInterface);
return $result;
} elseif ($async === true || $async === 'lazy') {
return $result;
}
}
/**
* @param $request
*
* @return bool
*/
public function shouldRetry($request)
{
if ($this->retryAttempts < $this->retries) {
$this->retryAttempts += 1;
return true;
}
return false;
}
/**
* Returns the last used connection so that it may be inspected. Mainly
* for debugging/testing purposes.
*
* @return Connection
*/
public function getLastConnection()
{
return $this->lastConnection;
}
}
|
| #1 | Elasticsearch\Transport->getConnection() /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php (90) <?php
namespace Elasticsearch;
use Elasticsearch\Common\Exceptions;
use Elasticsearch\ConnectionPool\AbstractConnectionPool;
use Elasticsearch\Connections\Connection;
use Elasticsearch\Connections\ConnectionInterface;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
use Psr\Log\LoggerInterface;
/**
* Class Transport
*
* @category Elasticsearch
* @package Elasticsearch
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Transport
{
/**
* @var AbstractConnectionPool
*/
public $connectionPool;
/**
* @var LoggerInterface
*/
private $log;
/** @var int */
public $retryAttempts = 0;
/** @var Connection */
public $lastConnection;
/** @var int */
public $retries;
/**
* Transport class is responsible for dispatching requests to the
* underlying cluster connections
*
* @param $retries
* @param bool $sniffOnStart
* @param ConnectionPool\AbstractConnectionPool $connectionPool
* @param \Psr\Log\LoggerInterface $log Monolog logger object
*/
public function __construct($retries, $sniffOnStart = false, AbstractConnectionPool $connectionPool, LoggerInterface $log)
{
$this->log = $log;
$this->connectionPool = $connectionPool;
$this->retries = $retries;
if ($sniffOnStart === true) {
$this->log->notice('Sniff on Start.');
$this->connectionPool->scheduleCheck();
}
}
/**
* Returns a single connection from the connection pool
* Potentially performs a sniffing step before returning
*
* @return ConnectionInterface Connection
*/
public function getConnection()
{
return $this->connectionPool->nextConnection();
}
/**
* Perform a request to the Cluster
*
* @param string $method HTTP method to use
* @param string $uri HTTP URI to send request to
* @param null $params Optional query parameters
* @param null $body Optional query body
* @param array $options
*
* @throws Common\Exceptions\NoNodesAvailableException|\Exception
* @return FutureArrayInterface
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [])
{
try {
$connection = $this->getConnection();
} catch (Exceptions\NoNodesAvailableException $exception) {
$this->log->critical('No alive nodes found in cluster');
throw $exception;
}
$response = array();
$caughtException = null;
$this->lastConnection = $connection;
$future = $connection->performRequest(
$method,
$uri,
$params,
$body,
$options,
$this
);
$future->promise()->then(
//onSuccess
function ($response) {
$this->retryAttempts = 0;
// Note, this could be a 4xx or 5xx error
},
//onFailure
function ($response) {
//some kind of real faiure here, like a timeout
$this->connectionPool->scheduleCheck();
// log stuff
});
return $future;
}
/**
* @param FutureArrayInterface $result Response of a request (promise)
* @param array $options Options for transport
*
* @return callable|array
*/
public function resultOrFuture($result, $options = [])
{
$response = null;
$async = isset($options['client']['future']) ? $options['client']['future'] : null;
if (is_null($async) || $async === false) {
do {
$result = $result->wait();
} while ($result instanceof FutureArrayInterface);
return $result;
} elseif ($async === true || $async === 'lazy') {
return $result;
}
}
/**
* @param $request
*
* @return bool
*/
public function shouldRetry($request)
{
if ($this->retryAttempts < $this->retries) {
$this->retryAttempts += 1;
return true;
}
return false;
}
/**
* Returns the last used connection so that it may be inspected. Mainly
* for debugging/testing purposes.
*
* @return Connection
*/
public function getLastConnection()
{
return $this->lastConnection;
}
}
|
| #2 | Elasticsearch\Transport->performRequest(HEAD, /sgr, Array(), null, Array([client] => Array([verbose] => 1))) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php (240) <?php
namespace Elasticsearch\Connections;
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost;
use Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException;
use Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\MaxRetriesException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RequestTimeout408Exception;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\ServerErrorResponseException;
use Elasticsearch\Common\Exceptions\TransportException;
use Elasticsearch\Serializers\SerializerInterface;
use Elasticsearch\Transport;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Exception\ConnectException;
use GuzzleHttp\Ring\Exception\RingException;
use Psr\Log\LoggerInterface;
/**
* Class AbstractConnection
*
* @category Elasticsearch
* @package Elasticsearch\Connections
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Connection implements ConnectionInterface
{
/** @var callable */
protected $handler;
/** @var SerializerInterface */
protected $serializer;
/**
* @var string
*/
protected $transportSchema = 'http'; // TODO depreciate this default
/**
* @var string
*/
protected $host;
/**
* @var string || null
*/
protected $path;
/**
* @var LoggerInterface
*/
protected $log;
/**
* @var LoggerInterface
*/
protected $trace;
/**
* @var array
*/
protected $connectionParams;
/** @var array */
protected $headers = [];
/** @var bool */
protected $isAlive = false;
/** @var float */
private $pingTimeout = 1; //TODO expose this
/** @var int */
private $lastPing = 0;
/** @var int */
private $failedPings = 0;
private $lastRequest = array();
/**
* Constructor
*
* @param $handler
* @param array $hostDetails
* @param array $connectionParams Array of connection-specific parameters
* @param \Elasticsearch\Serializers\SerializerInterface $serializer
* @param \Psr\Log\LoggerInterface $log Logger object
* @param \Psr\Log\LoggerInterface $trace
*/
public function __construct($handler, $hostDetails, $connectionParams,
SerializerInterface $serializer, LoggerInterface $log, LoggerInterface $trace)
{
if (isset($hostDetails['port']) !== true) {
$hostDetails['port'] = 9200;
}
if (isset($hostDetails['scheme'])) {
$this->transportSchema = $hostDetails['scheme'];
}
if (isset($hostDetails['user']) && isset($hostDetails['pass'])) {
$connectionParams['client']['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$connectionParams['client']['curl'][CURLOPT_USERPWD] = $hostDetails['user'].':'.$hostDetails['pass'];
}
if (isset($connectionParams['client']['headers']) === true) {
$this->headers = $connectionParams['client']['headers'];
unset($connectionParams['client']['headers']);
}
$host = $hostDetails['host'].':'.$hostDetails['port'];
$path = null;
if (isset($hostDetails['path']) === true) {
$path = $hostDetails['path'];
}
$this->host = $host;
$this->path = $path;
$this->log = $log;
$this->trace = $trace;
$this->connectionParams = $connectionParams;
$this->serializer = $serializer;
$this->handler = $this->wrapHandler($handler, $log, $trace);
}
/**
* @param $method
* @param $uri
* @param null $params
* @param null $body
* @param array $options
* @param \Elasticsearch\Transport $transport
* @return mixed
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [], Transport $transport = null)
{
if (isset($body) === true) {
$body = $this->serializer->serialize($body);
}
$request = [
'http_method' => $method,
'scheme' => $this->transportSchema,
'uri' => $this->getURI($uri, $params),
'body' => $body,
'headers' => array_merge([
'host' => [$this->host]
], $this->headers)
];
$request = array_merge_recursive($request, $this->connectionParams, $options);
// RingPHP does not like if client is empty
if (empty($request['client'])) {
unset($request['client']);
}
$handler = $this->handler;
$future = $handler($request, $this, $transport, $options);
return $future;
}
/** @return string */
public function getTransportSchema()
{
return $this->transportSchema;
}
/** @return array */
public function getLastRequestInfo()
{
return $this->lastRequest;
}
private function wrapHandler(callable $handler, LoggerInterface $logger, LoggerInterface $tracer)
{
return function (array $request, Connection $connection, Transport $transport = null, $options) use ($handler, $logger, $tracer) {
$this->lastRequest = [];
$this->lastRequest['request'] = $request;
// Send the request using the wrapped handler.
$response = Core::proxy($handler($request), function ($response) use ($connection, $transport, $logger, $tracer, $request, $options) {
$this->lastRequest['response'] = $response;
if (isset($response['error']) === true) {
if ($response['error'] instanceof ConnectException || $response['error'] instanceof RingException) {
$this->log->warning("Curl exception encountered.");
$exception = $this->getCurlRetryException($request, $response);
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
$node = $connection->getHost();
$this->log->warning("Marking node $node dead.");
$connection->markDead();
// If the transport has not been set, we are inside a Ping or Sniff,
// so we don't want to retrigger retries anyway.
//
// TODO this could be handled better, but we are limited because connectionpools do not
// have access to Transport. Architecturally, all of this needs to be refactored
if (isset($transport) === true) {
$transport->connectionPool->scheduleCheck();
$neverRetry = isset($request['client']['never_retry']) ? $request['client']['never_retry'] : false;
$shouldRetry = $transport->shouldRetry($request);
$shouldRetryText = ($shouldRetry) ? 'true' : 'false';
$this->log->warning("Retries left? $shouldRetryText");
if ($shouldRetry && !$neverRetry) {
return $transport->performRequest(
$request['http_method'],
$request['uri'],
[],
$request['body'],
$options
);
}
}
$this->log->warning("Out of retries, throwing exception from $node");
// Only throw if we run out of retries
throw $exception;
} else {
// Something went seriously wrong, bail
$exception = new TransportException($response['error']->getMessage());
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
} else {
$connection->markAlive();
if (isset($response['body']) === true) {
$response['body'] = stream_get_contents($response['body']);
$this->lastRequest['response']['body'] = $response['body'];
}
if ($response['status'] >= 400 && $response['status'] < 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process4xxError($request, $response, $ignore);
} elseif ($response['status'] >= 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process5xxError($request, $response, $ignore);
}
// No error, deserialize
$response['body'] = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
}
$this->logRequestSuccess(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time']
);
return isset($request['client']['verbose']) && $request['client']['verbose'] === true ? $response : $response['body'];
});
return $response;
};
}
/**
* @param string $uri
* @param array $params
*
* @return string
*/
private function getURI($uri, $params)
{
if (isset($params) === true && !empty($params)) {
array_walk($params, function (&$value, &$key) {
if ($value === true) {
$value = 'true';
} else if ($value === false) {
$value = 'false';
}
});
$uri .= '?' . http_build_query($params);
}
if ($this->path !== null) {
$uri = $this->path . $uri;
}
return $uri;
}
/**
* Log a successful request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param string $statusCode
* @param string $response
* @param string $duration
*
* @return void
*/
public function logRequestSuccess($method, $fullURI, $body, $headers, $statusCode, $response, $duration)
{
$this->log->debug('Request Body', array($body));
$this->log->info(
'Request Success:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
$this->log->debug('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* Log a a failed request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param null|string $statusCode
* @param null|string $response
* @param string $duration
* @param \Exception|null $exception
*
* @return void
*/
public function logRequestFail($method, $fullURI, $body, $headers, $statusCode, $response, $duration, \Exception $exception)
{
$this->log->debug('Request Body', array($body));
$this->log->warning(
'Request Failure:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
'error' => $exception->getMessage(),
)
);
$this->log->warning('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* @return bool
*/
public function ping()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true,
'verbose' => true
]
];
try {
$response = $this->performRequest('HEAD', '/', null, null, $options);
$response = $response->wait();
} catch (TransportException $exception) {
$this->markDead();
return false;
}
if ($response['status'] === 200) {
$this->markAlive();
return true;
} else {
$this->markDead();
return false;
}
}
/**
* @return array
*/
public function sniff()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true
]
];
return $this->performRequest('GET', '/_nodes/_all/clear', null, null, $options);
}
/**
* @return bool
*/
public function isAlive()
{
return $this->isAlive;
}
public function markAlive()
{
$this->failedPings = 0;
$this->isAlive = true;
$this->lastPing = time();
}
public function markDead()
{
$this->isAlive = false;
$this->failedPings += 1;
$this->lastPing = time();
}
/**
* @return int
*/
public function getLastPing()
{
return $this->lastPing;
}
/**
* @return int
*/
public function getPingFailures()
{
return $this->failedPings;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return null|string
*/
public function getUserPass()
{
if (isset($this->connectionParams['client']['curl'][CURLOPT_USERPWD]) === true) {
return $this->connectionParams['client']['curl'][CURLOPT_USERPWD];
}
return null;
}
/**
* @return null|string
*/
public function getPath()
{
return $this->path;
}
/**
* @param $request
* @param $response
* @return \Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost|\Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException|\Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException|\Elasticsearch\Common\Exceptions\MaxRetriesException
*/
protected function getCurlRetryException($request, $response)
{
$exception = null;
$message = $response['error']->getMessage();
$exception = new MaxRetriesException($message);
switch ($response['curl']['errno']) {
case 6:
$exception = new CouldNotResolveHostException($message, null, $exception);
break;
case 7:
$exception = new CouldNotConnectToHost($message, null, $exception);
break;
case 28:
$exception = new OperationTimeoutException($message, null, $exception);
break;
}
return $exception;
}
/**
* Construct a string cURL command
*
* @param string $method HTTP method
* @param string $uri Full URI of request
* @param string $body Request body
*
* @return string
*/
private function buildCurlCommand($method, $uri, $body)
{
if (strpos($uri, '?') === false) {
$uri .= '?pretty=true';
} else {
str_replace('?', '?pretty=true', $uri);
}
$curlCommand = 'curl -X' . strtoupper($method);
$curlCommand .= " '" . $uri . "'";
if (isset($body) === true && $body !== '') {
$curlCommand .= " -d '" . $body . "'";
}
return $curlCommand;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\AlreadyExpiredException|\Elasticsearch\Common\Exceptions\BadRequest400Exception|\Elasticsearch\Common\Exceptions\Conflict409Exception|\Elasticsearch\Common\Exceptions\Forbidden403Exception|\Elasticsearch\Common\Exceptions\Missing404Exception|\Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException|null
*/
private function process4xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize400Error($response);
if (array_search($response['status'], $ignore) !== false) {
return;
}
if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
$exception = new AlreadyExpiredException($responseBody, $statusCode);
} elseif ($statusCode === 403) {
$exception = new Forbidden403Exception($responseBody, $statusCode);
} elseif ($statusCode === 404) {
$exception = new Missing404Exception($responseBody, $statusCode);
} elseif ($statusCode === 409) {
$exception = new Conflict409Exception($responseBody, $statusCode);
} elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
$exception = new ScriptLangNotSupportedException($responseBody. $statusCode);
} elseif ($statusCode === 408) {
$exception = new RequestTimeout408Exception($responseBody, $statusCode);
} else {
$exception = new BadRequest400Exception($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException|\Elasticsearch\Common\Exceptions\NoShardAvailableException|\Elasticsearch\Common\Exceptions\RoutingMissingException|\Elasticsearch\Common\Exceptions\ServerErrorResponseException
*/
private function process5xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize500Error($response);
$exceptionText = "[$statusCode Server Exception] ".$exception->getMessage();
$this->log->error($exceptionText);
$this->log->error($exception->getTraceAsString());
if (array_search($statusCode, $ignore) !== false) {
return;
}
if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
$exception = new RoutingMissingException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/', $responseBody) === 1) {
$exception = new NoDocumentsToGetException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
$exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception);
} else {
$exception = new ServerErrorResponseException($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
private function tryDeserialize400Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\BadRequest400Exception');
}
private function tryDeserialize500Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\ServerErrorResponseException');
}
private function tryDeserializeError($response, $errorClass)
{
$error = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
if (is_array($error) === true) {
// 2.0 structured exceptions
if (isset($error['error']['reason']) === true) {
// Try to use root cause first (only grabs the first root cause)
$root = $error['error']['root_cause'];
if (isset($root) && isset($root[0])) {
$cause = $root[0]['reason'];
$type = $root[0]['type'];
} else {
$cause = $error['error']['reason'];
$type = $error['error']['type'];
}
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass("$type: $cause", $response['status'], $original);
} elseif (isset($error['error']) === true) {
// <2.0 semi-structured exceptions
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass($error['error'], $response['status'], $original);
}
// <2.0 "i just blew up" nonstructured exception
// $error is an array but we don't know the format, reuse the response body instead
return new $errorClass($response['body'], $response['status']);
}
// <2.0 "i just blew up" nonstructured exception
return new $errorClass($response['body']);
}
}
|
| #3 | Elasticsearch\Connections\Connection->Elasticsearch\Connections\{closure}(Array([transfer_stats] => Array(28), [curl] => Array([error] => Failed connect to 61.14.233.46:9400; Connection refused, [errno] => 7), [effective_url] => http://61.14.233.46:9400/sgr, [status] => (empty string), [reason] => (empty string), [body] => (empty string), [headers] => Array(), [error] => Object(GuzzleHttp\Ring\Exception\ConnectException))) /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/FulfilledPromise.php (28) <?php
namespace React\Promise;
/**
* @deprecated 2.8.0 External usage of FulfilledPromise is deprecated, use `resolve()` instead.
*/
class FulfilledPromise implements ExtendedPromiseInterface, CancellablePromiseInterface
{
private $value;
public function __construct($value = null)
{
if ($value instanceof PromiseInterface) {
throw new \InvalidArgumentException('You cannot create React\Promise\FulfilledPromise with a promise. Use React\Promise\resolve($promiseOrValue) instead.');
}
$this->value = $value;
}
public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null)
{
if (null === $onFulfilled) {
return $this;
}
try {
return resolve($onFulfilled($this->value));
} catch (\Throwable $exception) {
return new RejectedPromise($exception);
} catch (\Exception $exception) {
return new RejectedPromise($exception);
}
}
public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null)
{
if (null === $onFulfilled) {
return;
}
$result = $onFulfilled($this->value);
if ($result instanceof ExtendedPromiseInterface) {
$result->done();
}
}
public function otherwise(callable $onRejected)
{
return $this;
}
public function always(callable $onFulfilledOrRejected)
{
return $this->then(function ($value) use ($onFulfilledOrRejected) {
return resolve($onFulfilledOrRejected())->then(function () use ($value) {
return $value;
});
});
}
public function progress(callable $onProgress)
{
return $this;
}
public function cancel()
{
}
}
|
| #4 | React\Promise\FulfilledPromise->then(Object(Closure), null, null) /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/CompletedFutureValue.php (55) <?php
namespace GuzzleHttp\Ring\Future;
use React\Promise\FulfilledPromise;
use React\Promise\RejectedPromise;
/**
* Represents a future value that has been resolved or rejected.
*/
class CompletedFutureValue implements FutureInterface
{
protected $result;
protected $error;
private $cachedPromise;
/**
* @param mixed $result Resolved result
* @param \Exception $e Error. Pass a GuzzleHttp\Ring\Exception\CancelledFutureAccessException
* to mark the future as cancelled.
*/
public function __construct($result, \Exception $e = null)
{
$this->result = $result;
$this->error = $e;
}
public function wait()
{
if ($this->error) {
throw $this->error;
}
return $this->result;
}
public function cancel() {}
public function promise()
{
if (!$this->cachedPromise) {
$this->cachedPromise = $this->error
? new RejectedPromise($this->error)
: new FulfilledPromise($this->result);
}
return $this->cachedPromise;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return $this->promise()->then($onFulfilled, $onRejected, $onProgress);
}
}
|
| #5 | GuzzleHttp\Ring\Future\CompletedFutureValue->then(Object(Closure), null, null) /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Core.php (341) <?php
namespace GuzzleHttp\Ring;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
use GuzzleHttp\Ring\Future\FutureArray;
/**
* Provides core functionality of Ring handlers and middleware.
*/
class Core
{
/**
* Returns a function that calls all of the provided functions, in order,
* passing the arguments provided to the composed function to each function.
*
* @param callable[] $functions Array of functions to proxy to.
*
* @return callable
*/
public static function callArray(array $functions)
{
return function () use ($functions) {
$args = func_get_args();
foreach ($functions as $fn) {
call_user_func_array($fn, $args);
}
};
}
/**
* Gets an array of header line values from a message for a specific header
*
* This method searches through the "headers" key of a message for a header
* using a case-insensitive search.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return array
*/
public static function headerLines($message, $header)
{
$result = [];
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
$result = array_merge($result, $value);
}
}
}
return $result;
}
/**
* Gets a header value from a message as a string or null
*
* This method searches through the "headers" key of a message for a header
* using a case-insensitive search. The lines of the header are imploded
* using commas into a single string return value.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return string|null Returns the header string if found, or null if not.
*/
public static function header($message, $header)
{
$match = self::headerLines($message, $header);
return $match ? implode(', ', $match) : null;
}
/**
* Returns the first header value from a message as a string or null. If
* a header line contains multiple values separated by a comma, then this
* function will return the first value in the list.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return string|null Returns the value as a string if found.
*/
public static function firstHeader($message, $header)
{
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
// Return the match itself if it is a single value.
$pos = strpos($value[0], ',');
return $pos ? substr($value[0], 0, $pos) : $value[0];
}
}
}
return null;
}
/**
* Returns true if a message has the provided case-insensitive header.
*
* @param array $message Request or response hash.
* @param string $header Header to check
*
* @return bool
*/
public static function hasHeader($message, $header)
{
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
return true;
}
}
}
return false;
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param array $lines Header lines array of strings in the following
* format: "Name: Value"
* @return array
*/
public static function headersFromLines($lines)
{
$headers = [];
foreach ($lines as $line) {
$parts = explode(':', $line, 2);
$headers[trim($parts[0])][] = isset($parts[1])
? trim($parts[1])
: null;
}
return $headers;
}
/**
* Removes a header from a message using a case-insensitive comparison.
*
* @param array $message Message that contains 'headers'
* @param string $header Header to remove
*
* @return array
*/
public static function removeHeader(array $message, $header)
{
if (isset($message['headers'])) {
foreach (array_keys($message['headers']) as $key) {
if (!strcasecmp($header, $key)) {
unset($message['headers'][$key]);
}
}
}
return $message;
}
/**
* Replaces any existing case insensitive headers with the given value.
*
* @param array $message Message that contains 'headers'
* @param string $header Header to set.
* @param array $value Value to set.
*
* @return array
*/
public static function setHeader(array $message, $header, array $value)
{
$message = self::removeHeader($message, $header);
$message['headers'][$header] = $value;
return $message;
}
/**
* Creates a URL string from a request.
*
* If the "url" key is present on the request, it is returned, otherwise
* the url is built up based on the scheme, host, uri, and query_string
* request values.
*
* @param array $request Request to get the URL from
*
* @return string Returns the request URL as a string.
* @throws \InvalidArgumentException if no Host header is present.
*/
public static function url(array $request)
{
if (isset($request['url'])) {
return $request['url'];
}
$uri = (isset($request['scheme'])
? $request['scheme'] : 'http') . '://';
if ($host = self::header($request, 'host')) {
$uri .= $host;
} else {
throw new \InvalidArgumentException('No Host header was provided');
}
if (isset($request['uri'])) {
$uri .= $request['uri'];
}
if (isset($request['query_string'])) {
$uri .= '?' . $request['query_string'];
}
return $uri;
}
/**
* Reads the body of a message into a string.
*
* @param array|FutureArrayInterface $message Array containing a "body" key
*
* @return null|string Returns the body as a string or null if not set.
* @throws \InvalidArgumentException if a request body is invalid.
*/
public static function body($message)
{
if (!isset($message['body'])) {
return null;
}
if ($message['body'] instanceof StreamInterface) {
return (string) $message['body'];
}
switch (gettype($message['body'])) {
case 'string':
return $message['body'];
case 'resource':
return stream_get_contents($message['body']);
case 'object':
if ($message['body'] instanceof \Iterator) {
return implode('', iterator_to_array($message['body']));
} elseif (method_exists($message['body'], '__toString')) {
return (string) $message['body'];
}
default:
throw new \InvalidArgumentException('Invalid request body: '
. self::describeType($message['body']));
}
}
/**
* Rewind the body of the provided message if possible.
*
* @param array $message Message that contains a 'body' field.
*
* @return bool Returns true on success, false on failure
*/
public static function rewindBody($message)
{
if ($message['body'] instanceof StreamInterface) {
return $message['body']->seek(0);
}
if ($message['body'] instanceof \Generator) {
return false;
}
if ($message['body'] instanceof \Iterator) {
$message['body']->rewind();
return true;
}
if (is_resource($message['body'])) {
return rewind($message['body']);
}
return is_string($message['body'])
|| (is_object($message['body'])
&& method_exists($message['body'], '__toString'));
}
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*/
public static function describeType($input)
{
switch (gettype($input)) {
case 'object':
return 'object(' . get_class($input) . ')';
case 'array':
return 'array(' . count($input) . ')';
default:
ob_start();
var_dump($input);
// normalize float vs double
return str_replace('double(', 'float(', rtrim(ob_get_clean()));
}
}
/**
* Sleep for the specified amount of time specified in the request's
* ['client']['delay'] option if present.
*
* This function should only be used when a non-blocking sleep is not
* possible.
*
* @param array $request Request to sleep
*/
public static function doSleep(array $request)
{
if (isset($request['client']['delay'])) {
usleep($request['client']['delay'] * 1000);
}
}
/**
* Returns a proxied future that modifies the dereferenced value of another
* future using a promise.
*
* @param FutureArrayInterface $future Future to wrap with a new future
* @param callable $onFulfilled Invoked when the future fulfilled
* @param callable $onRejected Invoked when the future rejected
* @param callable $onProgress Invoked when the future progresses
*
* @return FutureArray
*/
public static function proxy(
FutureArrayInterface $future,
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return new FutureArray(
$future->then($onFulfilled, $onRejected, $onProgress),
[$future, 'wait'],
[$future, 'cancel']
);
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*/
public static function getDebugResource($value = null)
{
if (is_resource($value)) {
return $value;
} elseif (defined('STDOUT')) {
return STDOUT;
} else {
return fopen('php://output', 'w');
}
}
}
|
| #6 | GuzzleHttp\Ring\Core::proxy(Object(GuzzleHttp\Ring\Future\CompletedFutureArray), Object(Closure)) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php (294) <?php
namespace Elasticsearch\Connections;
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost;
use Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException;
use Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\MaxRetriesException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RequestTimeout408Exception;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\ServerErrorResponseException;
use Elasticsearch\Common\Exceptions\TransportException;
use Elasticsearch\Serializers\SerializerInterface;
use Elasticsearch\Transport;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Exception\ConnectException;
use GuzzleHttp\Ring\Exception\RingException;
use Psr\Log\LoggerInterface;
/**
* Class AbstractConnection
*
* @category Elasticsearch
* @package Elasticsearch\Connections
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Connection implements ConnectionInterface
{
/** @var callable */
protected $handler;
/** @var SerializerInterface */
protected $serializer;
/**
* @var string
*/
protected $transportSchema = 'http'; // TODO depreciate this default
/**
* @var string
*/
protected $host;
/**
* @var string || null
*/
protected $path;
/**
* @var LoggerInterface
*/
protected $log;
/**
* @var LoggerInterface
*/
protected $trace;
/**
* @var array
*/
protected $connectionParams;
/** @var array */
protected $headers = [];
/** @var bool */
protected $isAlive = false;
/** @var float */
private $pingTimeout = 1; //TODO expose this
/** @var int */
private $lastPing = 0;
/** @var int */
private $failedPings = 0;
private $lastRequest = array();
/**
* Constructor
*
* @param $handler
* @param array $hostDetails
* @param array $connectionParams Array of connection-specific parameters
* @param \Elasticsearch\Serializers\SerializerInterface $serializer
* @param \Psr\Log\LoggerInterface $log Logger object
* @param \Psr\Log\LoggerInterface $trace
*/
public function __construct($handler, $hostDetails, $connectionParams,
SerializerInterface $serializer, LoggerInterface $log, LoggerInterface $trace)
{
if (isset($hostDetails['port']) !== true) {
$hostDetails['port'] = 9200;
}
if (isset($hostDetails['scheme'])) {
$this->transportSchema = $hostDetails['scheme'];
}
if (isset($hostDetails['user']) && isset($hostDetails['pass'])) {
$connectionParams['client']['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$connectionParams['client']['curl'][CURLOPT_USERPWD] = $hostDetails['user'].':'.$hostDetails['pass'];
}
if (isset($connectionParams['client']['headers']) === true) {
$this->headers = $connectionParams['client']['headers'];
unset($connectionParams['client']['headers']);
}
$host = $hostDetails['host'].':'.$hostDetails['port'];
$path = null;
if (isset($hostDetails['path']) === true) {
$path = $hostDetails['path'];
}
$this->host = $host;
$this->path = $path;
$this->log = $log;
$this->trace = $trace;
$this->connectionParams = $connectionParams;
$this->serializer = $serializer;
$this->handler = $this->wrapHandler($handler, $log, $trace);
}
/**
* @param $method
* @param $uri
* @param null $params
* @param null $body
* @param array $options
* @param \Elasticsearch\Transport $transport
* @return mixed
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [], Transport $transport = null)
{
if (isset($body) === true) {
$body = $this->serializer->serialize($body);
}
$request = [
'http_method' => $method,
'scheme' => $this->transportSchema,
'uri' => $this->getURI($uri, $params),
'body' => $body,
'headers' => array_merge([
'host' => [$this->host]
], $this->headers)
];
$request = array_merge_recursive($request, $this->connectionParams, $options);
// RingPHP does not like if client is empty
if (empty($request['client'])) {
unset($request['client']);
}
$handler = $this->handler;
$future = $handler($request, $this, $transport, $options);
return $future;
}
/** @return string */
public function getTransportSchema()
{
return $this->transportSchema;
}
/** @return array */
public function getLastRequestInfo()
{
return $this->lastRequest;
}
private function wrapHandler(callable $handler, LoggerInterface $logger, LoggerInterface $tracer)
{
return function (array $request, Connection $connection, Transport $transport = null, $options) use ($handler, $logger, $tracer) {
$this->lastRequest = [];
$this->lastRequest['request'] = $request;
// Send the request using the wrapped handler.
$response = Core::proxy($handler($request), function ($response) use ($connection, $transport, $logger, $tracer, $request, $options) {
$this->lastRequest['response'] = $response;
if (isset($response['error']) === true) {
if ($response['error'] instanceof ConnectException || $response['error'] instanceof RingException) {
$this->log->warning("Curl exception encountered.");
$exception = $this->getCurlRetryException($request, $response);
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
$node = $connection->getHost();
$this->log->warning("Marking node $node dead.");
$connection->markDead();
// If the transport has not been set, we are inside a Ping or Sniff,
// so we don't want to retrigger retries anyway.
//
// TODO this could be handled better, but we are limited because connectionpools do not
// have access to Transport. Architecturally, all of this needs to be refactored
if (isset($transport) === true) {
$transport->connectionPool->scheduleCheck();
$neverRetry = isset($request['client']['never_retry']) ? $request['client']['never_retry'] : false;
$shouldRetry = $transport->shouldRetry($request);
$shouldRetryText = ($shouldRetry) ? 'true' : 'false';
$this->log->warning("Retries left? $shouldRetryText");
if ($shouldRetry && !$neverRetry) {
return $transport->performRequest(
$request['http_method'],
$request['uri'],
[],
$request['body'],
$options
);
}
}
$this->log->warning("Out of retries, throwing exception from $node");
// Only throw if we run out of retries
throw $exception;
} else {
// Something went seriously wrong, bail
$exception = new TransportException($response['error']->getMessage());
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
} else {
$connection->markAlive();
if (isset($response['body']) === true) {
$response['body'] = stream_get_contents($response['body']);
$this->lastRequest['response']['body'] = $response['body'];
}
if ($response['status'] >= 400 && $response['status'] < 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process4xxError($request, $response, $ignore);
} elseif ($response['status'] >= 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process5xxError($request, $response, $ignore);
}
// No error, deserialize
$response['body'] = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
}
$this->logRequestSuccess(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time']
);
return isset($request['client']['verbose']) && $request['client']['verbose'] === true ? $response : $response['body'];
});
return $response;
};
}
/**
* @param string $uri
* @param array $params
*
* @return string
*/
private function getURI($uri, $params)
{
if (isset($params) === true && !empty($params)) {
array_walk($params, function (&$value, &$key) {
if ($value === true) {
$value = 'true';
} else if ($value === false) {
$value = 'false';
}
});
$uri .= '?' . http_build_query($params);
}
if ($this->path !== null) {
$uri = $this->path . $uri;
}
return $uri;
}
/**
* Log a successful request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param string $statusCode
* @param string $response
* @param string $duration
*
* @return void
*/
public function logRequestSuccess($method, $fullURI, $body, $headers, $statusCode, $response, $duration)
{
$this->log->debug('Request Body', array($body));
$this->log->info(
'Request Success:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
$this->log->debug('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* Log a a failed request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param null|string $statusCode
* @param null|string $response
* @param string $duration
* @param \Exception|null $exception
*
* @return void
*/
public function logRequestFail($method, $fullURI, $body, $headers, $statusCode, $response, $duration, \Exception $exception)
{
$this->log->debug('Request Body', array($body));
$this->log->warning(
'Request Failure:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
'error' => $exception->getMessage(),
)
);
$this->log->warning('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* @return bool
*/
public function ping()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true,
'verbose' => true
]
];
try {
$response = $this->performRequest('HEAD', '/', null, null, $options);
$response = $response->wait();
} catch (TransportException $exception) {
$this->markDead();
return false;
}
if ($response['status'] === 200) {
$this->markAlive();
return true;
} else {
$this->markDead();
return false;
}
}
/**
* @return array
*/
public function sniff()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true
]
];
return $this->performRequest('GET', '/_nodes/_all/clear', null, null, $options);
}
/**
* @return bool
*/
public function isAlive()
{
return $this->isAlive;
}
public function markAlive()
{
$this->failedPings = 0;
$this->isAlive = true;
$this->lastPing = time();
}
public function markDead()
{
$this->isAlive = false;
$this->failedPings += 1;
$this->lastPing = time();
}
/**
* @return int
*/
public function getLastPing()
{
return $this->lastPing;
}
/**
* @return int
*/
public function getPingFailures()
{
return $this->failedPings;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return null|string
*/
public function getUserPass()
{
if (isset($this->connectionParams['client']['curl'][CURLOPT_USERPWD]) === true) {
return $this->connectionParams['client']['curl'][CURLOPT_USERPWD];
}
return null;
}
/**
* @return null|string
*/
public function getPath()
{
return $this->path;
}
/**
* @param $request
* @param $response
* @return \Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost|\Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException|\Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException|\Elasticsearch\Common\Exceptions\MaxRetriesException
*/
protected function getCurlRetryException($request, $response)
{
$exception = null;
$message = $response['error']->getMessage();
$exception = new MaxRetriesException($message);
switch ($response['curl']['errno']) {
case 6:
$exception = new CouldNotResolveHostException($message, null, $exception);
break;
case 7:
$exception = new CouldNotConnectToHost($message, null, $exception);
break;
case 28:
$exception = new OperationTimeoutException($message, null, $exception);
break;
}
return $exception;
}
/**
* Construct a string cURL command
*
* @param string $method HTTP method
* @param string $uri Full URI of request
* @param string $body Request body
*
* @return string
*/
private function buildCurlCommand($method, $uri, $body)
{
if (strpos($uri, '?') === false) {
$uri .= '?pretty=true';
} else {
str_replace('?', '?pretty=true', $uri);
}
$curlCommand = 'curl -X' . strtoupper($method);
$curlCommand .= " '" . $uri . "'";
if (isset($body) === true && $body !== '') {
$curlCommand .= " -d '" . $body . "'";
}
return $curlCommand;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\AlreadyExpiredException|\Elasticsearch\Common\Exceptions\BadRequest400Exception|\Elasticsearch\Common\Exceptions\Conflict409Exception|\Elasticsearch\Common\Exceptions\Forbidden403Exception|\Elasticsearch\Common\Exceptions\Missing404Exception|\Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException|null
*/
private function process4xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize400Error($response);
if (array_search($response['status'], $ignore) !== false) {
return;
}
if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
$exception = new AlreadyExpiredException($responseBody, $statusCode);
} elseif ($statusCode === 403) {
$exception = new Forbidden403Exception($responseBody, $statusCode);
} elseif ($statusCode === 404) {
$exception = new Missing404Exception($responseBody, $statusCode);
} elseif ($statusCode === 409) {
$exception = new Conflict409Exception($responseBody, $statusCode);
} elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
$exception = new ScriptLangNotSupportedException($responseBody. $statusCode);
} elseif ($statusCode === 408) {
$exception = new RequestTimeout408Exception($responseBody, $statusCode);
} else {
$exception = new BadRequest400Exception($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException|\Elasticsearch\Common\Exceptions\NoShardAvailableException|\Elasticsearch\Common\Exceptions\RoutingMissingException|\Elasticsearch\Common\Exceptions\ServerErrorResponseException
*/
private function process5xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize500Error($response);
$exceptionText = "[$statusCode Server Exception] ".$exception->getMessage();
$this->log->error($exceptionText);
$this->log->error($exception->getTraceAsString());
if (array_search($statusCode, $ignore) !== false) {
return;
}
if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
$exception = new RoutingMissingException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/', $responseBody) === 1) {
$exception = new NoDocumentsToGetException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
$exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception);
} else {
$exception = new ServerErrorResponseException($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
private function tryDeserialize400Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\BadRequest400Exception');
}
private function tryDeserialize500Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\ServerErrorResponseException');
}
private function tryDeserializeError($response, $errorClass)
{
$error = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
if (is_array($error) === true) {
// 2.0 structured exceptions
if (isset($error['error']['reason']) === true) {
// Try to use root cause first (only grabs the first root cause)
$root = $error['error']['root_cause'];
if (isset($root) && isset($root[0])) {
$cause = $root[0]['reason'];
$type = $root[0]['type'];
} else {
$cause = $error['error']['reason'];
$type = $error['error']['type'];
}
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass("$type: $cause", $response['status'], $original);
} elseif (isset($error['error']) === true) {
// <2.0 semi-structured exceptions
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass($error['error'], $response['status'], $original);
}
// <2.0 "i just blew up" nonstructured exception
// $error is an array but we don't know the format, reuse the response body instead
return new $errorClass($response['body'], $response['status']);
}
// <2.0 "i just blew up" nonstructured exception
return new $errorClass($response['body']);
}
}
|
| #7 | Elasticsearch\Connections\Connection->Elasticsearch\Connections\{closure}(Array([http_method] => HEAD, [scheme] => http, [uri] => /sgr, [body] => (empty string), [headers] => Array([host] => Array([0] => 61.14.233.46:9400), [Content-type] => Array([0] => application/json), [Accept] => Array([0] => application/json)), [client] => Array([curl] => Array([107] => 1, [10005] => elastic:sangiare2020), [verbose] => 1)), Object(Elasticsearch\Connections\Connection), Object(Elasticsearch\Transport), Array([client] => Array([verbose] => 1))) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php (171) <?php
namespace Elasticsearch\Connections;
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost;
use Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException;
use Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\MaxRetriesException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RequestTimeout408Exception;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\ServerErrorResponseException;
use Elasticsearch\Common\Exceptions\TransportException;
use Elasticsearch\Serializers\SerializerInterface;
use Elasticsearch\Transport;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Exception\ConnectException;
use GuzzleHttp\Ring\Exception\RingException;
use Psr\Log\LoggerInterface;
/**
* Class AbstractConnection
*
* @category Elasticsearch
* @package Elasticsearch\Connections
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Connection implements ConnectionInterface
{
/** @var callable */
protected $handler;
/** @var SerializerInterface */
protected $serializer;
/**
* @var string
*/
protected $transportSchema = 'http'; // TODO depreciate this default
/**
* @var string
*/
protected $host;
/**
* @var string || null
*/
protected $path;
/**
* @var LoggerInterface
*/
protected $log;
/**
* @var LoggerInterface
*/
protected $trace;
/**
* @var array
*/
protected $connectionParams;
/** @var array */
protected $headers = [];
/** @var bool */
protected $isAlive = false;
/** @var float */
private $pingTimeout = 1; //TODO expose this
/** @var int */
private $lastPing = 0;
/** @var int */
private $failedPings = 0;
private $lastRequest = array();
/**
* Constructor
*
* @param $handler
* @param array $hostDetails
* @param array $connectionParams Array of connection-specific parameters
* @param \Elasticsearch\Serializers\SerializerInterface $serializer
* @param \Psr\Log\LoggerInterface $log Logger object
* @param \Psr\Log\LoggerInterface $trace
*/
public function __construct($handler, $hostDetails, $connectionParams,
SerializerInterface $serializer, LoggerInterface $log, LoggerInterface $trace)
{
if (isset($hostDetails['port']) !== true) {
$hostDetails['port'] = 9200;
}
if (isset($hostDetails['scheme'])) {
$this->transportSchema = $hostDetails['scheme'];
}
if (isset($hostDetails['user']) && isset($hostDetails['pass'])) {
$connectionParams['client']['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$connectionParams['client']['curl'][CURLOPT_USERPWD] = $hostDetails['user'].':'.$hostDetails['pass'];
}
if (isset($connectionParams['client']['headers']) === true) {
$this->headers = $connectionParams['client']['headers'];
unset($connectionParams['client']['headers']);
}
$host = $hostDetails['host'].':'.$hostDetails['port'];
$path = null;
if (isset($hostDetails['path']) === true) {
$path = $hostDetails['path'];
}
$this->host = $host;
$this->path = $path;
$this->log = $log;
$this->trace = $trace;
$this->connectionParams = $connectionParams;
$this->serializer = $serializer;
$this->handler = $this->wrapHandler($handler, $log, $trace);
}
/**
* @param $method
* @param $uri
* @param null $params
* @param null $body
* @param array $options
* @param \Elasticsearch\Transport $transport
* @return mixed
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [], Transport $transport = null)
{
if (isset($body) === true) {
$body = $this->serializer->serialize($body);
}
$request = [
'http_method' => $method,
'scheme' => $this->transportSchema,
'uri' => $this->getURI($uri, $params),
'body' => $body,
'headers' => array_merge([
'host' => [$this->host]
], $this->headers)
];
$request = array_merge_recursive($request, $this->connectionParams, $options);
// RingPHP does not like if client is empty
if (empty($request['client'])) {
unset($request['client']);
}
$handler = $this->handler;
$future = $handler($request, $this, $transport, $options);
return $future;
}
/** @return string */
public function getTransportSchema()
{
return $this->transportSchema;
}
/** @return array */
public function getLastRequestInfo()
{
return $this->lastRequest;
}
private function wrapHandler(callable $handler, LoggerInterface $logger, LoggerInterface $tracer)
{
return function (array $request, Connection $connection, Transport $transport = null, $options) use ($handler, $logger, $tracer) {
$this->lastRequest = [];
$this->lastRequest['request'] = $request;
// Send the request using the wrapped handler.
$response = Core::proxy($handler($request), function ($response) use ($connection, $transport, $logger, $tracer, $request, $options) {
$this->lastRequest['response'] = $response;
if (isset($response['error']) === true) {
if ($response['error'] instanceof ConnectException || $response['error'] instanceof RingException) {
$this->log->warning("Curl exception encountered.");
$exception = $this->getCurlRetryException($request, $response);
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
$node = $connection->getHost();
$this->log->warning("Marking node $node dead.");
$connection->markDead();
// If the transport has not been set, we are inside a Ping or Sniff,
// so we don't want to retrigger retries anyway.
//
// TODO this could be handled better, but we are limited because connectionpools do not
// have access to Transport. Architecturally, all of this needs to be refactored
if (isset($transport) === true) {
$transport->connectionPool->scheduleCheck();
$neverRetry = isset($request['client']['never_retry']) ? $request['client']['never_retry'] : false;
$shouldRetry = $transport->shouldRetry($request);
$shouldRetryText = ($shouldRetry) ? 'true' : 'false';
$this->log->warning("Retries left? $shouldRetryText");
if ($shouldRetry && !$neverRetry) {
return $transport->performRequest(
$request['http_method'],
$request['uri'],
[],
$request['body'],
$options
);
}
}
$this->log->warning("Out of retries, throwing exception from $node");
// Only throw if we run out of retries
throw $exception;
} else {
// Something went seriously wrong, bail
$exception = new TransportException($response['error']->getMessage());
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
} else {
$connection->markAlive();
if (isset($response['body']) === true) {
$response['body'] = stream_get_contents($response['body']);
$this->lastRequest['response']['body'] = $response['body'];
}
if ($response['status'] >= 400 && $response['status'] < 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process4xxError($request, $response, $ignore);
} elseif ($response['status'] >= 500) {
$ignore = isset($request['client']['ignore']) ? $request['client']['ignore'] : [];
$this->process5xxError($request, $response, $ignore);
}
// No error, deserialize
$response['body'] = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
}
$this->logRequestSuccess(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time']
);
return isset($request['client']['verbose']) && $request['client']['verbose'] === true ? $response : $response['body'];
});
return $response;
};
}
/**
* @param string $uri
* @param array $params
*
* @return string
*/
private function getURI($uri, $params)
{
if (isset($params) === true && !empty($params)) {
array_walk($params, function (&$value, &$key) {
if ($value === true) {
$value = 'true';
} else if ($value === false) {
$value = 'false';
}
});
$uri .= '?' . http_build_query($params);
}
if ($this->path !== null) {
$uri = $this->path . $uri;
}
return $uri;
}
/**
* Log a successful request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param string $statusCode
* @param string $response
* @param string $duration
*
* @return void
*/
public function logRequestSuccess($method, $fullURI, $body, $headers, $statusCode, $response, $duration)
{
$this->log->debug('Request Body', array($body));
$this->log->info(
'Request Success:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
$this->log->debug('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* Log a a failed request
*
* @param string $method
* @param string $fullURI
* @param string $body
* @param array $headers
* @param null|string $statusCode
* @param null|string $response
* @param string $duration
* @param \Exception|null $exception
*
* @return void
*/
public function logRequestFail($method, $fullURI, $body, $headers, $statusCode, $response, $duration, \Exception $exception)
{
$this->log->debug('Request Body', array($body));
$this->log->warning(
'Request Failure:',
array(
'method' => $method,
'uri' => $fullURI,
'headers' => $headers,
'HTTP code' => $statusCode,
'duration' => $duration,
'error' => $exception->getMessage(),
)
);
$this->log->warning('Response', array($response));
// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($method, $fullURI, $body);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $method,
'uri' => $fullURI,
'HTTP code' => $statusCode,
'duration' => $duration,
)
);
}
/**
* @return bool
*/
public function ping()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true,
'verbose' => true
]
];
try {
$response = $this->performRequest('HEAD', '/', null, null, $options);
$response = $response->wait();
} catch (TransportException $exception) {
$this->markDead();
return false;
}
if ($response['status'] === 200) {
$this->markAlive();
return true;
} else {
$this->markDead();
return false;
}
}
/**
* @return array
*/
public function sniff()
{
$options = [
'client' => [
'timeout' => $this->pingTimeout,
'never_retry' => true
]
];
return $this->performRequest('GET', '/_nodes/_all/clear', null, null, $options);
}
/**
* @return bool
*/
public function isAlive()
{
return $this->isAlive;
}
public function markAlive()
{
$this->failedPings = 0;
$this->isAlive = true;
$this->lastPing = time();
}
public function markDead()
{
$this->isAlive = false;
$this->failedPings += 1;
$this->lastPing = time();
}
/**
* @return int
*/
public function getLastPing()
{
return $this->lastPing;
}
/**
* @return int
*/
public function getPingFailures()
{
return $this->failedPings;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return null|string
*/
public function getUserPass()
{
if (isset($this->connectionParams['client']['curl'][CURLOPT_USERPWD]) === true) {
return $this->connectionParams['client']['curl'][CURLOPT_USERPWD];
}
return null;
}
/**
* @return null|string
*/
public function getPath()
{
return $this->path;
}
/**
* @param $request
* @param $response
* @return \Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost|\Elasticsearch\Common\Exceptions\Curl\CouldNotResolveHostException|\Elasticsearch\Common\Exceptions\Curl\OperationTimeoutException|\Elasticsearch\Common\Exceptions\MaxRetriesException
*/
protected function getCurlRetryException($request, $response)
{
$exception = null;
$message = $response['error']->getMessage();
$exception = new MaxRetriesException($message);
switch ($response['curl']['errno']) {
case 6:
$exception = new CouldNotResolveHostException($message, null, $exception);
break;
case 7:
$exception = new CouldNotConnectToHost($message, null, $exception);
break;
case 28:
$exception = new OperationTimeoutException($message, null, $exception);
break;
}
return $exception;
}
/**
* Construct a string cURL command
*
* @param string $method HTTP method
* @param string $uri Full URI of request
* @param string $body Request body
*
* @return string
*/
private function buildCurlCommand($method, $uri, $body)
{
if (strpos($uri, '?') === false) {
$uri .= '?pretty=true';
} else {
str_replace('?', '?pretty=true', $uri);
}
$curlCommand = 'curl -X' . strtoupper($method);
$curlCommand .= " '" . $uri . "'";
if (isset($body) === true && $body !== '') {
$curlCommand .= " -d '" . $body . "'";
}
return $curlCommand;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\AlreadyExpiredException|\Elasticsearch\Common\Exceptions\BadRequest400Exception|\Elasticsearch\Common\Exceptions\Conflict409Exception|\Elasticsearch\Common\Exceptions\Forbidden403Exception|\Elasticsearch\Common\Exceptions\Missing404Exception|\Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException|null
*/
private function process4xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize400Error($response);
if (array_search($response['status'], $ignore) !== false) {
return;
}
if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
$exception = new AlreadyExpiredException($responseBody, $statusCode);
} elseif ($statusCode === 403) {
$exception = new Forbidden403Exception($responseBody, $statusCode);
} elseif ($statusCode === 404) {
$exception = new Missing404Exception($responseBody, $statusCode);
} elseif ($statusCode === 409) {
$exception = new Conflict409Exception($responseBody, $statusCode);
} elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
$exception = new ScriptLangNotSupportedException($responseBody. $statusCode);
} elseif ($statusCode === 408) {
$exception = new RequestTimeout408Exception($responseBody, $statusCode);
} else {
$exception = new BadRequest400Exception($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
/**
* @param $request
* @param $response
* @param $ignore
* @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException|\Elasticsearch\Common\Exceptions\NoShardAvailableException|\Elasticsearch\Common\Exceptions\RoutingMissingException|\Elasticsearch\Common\Exceptions\ServerErrorResponseException
*/
private function process5xxError($request, $response, $ignore)
{
$statusCode = $response['status'];
$responseBody = $response['body'];
/** @var \Exception $exception */
$exception = $this->tryDeserialize500Error($response);
$exceptionText = "[$statusCode Server Exception] ".$exception->getMessage();
$this->log->error($exceptionText);
$this->log->error($exception->getTraceAsString());
if (array_search($statusCode, $ignore) !== false) {
return;
}
if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
$exception = new RoutingMissingException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/', $responseBody) === 1) {
$exception = new NoDocumentsToGetException($exception->getMessage(), $statusCode, $exception);
} elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
$exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception);
} else {
$exception = new ServerErrorResponseException($responseBody, $statusCode);
}
$this->logRequestFail(
$request['http_method'],
$response['effective_url'],
$request['body'],
$request['headers'],
$response['status'],
$response['body'],
$response['transfer_stats']['total_time'],
$exception
);
throw $exception;
}
private function tryDeserialize400Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\BadRequest400Exception');
}
private function tryDeserialize500Error($response)
{
return $this->tryDeserializeError($response, 'Elasticsearch\Common\Exceptions\ServerErrorResponseException');
}
private function tryDeserializeError($response, $errorClass)
{
$error = $this->serializer->deserialize($response['body'], $response['transfer_stats']);
if (is_array($error) === true) {
// 2.0 structured exceptions
if (isset($error['error']['reason']) === true) {
// Try to use root cause first (only grabs the first root cause)
$root = $error['error']['root_cause'];
if (isset($root) && isset($root[0])) {
$cause = $root[0]['reason'];
$type = $root[0]['type'];
} else {
$cause = $error['error']['reason'];
$type = $error['error']['type'];
}
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass("$type: $cause", $response['status'], $original);
} elseif (isset($error['error']) === true) {
// <2.0 semi-structured exceptions
$original = new $errorClass($response['body'], $response['status']);
return new $errorClass($error['error'], $response['status'], $original);
}
// <2.0 "i just blew up" nonstructured exception
// $error is an array but we don't know the format, reuse the response body instead
return new $errorClass($response['body'], $response['status']);
}
// <2.0 "i just blew up" nonstructured exception
return new $errorClass($response['body']);
}
}
|
| #8 | Elasticsearch\Connections\Connection->performRequest(HEAD, /sgr, Array(), null, Array([client] => Array([verbose] => 1)), Object(Elasticsearch\Transport)) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php (106) <?php
namespace Elasticsearch;
use Elasticsearch\Common\Exceptions;
use Elasticsearch\ConnectionPool\AbstractConnectionPool;
use Elasticsearch\Connections\Connection;
use Elasticsearch\Connections\ConnectionInterface;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
use Psr\Log\LoggerInterface;
/**
* Class Transport
*
* @category Elasticsearch
* @package Elasticsearch
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class Transport
{
/**
* @var AbstractConnectionPool
*/
public $connectionPool;
/**
* @var LoggerInterface
*/
private $log;
/** @var int */
public $retryAttempts = 0;
/** @var Connection */
public $lastConnection;
/** @var int */
public $retries;
/**
* Transport class is responsible for dispatching requests to the
* underlying cluster connections
*
* @param $retries
* @param bool $sniffOnStart
* @param ConnectionPool\AbstractConnectionPool $connectionPool
* @param \Psr\Log\LoggerInterface $log Monolog logger object
*/
public function __construct($retries, $sniffOnStart = false, AbstractConnectionPool $connectionPool, LoggerInterface $log)
{
$this->log = $log;
$this->connectionPool = $connectionPool;
$this->retries = $retries;
if ($sniffOnStart === true) {
$this->log->notice('Sniff on Start.');
$this->connectionPool->scheduleCheck();
}
}
/**
* Returns a single connection from the connection pool
* Potentially performs a sniffing step before returning
*
* @return ConnectionInterface Connection
*/
public function getConnection()
{
return $this->connectionPool->nextConnection();
}
/**
* Perform a request to the Cluster
*
* @param string $method HTTP method to use
* @param string $uri HTTP URI to send request to
* @param null $params Optional query parameters
* @param null $body Optional query body
* @param array $options
*
* @throws Common\Exceptions\NoNodesAvailableException|\Exception
* @return FutureArrayInterface
*/
public function performRequest($method, $uri, $params = null, $body = null, $options = [])
{
try {
$connection = $this->getConnection();
} catch (Exceptions\NoNodesAvailableException $exception) {
$this->log->critical('No alive nodes found in cluster');
throw $exception;
}
$response = array();
$caughtException = null;
$this->lastConnection = $connection;
$future = $connection->performRequest(
$method,
$uri,
$params,
$body,
$options,
$this
);
$future->promise()->then(
//onSuccess
function ($response) {
$this->retryAttempts = 0;
// Note, this could be a 4xx or 5xx error
},
//onFailure
function ($response) {
//some kind of real faiure here, like a timeout
$this->connectionPool->scheduleCheck();
// log stuff
});
return $future;
}
/**
* @param FutureArrayInterface $result Response of a request (promise)
* @param array $options Options for transport
*
* @return callable|array
*/
public function resultOrFuture($result, $options = [])
{
$response = null;
$async = isset($options['client']['future']) ? $options['client']['future'] : null;
if (is_null($async) || $async === false) {
do {
$result = $result->wait();
} while ($result instanceof FutureArrayInterface);
return $result;
} elseif ($async === true || $async === 'lazy') {
return $result;
}
}
/**
* @param $request
*
* @return bool
*/
public function shouldRetry($request)
{
if ($this->retryAttempts < $this->retries) {
$this->retryAttempts += 1;
return true;
}
return false;
}
/**
* Returns the last used connection so that it may be inspected. Mainly
* for debugging/testing purposes.
*
* @return Connection
*/
public function getLastConnection()
{
return $this->lastConnection;
}
}
|
| #9 | Elasticsearch\Transport->performRequest(HEAD, /sgr, Array(), null, Array([client] => Array([verbose] => 1))) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/BooleanRequestWrapper.php (38) <?php
namespace Elasticsearch\Namespaces;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Endpoints\AbstractEndpoint;
use Elasticsearch\Transport;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
/**
* Trait AbstractNamespace
*
* @category Elasticsearch
* @package Elasticsearch\Namespaces
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
trait BooleanRequestWrapper
{
/**
* Perform Request
*
* @param AbstractEndpoint $endpoint The Endpoint to perform this request against
*
* @throws Missing404Exception
* @throws RoutingMissingException
*/
public static function performRequest(AbstractEndpoint $endpoint, Transport $transport)
{
try {
$response = $transport->performRequest(
$endpoint->getMethod(),
$endpoint->getURI(),
$endpoint->getParams(),
$endpoint->getBody(),
$endpoint->getOptions()
);
$response = $transport->resultOrFuture($response, $endpoint->getOptions());
if (!($response instanceof FutureArrayInterface)) {
if ($response['status'] === 200) {
return true;
} else {
return false;
}
} else {
// async mode, can't easily resolve this...punt to user
return $response;
}
} catch (Missing404Exception $exception) {
return false;
} catch (RoutingMissingException $exception) {
return false;
}
}
}
|
| #10 | Elasticsearch\Namespaces\BooleanRequestWrapper::performRequest(Object(Elasticsearch\Endpoints\Indices\Exists), Object(Elasticsearch\Transport)) /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/IndicesNamespace.php (38) <?php
namespace Elasticsearch\Namespaces;
/**
* Class IndicesNamespace
*
* @category Elasticsearch
* @package Elasticsearch\Namespaces\IndicesNamespace
* @author Zachary Tong <zach@elastic.co>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class IndicesNamespace extends AbstractNamespace
{
/**
* $params['index'] = (list) A comma-separated list of indices to check (Required)
*
* @param $params array Associative array of parameters
*
* @return boolean
*/
public function exists($params)
{
$index = $this->extractArgument($params, 'index');
//manually make this verbose so we can check status code
$params['client']['verbose'] = true;
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Exists $endpoint */
$endpoint = $endpointBuilder('Indices\Exists');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return BooleanRequestWrapper::performRequest($endpoint, $this->transport);
}
/**
* $params['index'] = (list) A comma-separated list of indices to check (Required)
* ['feature'] = (list) A comma-separated list of features to return
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
* ['local'] = (bool) Return local information, do not retrieve the state from master node (default: false)
*
* @param $params array Associative array of parameters
*
* @return bool
*/
public function get($params)
{
$index = $this->extractArgument($params, 'index');
$feature = $this->extractArgument($params, 'feature');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Get');
$endpoint->setIndex($index)
->setFeature($feature)
->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['operation_threading'] = () TODO: ?
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function segments($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Segments $endpoint */
$endpoint = $endpointBuilder('Indices\Segments');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (string) The name of the template (Required)
* ['timeout'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function deleteTemplate($params)
{
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Template\Delete $endpoint */
$endpoint = $endpointBuilder('Indices\Template\Delete');
$endpoint->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of indices to delete; use `_all` or empty string to delete all indices
* ['timeout'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function delete($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Delete $endpoint */
$endpoint = $endpointBuilder('Indices\Delete');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['fields'] = (boolean) A comma-separated list of fields for `fielddata` metric (supports wildcards)
* ['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['indexing_types'] = (list) A comma-separated list of document types to include in the `indexing` statistics
* ['metric_family'] = (enum) Limit the information returned to a specific metric
* ['search_groups'] = (list) A comma-separated list of search groups to include in the `search` statistics
* ['all'] = (boolean) Return all available information
* ['clear'] = (boolean) Reset the default level of detail
* ['docs'] = (boolean) Return information about indexed and deleted documents
* ['fielddata'] = (boolean) Return information about field data
* ['filter_cache'] = (boolean) Return information about filter cache
* ['flush'] = (boolean) Return information about flush operations
* ['get'] = (boolean) Return information about get operations
* ['groups'] = (boolean) A comma-separated list of search groups for `search` statistics
* ['id_cache'] = (boolean) Return information about ID cache
* ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones
* ['indexing'] = (boolean) Return information about indexing operations
* ['merge'] = (boolean) Return information about merge operations
* ['refresh'] = (boolean) Return information about refresh operations
* ['search'] = (boolean) Return information about search operations; use the `groups` parameter to include information for specific search groups
* ['store'] = (boolean) Return information about the size of the index
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function stats($params = array())
{
$metric = $this->extractArgument($params, 'metric');
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Stats $endpoint */
$endpoint = $endpointBuilder('Indices\Stats');
$endpoint->setIndex($index)
->setMetric($metric);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['body'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function putSettings($params = array())
{
$index = $this->extractArgument($params, 'index');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Settings\Put $endpoint */
$endpoint = $endpointBuilder('Indices\Settings\Put');
$endpoint->setIndex($index)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function snapshotIndex($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Gateway\Snapshot $endpoint */
$endpoint = $endpointBuilder('Indices\Gateway\Snapshot');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the source index to shrink
* ['target'] = (string) The name of the target index to shrink into
* ['timeout'] = (time) Explicit operation timeout
* ['master_timeout'] = (time) Specify timeout for connection to master
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function shrink($params = array())
{
$index = $this->extractArgument($params, 'index');
$target = $this->extractArgument($params, 'target');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Shrink $endpoint */
$endpoint = $endpointBuilder('Indices\Shrink');
$endpoint->setIndex($index)
->setTarget($target);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['type'] = (list) A comma-separated list of document types
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getMapping($params = array())
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Mapping\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Mapping\Get');
$endpoint->setIndex($index)
->setType($type);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['type'] = (list) A comma-separated list of document types
* ['field'] = (list) A comma-separated list of document fields
* ['include_defaults'] = (bool) specifies default mapping values should be returned
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getFieldMapping($params = array())
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
$fields = $this->extractArgument($params, 'fields');
if (!isset($fields)) {
$fields = $this->extractArgument($params, 'field');
}
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Mapping\GetField $endpoint */
$endpoint = $endpointBuilder('Indices\Mapping\GetField');
$endpoint->setIndex($index)
->setType($type)
->setFields($fields);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['force'] = (boolean) TODO: ?
* ['full'] = (boolean) TODO: ?
* ['refresh'] = (boolean) Refresh the index after performing the operation
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function flush($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Flush $endpoint */
$endpoint = $endpointBuilder('Indices\Flush');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['force'] = (boolean) TODO: ?
* ['full'] = (boolean) TODO: ?
* ['refresh'] = (boolean) Refresh the index after performing the operation
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function flushSynced($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Flush $endpoint */
$endpoint = $endpointBuilder('Indices\Flush');
$endpoint->setIndex($index);
$endpoint->setParams($params);
$endpoint->setSynced(true);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['operation_threading'] = () TODO: ?
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function refresh($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Refresh $endpoint */
$endpoint = $endpointBuilder('Indices\Refresh');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['detailed'] = (bool) Whether to display detailed information about shard recovery
* ['active_only'] = (bool) Display only those recoveries that are currently on-going
* ['human'] = (bool) Whether to return time and byte values in human-readable format.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function recovery($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Flush $endpoint */
$endpoint = $endpointBuilder('Indices\Recovery');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` to check the types across all indices (Required)
* ['type'] = (list) A comma-separated list of document types to check (Required)
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return boolean
*/
public function existsType($params)
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
//manually make this verbose so we can check status code
$params['client']['verbose'] = true;
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Type\Exists $endpoint */
$endpoint = $endpointBuilder('Indices\Type\Exists');
$endpoint->setIndex($index)
->setType($type);
$endpoint->setParams($params);
return BooleanRequestWrapper::performRequest($endpoint, $this->transport);
}
/**
* $params['index'] = (string) The name of the index with an alias
* ['name'] = (string) The name of the alias to be created or updated
* ['timeout'] = (time) Explicit timestamp for the document
* ['body'] = (time) Explicit timestamp for the document
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function putAlias($params = array())
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Alias\Put $endpoint */
$endpoint = $endpointBuilder('Indices\Alias\Put');
$endpoint->setIndex($index)
->setName($name)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (string) The name of the template (Required)
* ['order'] = (number) The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers)
* ['timeout'] = (time) Explicit operation timeout
* ['body'] = (time) Explicit operation timeout
* ['create'] = (bool) Whether the index template should only be added if new or can also replace an existing one
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function putTemplate($params)
{
$name = $this->extractArgument($params, 'name');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Template\Put $endpoint */
$endpoint = $endpointBuilder('Indices\Template\Put');
$endpoint->setName($name)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
* ['type'] = (list) A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
* ['explain'] = (boolean) Return detailed information about the error
* ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones
* ['operation_threading'] = () TODO: ?
* ['source'] = (string) The URL-encoded query definition (instead of using the request body)
* ['body'] = (string) The URL-encoded query definition (instead of using the request body)
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function validateQuery($params = array())
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Validate\Query $endpoint */
$endpoint = $endpointBuilder('Indices\Validate\Query');
$endpoint->setIndex($index)
->setType($type)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (list) A comma-separated list of alias names to return (Required)
* ['index'] = (list) A comma-separated list of index names to filter aliases
* ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones
* ['name'] = (list) A comma-separated list of alias names to return
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getAlias($params)
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Alias\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Alias\Get');
$endpoint->setIndex($index)
->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` to perform the operation on all indices (Required)
* ['type'] = (string) The name of the document type
* ['ignore_conflicts'] = (boolean) Specify whether to ignore conflicts while updating the mapping (default: false)
* ['timeout'] = (time) Explicit operation timeout
* ['body'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function putMapping($params)
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Mapping\Put $endpoint */
$endpoint = $endpointBuilder('Indices\Mapping\Put');
$endpoint->setIndex($index)
->setType($type)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` for all indices (Required)
* ['type'] = (string) The name of the document type to delete (Required)
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function deleteMapping($params)
{
$index = $this->extractArgument($params, 'index');
$type = $this->extractArgument($params, 'type');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Mapping\Delete $endpoint */
$endpoint = $endpointBuilder('Indices\Mapping\Delete');
$endpoint->setIndex($index)
->setType($type);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (string) The name of the template (Required)
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getTemplate($params)
{
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Template\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Template\Get');
$endpoint->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (string) The name of the template (Required)
*
* @param $params array Associative array of parameters
*
* @return boolean
*/
public function existsTemplate($params)
{
$name = $this->extractArgument($params, 'name');
//manually make this verbose so we can check status code
$params['client']['verbose'] = true;
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Template\Exists $endpoint */
$endpoint = $endpointBuilder('Indices\Template\Exists');
$endpoint->setName($name);
$endpoint->setParams($params);
return BooleanRequestWrapper::performRequest($endpoint, $this->transport);
}
/**
* $params['index'] = (string) The name of the index (Required)
* ['timeout'] = (time) Explicit operation timeout
* ['body'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function create($params)
{
$index = $this->extractArgument($params, 'index');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Create $endpoint */
$endpoint = $endpointBuilder('Indices\Create');
$endpoint->setIndex($index)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['flush'] = (boolean) Specify whether the index should be flushed after performing the operation (default: true)
* ['max_num_segments'] = (number) The number of segments the index should be merged into (default: dynamic)
* ['only_expunge_deletes'] = (boolean) Specify whether the operation should only expunge deleted documents
* ['operation_threading'] = () TODO: ?
* ['refresh'] = (boolean) Specify whether the index should be refreshed after performing the operation (default: true)
* ['wait_for_merge'] = (boolean) Specify whether the request should block until the merge process is finished (default: true)
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function forceMerge($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\ForceMerge $endpoint */
$endpoint = $endpointBuilder('Indices\ForceMerge');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the index with an alias (Required)
* ['name'] = (string) The name of the alias to be deleted (Required)
* ['timeout'] = (time) Explicit timestamp for the document
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function deleteAlias($params)
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Alias\Delete $endpoint */
$endpoint = $endpointBuilder('Indices\Alias\Delete');
$endpoint->setIndex($index)
->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the index (Required)
* ['timeout'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function open($params)
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Open $endpoint */
$endpoint = $endpointBuilder('Indices\Open');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the index to scope the operation
* ['analyzer'] = (string) The name of the analyzer to use
* ['field'] = (string) Use the analyzer configured for this field (instead of passing the analyzer name)
* ['filter'] = (list) A comma-separated list of filters to use for the analysis
* ['prefer_local'] = (boolean) With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
* ['text'] = (string) The text on which the analysis should be performed (when request body is not used)
* ['tokenizer'] = (string) The name of the tokenizer to use for the analysis
* ['format'] = (enum) Format of the output
* ['body'] = (enum) Format of the output
* ['char_filter'] = (list) A comma-separated list of character filters to use for the analysis
* ['explain'] = (bool) With `true`, outputs more advanced details. (default: false)
* ['attributes'] = (list) A comma-separated list of token attributes to output, this parameter works only with `explain=true`
* ['format'] = (enum) Format of the output (["detailed", "text"])
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function analyze($params = array())
{
$index = $this->extractArgument($params, 'index');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Analyze $endpoint */
$endpoint = $endpointBuilder('Indices\Analyze');
$endpoint->setIndex($index)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index name to limit the operation
* ['field_data'] = (boolean) Clear field data
* ['fielddata'] = (boolean) Clear field data
* ['fields'] = (list) A comma-separated list of fields to clear when using the `field_data` parameter (default: all)
* ['filter'] = (boolean) Clear filter caches
* ['filter_cache'] = (boolean) Clear filter caches
* ['filter_keys'] = (boolean) A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all)
* ['id'] = (boolean) Clear ID caches for parent/child
* ['id_cache'] = (boolean) Clear ID caches for parent/child
* ['recycler'] = (boolean) Clear the recycler cache
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function clearCache($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Cache\Clear $endpoint */
$endpoint = $endpointBuilder('Indices\Cache\Clear');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names to filter aliases
* ['timeout'] = (time) Explicit timestamp for the document
* ['body'] = (time) Explicit timestamp for the document
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function updateAliases($params = array())
{
$index = $this->extractArgument($params, 'index');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Aliases\Update $endpoint */
$endpoint = $endpointBuilder('Indices\Aliases\Update');
$endpoint->setIndex($index)
->setBody($body);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['local'] = (bool) Return local information, do not retrieve the state from master node (default: false)
* ['timeout'] = (time) Explicit timestamp for the document
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getAliases($params = array())
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Aliases\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Aliases\Get');
$endpoint->setIndex($index)
->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['name'] = (list) A comma-separated list of alias names to return (Required)
* ['index'] = (list) A comma-separated list of index names to filter aliases
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return boolean
*/
public function existsAlias($params)
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
//manually make this verbose so we can check status code
$params['client']['verbose'] = true;
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Alias\Exists $endpoint */
$endpoint = $endpointBuilder('Indices\Alias\Exists');
$endpoint->setIndex($index)
->setName($name);
$endpoint->setParams($params);
return BooleanRequestWrapper::performRequest($endpoint, $this->transport);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones
* ['operation_threading'] = () TODO: ?
* ['recovery'] = (boolean) Return information about shard recovery
* ['snapshot'] = (boolean) TODO: ?
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function status($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Status $endpoint */
$endpoint = $endpointBuilder('Indices\Status');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getSettings($params = array())
{
$index = $this->extractArgument($params, 'index');
$name = $this->extractArgument($params, 'name');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Settings\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Settings\Get');
$endpoint->setIndex($index)
->setName($name);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the index (Required)
* ['timeout'] = (time) Explicit operation timeout
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function close($params)
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Close $endpoint */
$endpoint = $endpointBuilder('Indices\Close');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) The name of the index
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function seal($params)
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Seal $endpoint */
$endpoint = $endpointBuilder('Indices\Seal');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['wait_for_completion']= (boolean) Specify whether the request should block until the all segments are upgraded (default: false)
* ['only_ancient_segments'] = (boolean) If true, only ancient (an older Lucene major release) segments will be upgraded
* ['refresh'] = (boolean) Refresh the index after performing the operation
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function upgrade($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Upgrade\Post $endpoint */
$endpoint = $endpointBuilder('Indices\Upgrade\Post');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (list) A comma-separated list of index names; use `_all` or empty string for all indices
* ['wait_for_completion']= (boolean) Specify whether the request should block until the all segments are upgraded (default: false)
* ['only_ancient_segments'] = (boolean) If true, only ancient (an older Lucene major release) segments will be upgraded
* ['refresh'] = (boolean) Refresh the index after performing the operation
* ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function getUpgrade($params = array())
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Upgrade\Get $endpoint */
$endpoint = $endpointBuilder('Indices\Upgrade\Get');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['index'] = (string) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
* ['status'] = (list) A comma-separated list of statuses used to filter on shards to get store information for
* ['ignore_unavailable'] = (boolean) Whether specified concrete indices should be ignored when unavailable (missing or closed)
* ['allow_no_indices'] = (boolean) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
* ['expand_wildcards'] = (boolean) Whether to expand wildcard expression to concrete indices that are open, closed or both.
* ['operation_threading']
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function shardStores($params)
{
$index = $this->extractArgument($params, 'index');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\ShardStores $endpoint */
$endpoint = $endpointBuilder('Indices\ShardStores');
$endpoint->setIndex($index);
$endpoint->setParams($params);
return $this->performRequest($endpoint);
}
/**
* $params['newIndex'] = (string) The name of the rollover index
* ['alias'] = (string) The name of the alias to rollover
* ['timeout'] = (time) Explicit operation timeout
* ['master_timeout'] = (time) Specify timeout for connection to master
*
* @param $params array Associative array of parameters
*
* @return array
*/
public function rollover($params)
{
$newIndex = $this->extractArgument($params, 'newIndex');
$alias = $this->extractArgument($params, 'alias');
$body = $this->extractArgument($params, 'body');
/** @var callback $endpointBuilder */
$endpointBuilder = $this->endpoints;
/** @var \Elasticsearch\Endpoints\Indices\Rollover $endpoint */
$endpoint = $endpointBuilder('Indices\Rollover');
$endpoint->setNewIndex($newIndex)
->setAlias($alias)
->setParams($params)
->setBody($body);
return $this->performRequest($endpoint);
}
}
|
| #11 | Elasticsearch\Namespaces\IndicesNamespace->exists(Array([client] => Array([verbose] => 1))) /srv/www/subdomain-sangiare/xe/app/models/Adapter/Elastic.php (47) <?php
/**
* Description of ElasticAbstract
*
* @author hoapm <kuro37@hotmail.com>
*
*/
namespace Model\Adapter;
use Elasticsearch\ClientBuilder;
use Core\Logger;
use Application\Mvc\Helper\Text;
class Elastic
{
/**
* Elasticsearch\Client
* @var \Elasticsearch\Client
*/
protected static $_instance = null;
protected static $_client = null;
protected static $_host = '';
protected static $_port = '';
protected static $_index = '';
public function __construct($instance = 'elastic')
{
$config = \Core\App::getConfig();
self::$_host = $config->elastic->ELASTIC_HOST;
self::$_port = $config->elastic->ELASTIC_PORT;
self::$_index = $config->elastic->ELASTIC_INDEX;
$indexParams['index'] = $config->elastic->ELASTIC_INDEX;
//$params['hosts'] = array(self::$_host . ':' . self::$_port);
$hosts = [
[
'host' => $config->elastic->ELASTIC_HOST,
'port' => $config->elastic->ELASTIC_PORT,
'user' => $config->elastic->ELASTIC_USERNAME,
'pass' => $config->elastic->ELASTIC_PASSWORD
]
];
self::$_client = ClientBuilder::create()->setHosts($hosts)
->setConnectionPool('\Elasticsearch\ConnectionPool\StaticNoPingConnectionPool', [])
->build();
$exist = self::$_client->indices()->exists($indexParams);
if ($exist == false) {
$this->createIndex($config->elastic->ELASTIC_INDEX);
}
}
/**
*
* @param string $name
* @return object
*/
public static function getInstance($name = 'elastic')
{
if (self::$_instance == null) {
self::$_instance = new self($name);
}
return self::$_instance;
}
/**
* Search
*
* @param string $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function search($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array(), $facets = array(), $minimum_should_match = '0%', $fields = array(), $aggs = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$_source = [];
if(count($group) > 0) $indexParams['body']['size'] = 0;
else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
if($key == '_source') {
$_source = $value['value']; continue;
}
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if($_source) $indexParams['_source'] = $_source;
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
if ($key == '_geo_distance') {
$indexParams['body']['sort'][$key] = $value;
} else {
$indexParams['body']['sort'][$key] = strtolower($value);
}
}
foreach ($group as $value) {
if($value == "max_price") {
$indexParams['body']['aggs']['group_by_' . $value]['max']['field'] = "price";
} elseif(strpos($value,"range_price") > -1 ) {
$value_ = explode("__", $value);
$range = explode("-",$value_[1]);
$ranges = array(
array("from"=>$range[0],"to"=>$range[1]),
array("from"=>$range[1],"to"=>$range[2]),
array("from"=>$range[2],"to"=>$range[3]),
array("from"=>$range[3],"to"=>$range[4]),
array("from"=>$range[4],"to"=>$range[5])
);
$indexParams['body']['aggs']['group_by_' . $value]['range']['field'] = "price";
$indexParams['body']['aggs']['group_by_' . $value]['range']['ranges'] = $ranges;
} else {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = 200;
}
}
foreach ($aggs as $key => $value) {
$indexParams['body']['aggs'][$key] = $value;
}
if (count($facets) > 0) {
foreach ($facets as $item) {
$indexParams['body']['facets'][$item]['terms']['field'] = $item;
$indexParams['body']['facets'][$item]['terms']['size'] = 500000;
}
}
if (count($fields) > 0) {
$indexParams['body']['_source'] = $fields;
}
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
if (count($facets) > 0) {
$list['facets'] = $result['facets'];
}
if (count($aggs)) {
$list['aggregations'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
public function searchProduct($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $keyword)
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
$keywordNUtf8 = Text::removeTextUtf8($keyword);
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('meta_title' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('alt_name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('brand.name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('category_name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('meta_title_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('alt_name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('brand.name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('category_name_ntf8' => $keywordNUtf8));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Search Custom Query
*
* @param $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function customSearch($type, $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array())
{
if (!empty($_GET['debug']) && $_GET['debug'] == 'Y') {
return self::customSearchV2($type, $query, $sort, $offset, $limit, $group);
}
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['body']['query'] = $query;
$isSKUorBarcode = false;
if (!empty($query["bool"]["should"])) {
foreach ($query["bool"]["should"] as $key => $value) {
if(isset($value["term"]["sku"]) && is_numeric($value["term"]["sku"])) $isSKUorBarcode = true;
}
}
if(count($group) > 0) {
$indexParams['body']['size'] = 0;
if(isset($query['bool']['should'])) {
if(!$isSKUorBarcode) $indexParams['body']['min_score'] = 7;
}
} else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
if(isset($query['bool']['should'])) {
if(!$isSKUorBarcode) $indexParams['body']['min_score'] = 7;
}
}
$newSort = array();
foreach ($sort as $key => $value) {
$newSort[$key] = array("order" => strtolower($value));
}
if(empty($newSort)) $indexParams['body']['sort'] = ["_score"];
else $indexParams['body']['sort'] = [ $newSort, "_score" ];
// if(empty($sort)) {
// $newSort = array();
// $newSort[]["_score"] = array("order" => 'DESC');
// $indexParams['body']['sort'] = $newSort;
// }
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = $limit;
}
// var_dump(\GuzzleHttp\json_encode($indexParams));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
public function skuByKeyword($query, $offset = 0, $limit = 0)
{
$list = array();
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = 'product';
$indexParams['_source'] = ['id'];
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
$indexParams['body']['query'] = $query;
$result = self::$_client->search($indexParams);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
foreach ($result['hits']['hits'] as $value) {
$list[] = $value['_source']["id"];
}
}
return $list;
}
/**
* get count
*
* @param $type
* @param array $query
*
* @return int
*/
public function getCount($type, $query = array(), $minimum_should_match = '0%')
{
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = array('from' => $value['value'][0], 'to' => $value['value'][1]);
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value'], 'minimum_should_match' => $minimum_should_match);
///var_dump($indexParams);die;
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
$result = self::$_client->count($indexParams);
if (isset($result['count'])) {
return $result['count'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return 0;
}
public function getComparison($comparison)
{
$comparison = strtolower($comparison);
$list['='] = 'match';
$list['in'] = 'terms';
$list['like'] = 'wildcard';
$list['between'] = 'range';
$list['query'] = 'query_string';
$list['prefix'] = 'prefix';
$list['>'] = 'range';
$list['>='] = 'range';
$list['<'] = 'range';
$list['<='] = 'range';
$list['exists'] = 'exists';
return isset($list[$comparison]) ? $list[$comparison] : $list['='];
}
public function getCondition($condition)
{
$condition = strtolower($condition);
$list['and'] = 'must';
$list['or'] = 'should';
$list['not'] = 'must_not';
return isset($list[$condition]) ? $list[$condition] : $list['and'];
}
public static function insert($type, $data)
{
try {
$data['index'] = self::$_index;
$data['type'] = $type;
$result = self::$_client->index($data);
return $result;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
public static function update($type, $data)
{
try {
$data['index'] = self::$_index;
$data['type'] = $type;
$result = self::$_client->update($data);
return $result;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
//HDK
/**
* Create index
*
* @param string $index
*/
public function createIndex($index = 'sgr',$update = false)
{
try {
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['body']['settings']['number_of_shards'] = 2;
$indexParams['body']['settings']['number_of_replicas'] = 0;
$productMapping = array(
'properties' => array(
// 'name' => array(
// 'type' => 'text',
// 'search_analyzer' => 'str_search_analyzer',
// 'analyzer' => 'str_index_analyzer',
// ),
'alt_name' => array(
'type' => 'text',
'search_analyzer' => 'str_search_analyzer',
'analyzer' => 'str_index_analyzer',
),
'sku' => array(
'type' => 'text',
'analyzer' => 'standard',
)
)
);
$productSettingsAnalysis = array(
'analyzer' => array(
'str_search_analyzer' => array(
'tokenizer' => 'keyword',
'filter' => array('lowercase')
),
'str_index_analyzer' => array(
'tokenizer' => 'keyword',
'filter' => array('lowercase','substring')
)
),
'filter' => array(
'substring' => array(
'type' => 'nGram',
'min_gram' => 3,
'max_gram' => 20
)
)
);
$indexParams['body']['settings']['analysis'] = $productSettingsAnalysis;
if($update == false) {
self::$_client->indices()->create($indexParams);
} else {
$updateParams['index'] = $index;
$updateParams['body'] = $indexParams['body'];
unset($updateParams['body']['settings']['number_of_shards']);
unset($updateParams['body']['settings']['number_of_replicas']);
self::$_client->indices()->putSettings($updateParams);
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}
}
/**
* Set index
*
* @param string $index
* @param string $type
* @param integer $id
* @param array $body
*/
public function setIndex($index, $type, $id, $body = array())
{
if(empty($index)) {
$index = 'sgr';
}
try {
// Check if index exist
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['id'] = $id;
$indexParams['body'] = $body;
self::$_client->index($indexParams);
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
}
public function setBulkIndex($params)
{
try {
$responses = self::$_client->bulk($params);
unset($responses);
return true;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
public function perform()
{
@list($index, $type, $id, $body) = $this->args;
$this->setIndex($index, $type, $id, $body);
}
/**
* Get index
*
* @param string $type
* @param null $id
* @param array $query
* @param array $sort
*
* @return array|mixed|null
*/
public function get($type, $id = null, $query = array(), $sort = array())
{
if ($id == null && (!is_array($query) || count($query) == 0))
return null;
try {
$indexParams = array();
$indexParams['index'] = self::$_index;
$indexParams['type'] = $type;
if ($id != null) {
$indexParams['id'] = $id;
$result = self::$_client->get($indexParams);
} else {
foreach ($query as $key => $value) {
$indexParams['body']['query']['match'][$key] = $value;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
$result = self::$_client->search($indexParams);
}
if ($result['found'])
return $result['_source'];
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
}
return null;
}
/**
* Get index
*
* @param string $type
* @param array $ids
*
* @return array|mixed|null
*/
public function getMulti($type, $ids = array()) {
$list = array();
if ((!is_array($ids) || count($ids) == 0))
return $list;
try {
$index = self::$_index;
$listId['ids'] = $ids;
$params = array();
$params['index'] = $index;
$params['type'] = $type;
$params['body'] = json_encode($listId);
$result = self::$_client->mget($params);
if (is_array($result) && isset($result['docs']) && is_array($result['docs'])) {
foreach ($result['docs'] as $value) {
if ($value['found']) {
$list[$value['_id']] = $value['_source'];
}
}
}
return $list;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Delete by id
*
* @param $type
* @param $id
*
* @return bool|null
*/
public function delete($type, $id)
{
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['id'] = $id;
$startTime = gettimeofday(true);
$result = self::$_client->delete($indexParams);
$endTime = gettimeofday(true);
//\Core\Profiler::getElasticProfiler(self::getInstance())->pushDeleteProfiler($startTime, $endTime, $index, $type, $id, $result);
if (isset($result['found']) && $result['found']) {
return true;
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return false;
}
/**
* Delete query
*
* @param $type
* @param array $params
*
* @return bool|null
*/
public function deleteQuery($type, $params = array()) {
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
foreach ($params as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = array('from' => $value['value'][0], 'to' => $value['value'][1]);
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
$startTime = gettimeofday(true);
$result = self::$_client->deleteByQuery($indexParams);
$endTime = gettimeofday(true);
//Profiler::getElasticProfiler(self::getInstance())->pushDeleteQueryProfiler($startTime, $endTime, $index, $type, $query, $result);
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return false;
}
/**
* Search Custom Query
*
* @param $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function customSearchV2($type, $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['body']['query'] = $query;
if(count($group) > 0) {
$indexParams['body']['size'] = 0;
} else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
$newSort = array();
$newSort[]["_score"] = array("order"=>'DESC');
$indexParams['body']['sort'] = $newSort;
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
}
$result = self::$_client->search($indexParams);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Search
*
* @param string $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function searchGroup($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = "", $facets = array(), $minimum_should_match = '0%', $fields = array(), $aggs = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
if(count($group) > 0) $indexParams['body']['size'] = 0;
else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
if (!empty($group)) {
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = $limit;
}
}
foreach ($aggs as $key => $value) {
$indexParams['body']['aggs'][$key] = $value;
}
if (count($facets) > 0) {
foreach ($facets as $item) {
$indexParams['body']['facets'][$item]['terms']['field'] = $item;
$indexParams['body']['facets'][$item]['terms']['size'] = 500000;
}
}
if (count($fields) > 0) {
$indexParams['body']['_source'] = $fields;
}
// echo '<pre>';
// echo serialize($indexParams['body']);die;
// var_dump(\GuzzleHttp\json_encode($indexParams));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
if (count($facets) > 0) {
$list['facets'] = $result['facets'];
}
if (count($aggs)) {
$list['aggregations'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
}
|
| #12 | Model\Adapter\Elastic->__construct(elastic) /srv/www/subdomain-sangiare/xe/app/models/Adapter/Elastic.php (61) <?php
/**
* Description of ElasticAbstract
*
* @author hoapm <kuro37@hotmail.com>
*
*/
namespace Model\Adapter;
use Elasticsearch\ClientBuilder;
use Core\Logger;
use Application\Mvc\Helper\Text;
class Elastic
{
/**
* Elasticsearch\Client
* @var \Elasticsearch\Client
*/
protected static $_instance = null;
protected static $_client = null;
protected static $_host = '';
protected static $_port = '';
protected static $_index = '';
public function __construct($instance = 'elastic')
{
$config = \Core\App::getConfig();
self::$_host = $config->elastic->ELASTIC_HOST;
self::$_port = $config->elastic->ELASTIC_PORT;
self::$_index = $config->elastic->ELASTIC_INDEX;
$indexParams['index'] = $config->elastic->ELASTIC_INDEX;
//$params['hosts'] = array(self::$_host . ':' . self::$_port);
$hosts = [
[
'host' => $config->elastic->ELASTIC_HOST,
'port' => $config->elastic->ELASTIC_PORT,
'user' => $config->elastic->ELASTIC_USERNAME,
'pass' => $config->elastic->ELASTIC_PASSWORD
]
];
self::$_client = ClientBuilder::create()->setHosts($hosts)
->setConnectionPool('\Elasticsearch\ConnectionPool\StaticNoPingConnectionPool', [])
->build();
$exist = self::$_client->indices()->exists($indexParams);
if ($exist == false) {
$this->createIndex($config->elastic->ELASTIC_INDEX);
}
}
/**
*
* @param string $name
* @return object
*/
public static function getInstance($name = 'elastic')
{
if (self::$_instance == null) {
self::$_instance = new self($name);
}
return self::$_instance;
}
/**
* Search
*
* @param string $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function search($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array(), $facets = array(), $minimum_should_match = '0%', $fields = array(), $aggs = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$_source = [];
if(count($group) > 0) $indexParams['body']['size'] = 0;
else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
if($key == '_source') {
$_source = $value['value']; continue;
}
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if($_source) $indexParams['_source'] = $_source;
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
if ($key == '_geo_distance') {
$indexParams['body']['sort'][$key] = $value;
} else {
$indexParams['body']['sort'][$key] = strtolower($value);
}
}
foreach ($group as $value) {
if($value == "max_price") {
$indexParams['body']['aggs']['group_by_' . $value]['max']['field'] = "price";
} elseif(strpos($value,"range_price") > -1 ) {
$value_ = explode("__", $value);
$range = explode("-",$value_[1]);
$ranges = array(
array("from"=>$range[0],"to"=>$range[1]),
array("from"=>$range[1],"to"=>$range[2]),
array("from"=>$range[2],"to"=>$range[3]),
array("from"=>$range[3],"to"=>$range[4]),
array("from"=>$range[4],"to"=>$range[5])
);
$indexParams['body']['aggs']['group_by_' . $value]['range']['field'] = "price";
$indexParams['body']['aggs']['group_by_' . $value]['range']['ranges'] = $ranges;
} else {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = 200;
}
}
foreach ($aggs as $key => $value) {
$indexParams['body']['aggs'][$key] = $value;
}
if (count($facets) > 0) {
foreach ($facets as $item) {
$indexParams['body']['facets'][$item]['terms']['field'] = $item;
$indexParams['body']['facets'][$item]['terms']['size'] = 500000;
}
}
if (count($fields) > 0) {
$indexParams['body']['_source'] = $fields;
}
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
if (count($facets) > 0) {
$list['facets'] = $result['facets'];
}
if (count($aggs)) {
$list['aggregations'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
public function searchProduct($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $keyword)
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
$keywordNUtf8 = Text::removeTextUtf8($keyword);
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('meta_title' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('alt_name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('brand.name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('category_name' => $keyword));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('meta_title_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('alt_name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('brand.name_ntf8' => $keywordNUtf8));
$indexParams['body']['query']['bool']['should'][] = array('match_phrase_prefix' => array('category_name_ntf8' => $keywordNUtf8));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Search Custom Query
*
* @param $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function customSearch($type, $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array())
{
if (!empty($_GET['debug']) && $_GET['debug'] == 'Y') {
return self::customSearchV2($type, $query, $sort, $offset, $limit, $group);
}
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['body']['query'] = $query;
$isSKUorBarcode = false;
if (!empty($query["bool"]["should"])) {
foreach ($query["bool"]["should"] as $key => $value) {
if(isset($value["term"]["sku"]) && is_numeric($value["term"]["sku"])) $isSKUorBarcode = true;
}
}
if(count($group) > 0) {
$indexParams['body']['size'] = 0;
if(isset($query['bool']['should'])) {
if(!$isSKUorBarcode) $indexParams['body']['min_score'] = 7;
}
} else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
if(isset($query['bool']['should'])) {
if(!$isSKUorBarcode) $indexParams['body']['min_score'] = 7;
}
}
$newSort = array();
foreach ($sort as $key => $value) {
$newSort[$key] = array("order" => strtolower($value));
}
if(empty($newSort)) $indexParams['body']['sort'] = ["_score"];
else $indexParams['body']['sort'] = [ $newSort, "_score" ];
// if(empty($sort)) {
// $newSort = array();
// $newSort[]["_score"] = array("order" => 'DESC');
// $indexParams['body']['sort'] = $newSort;
// }
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = $limit;
}
// var_dump(\GuzzleHttp\json_encode($indexParams));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
public function skuByKeyword($query, $offset = 0, $limit = 0)
{
$list = array();
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = 'product';
$indexParams['_source'] = ['id'];
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
$indexParams['body']['query'] = $query;
$result = self::$_client->search($indexParams);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
foreach ($result['hits']['hits'] as $value) {
$list[] = $value['_source']["id"];
}
}
return $list;
}
/**
* get count
*
* @param $type
* @param array $query
*
* @return int
*/
public function getCount($type, $query = array(), $minimum_should_match = '0%')
{
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = array('from' => $value['value'][0], 'to' => $value['value'][1]);
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value'], 'minimum_should_match' => $minimum_should_match);
///var_dump($indexParams);die;
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
$result = self::$_client->count($indexParams);
if (isset($result['count'])) {
return $result['count'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return 0;
}
public function getComparison($comparison)
{
$comparison = strtolower($comparison);
$list['='] = 'match';
$list['in'] = 'terms';
$list['like'] = 'wildcard';
$list['between'] = 'range';
$list['query'] = 'query_string';
$list['prefix'] = 'prefix';
$list['>'] = 'range';
$list['>='] = 'range';
$list['<'] = 'range';
$list['<='] = 'range';
$list['exists'] = 'exists';
return isset($list[$comparison]) ? $list[$comparison] : $list['='];
}
public function getCondition($condition)
{
$condition = strtolower($condition);
$list['and'] = 'must';
$list['or'] = 'should';
$list['not'] = 'must_not';
return isset($list[$condition]) ? $list[$condition] : $list['and'];
}
public static function insert($type, $data)
{
try {
$data['index'] = self::$_index;
$data['type'] = $type;
$result = self::$_client->index($data);
return $result;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
public static function update($type, $data)
{
try {
$data['index'] = self::$_index;
$data['type'] = $type;
$result = self::$_client->update($data);
return $result;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
//HDK
/**
* Create index
*
* @param string $index
*/
public function createIndex($index = 'sgr',$update = false)
{
try {
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['body']['settings']['number_of_shards'] = 2;
$indexParams['body']['settings']['number_of_replicas'] = 0;
$productMapping = array(
'properties' => array(
// 'name' => array(
// 'type' => 'text',
// 'search_analyzer' => 'str_search_analyzer',
// 'analyzer' => 'str_index_analyzer',
// ),
'alt_name' => array(
'type' => 'text',
'search_analyzer' => 'str_search_analyzer',
'analyzer' => 'str_index_analyzer',
),
'sku' => array(
'type' => 'text',
'analyzer' => 'standard',
)
)
);
$productSettingsAnalysis = array(
'analyzer' => array(
'str_search_analyzer' => array(
'tokenizer' => 'keyword',
'filter' => array('lowercase')
),
'str_index_analyzer' => array(
'tokenizer' => 'keyword',
'filter' => array('lowercase','substring')
)
),
'filter' => array(
'substring' => array(
'type' => 'nGram',
'min_gram' => 3,
'max_gram' => 20
)
)
);
$indexParams['body']['settings']['analysis'] = $productSettingsAnalysis;
if($update == false) {
self::$_client->indices()->create($indexParams);
} else {
$updateParams['index'] = $index;
$updateParams['body'] = $indexParams['body'];
unset($updateParams['body']['settings']['number_of_shards']);
unset($updateParams['body']['settings']['number_of_replicas']);
self::$_client->indices()->putSettings($updateParams);
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}
}
/**
* Set index
*
* @param string $index
* @param string $type
* @param integer $id
* @param array $body
*/
public function setIndex($index, $type, $id, $body = array())
{
if(empty($index)) {
$index = 'sgr';
}
try {
// Check if index exist
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['id'] = $id;
$indexParams['body'] = $body;
self::$_client->index($indexParams);
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
}
public function setBulkIndex($params)
{
try {
$responses = self::$_client->bulk($params);
unset($responses);
return true;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
}catch(\Elasticsearch\Common\Exceptions\UnexpectedValueException $e){
Logger::logElasticSearch($e);
}
return false;
}
public function perform()
{
@list($index, $type, $id, $body) = $this->args;
$this->setIndex($index, $type, $id, $body);
}
/**
* Get index
*
* @param string $type
* @param null $id
* @param array $query
* @param array $sort
*
* @return array|mixed|null
*/
public function get($type, $id = null, $query = array(), $sort = array())
{
if ($id == null && (!is_array($query) || count($query) == 0))
return null;
try {
$indexParams = array();
$indexParams['index'] = self::$_index;
$indexParams['type'] = $type;
if ($id != null) {
$indexParams['id'] = $id;
$result = self::$_client->get($indexParams);
} else {
foreach ($query as $key => $value) {
$indexParams['body']['query']['match'][$key] = $value;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
$result = self::$_client->search($indexParams);
}
if ($result['found'])
return $result['_source'];
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
}
return null;
}
/**
* Get index
*
* @param string $type
* @param array $ids
*
* @return array|mixed|null
*/
public function getMulti($type, $ids = array()) {
$list = array();
if ((!is_array($ids) || count($ids) == 0))
return $list;
try {
$index = self::$_index;
$listId['ids'] = $ids;
$params = array();
$params['index'] = $index;
$params['type'] = $type;
$params['body'] = json_encode($listId);
$result = self::$_client->mget($params);
if (is_array($result) && isset($result['docs']) && is_array($result['docs'])) {
foreach ($result['docs'] as $value) {
if ($value['found']) {
$list[$value['_id']] = $value['_source'];
}
}
}
return $list;
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Delete by id
*
* @param $type
* @param $id
*
* @return bool|null
*/
public function delete($type, $id)
{
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['id'] = $id;
$startTime = gettimeofday(true);
$result = self::$_client->delete($indexParams);
$endTime = gettimeofday(true);
//\Core\Profiler::getElasticProfiler(self::getInstance())->pushDeleteProfiler($startTime, $endTime, $index, $type, $id, $result);
if (isset($result['found']) && $result['found']) {
return true;
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return false;
}
/**
* Delete query
*
* @param $type
* @param array $params
*
* @return bool|null
*/
public function deleteQuery($type, $params = array()) {
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
foreach ($params as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = array('from' => $value['value'][0], 'to' => $value['value'][1]);
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
$startTime = gettimeofday(true);
$result = self::$_client->deleteByQuery($indexParams);
$endTime = gettimeofday(true);
//Profiler::getElasticProfiler(self::getInstance())->pushDeleteQueryProfiler($startTime, $endTime, $index, $type, $query, $result);
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return false;
}
/**
* Search Custom Query
*
* @param $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function customSearchV2($type, $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
$indexParams['body']['query'] = $query;
if(count($group) > 0) {
$indexParams['body']['size'] = 0;
} else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
$newSort = array();
$newSort[]["_score"] = array("order"=>'DESC');
$indexParams['body']['sort'] = $newSort;
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
}
$result = self::$_client->search($indexParams);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
/**
* Search
*
* @param string $type
* @param array $query
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public function searchGroup($type = '', $query = array(), $sort = array(), $offset = 0, $limit = 0, $group = "", $facets = array(), $minimum_should_match = '0%', $fields = array(), $aggs = array())
{
$list = array();
try {
$index = self::$_index;
$indexParams = array();
$indexParams['index'] = $index;
$indexParams['type'] = $type;
if(count($group) > 0) $indexParams['body']['size'] = 0;
else{
if (!empty($limit)) {
$indexParams['body']['from'] = $offset;
$indexParams['body']['size'] = $limit;
}
}
foreach ($query as $key => $value) {
if (isset($value['key']))
$key = $value['key'];
$value['condition'] = isset($value['condition']) ? $value['condition'] : 'and';
$value['comparison'] = isset($value['comparison']) ? $value['comparison'] : '=';
if ($value['comparison'] == ">" || $value['comparison'] == ">=") {
$value['value'] = array($value['value'], null);
} elseif ($value['comparison'] == "<" || $value['comparison'] == "<=") {
$value['value'] = array(null, $value['value']);
}
$comparison = $this->getComparison($value['comparison']);
$condition = $this->getCondition($value['condition']);
if ($comparison == 'range' && is_array($value)) {
$__cond = array();
if (!empty($value['value'][0])) {
$__cond['from'] = $value['value'][0];
}
if (!empty($value['value'][1])) {
$__cond['to'] = $value['value'][1];
}
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $__cond;
} elseif ($comparison == 'query_string') {
$indexParams['body']['query']['bool'][$condition][]['query_string'] = array('default_field' => $key, 'query' => $value['value']);
} elseif (is_array($value)) {
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
} else
$indexParams['body']['query']['bool'][$condition][][$comparison][$key] = $value['value'];
}
if(!empty($minimum_should_match) && $minimum_should_match != '0%'){
$indexParams['body']['query']['bool']['minimum_should_match']= $minimum_should_match;
}
foreach ($sort as $key => $value) {
$indexParams['body']['sort'][$key] = strtolower($value);
}
if (!empty($group)) {
foreach ($group as $value) {
$indexParams['body']['aggs']['group_by_' . $value]['terms']['field'] = $value;
$indexParams['body']['aggs']['group_by_' . $value]['terms']['size'] = $limit;
}
}
foreach ($aggs as $key => $value) {
$indexParams['body']['aggs'][$key] = $value;
}
if (count($facets) > 0) {
foreach ($facets as $item) {
$indexParams['body']['facets'][$item]['terms']['field'] = $item;
$indexParams['body']['facets'][$item]['terms']['size'] = 500000;
}
}
if (count($fields) > 0) {
$indexParams['body']['_source'] = $fields;
}
// echo '<pre>';
// echo serialize($indexParams['body']);die;
// var_dump(\GuzzleHttp\json_encode($indexParams));
$startTime = gettimeofday(true);
$result = self::$_client->search($indexParams);
$endTime = gettimeofday(true);
if (isset($result['hits']) && $result['hits']['total'] > 0) {
$list['total'] = $result['hits']['total'];
foreach ($result['hits']['hits'] as $value) {
$list['data'][$value['_id']] = $value['_source'];
}
}
if (count($group)) {
$list['group_by'] = $result['aggregations'];
}
if (count($facets) > 0) {
$list['facets'] = $result['facets'];
}
if (count($aggs)) {
$list['aggregations'] = $result['aggregations'];
}
} catch (\Elasticsearch\Common\Exceptions\ClientErrorResponseException $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
Logger::logElasticSearch($e);
} catch (\Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost $e) {
Logger::logElasticSearch($e);
} catch (\Exception $e) {
Logger::logElasticSearch($e);
}
return $list;
}
}
|
| #13 | Model\Adapter\Elastic::getInstance() /srv/www/subdomain-sangiare/xe/app/models/Traits/ElasticTrait.php (99) <?php
namespace Model\Traits;
use Library\Common;
use Model\Adapter\Elastic;
trait ElasticTrait
{
/**
* Format Mapping Data
*
* @param object $object
*
* @return object
*/
public static function formatMapping($object)
{
return $object;
}
/**
* Set cache
*
* @param object $data
*
* @return bool
*/
public static function setCache($data)
{
try {
$index = Common::getElasticSearchIndexName();
$elastic = Elastic::getInstance();
$data = self::formatMapping($data);
$elastic->setIndex($index, self::$esType, $data->{self::$primaryKey}, (array)$data);
return true;
} catch (\Exception $e) {
}
return false;
}
public static function updateCache($data)
{
try {
$index = Common::getElasticSearchIndexName();
Elastic::update(self::$esType, $data);
} catch (\Exception $e) {
print_r($e->getMessage()); die;
}
return false;
}
/**
* @param $id
*
* @return object|null
*/
public static function getCache($id)
{
$elastic = Elastic::getInstance();
$object = $elastic->get(self::$esType, $id);
if (!empty($object) && !is_object($object)) {
$object = (object)$object;
}
return $object;
}
/**
* Get by Multi id
*
* @param array $listId
*
* @return array
*/
public static function getMultiCache($listId)
{
$elastic = Elastic::getInstance();
$listData = $elastic->getMulti(self::$esType, $listId);
$listObject = [];
foreach ($listData as $object) {
$listObject[$object[self::$primaryKey]] = (object)$object;
}
return $listObject;
}
/**
* Query in Elastic
*
* @param array $params
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array|mixed|null
*/
public static function getCacheQuery($params = array(), $sort = array(), $offset = 0, $limit = 10)
{
$elastic = Elastic::getInstance();
$listData = $elastic->search(self::$esType, $params, $sort, $offset, $limit);
if (empty($listData)) {
return array();
}
$listObject = [];
foreach ($listData['data'] as $object) {
$listObject[$object[self::$primaryKey]] = (object)$object;
}
return $listObject;
}
/**
* Get total Province
*
* @param array $params
*
* @return integer
*/
public static function getCacheCount($params = array())
{
$elastic = Elastic::getInstance();
return (int)$elastic->getCount(self::$esType, $params);
}
/**
* Delete
*
* @param integer $id
*
* @return bool
*/
public static function deleteCache($id)
{
$elastic = Elastic::getInstance();
return $elastic->delete(self::$esType, $id);
}
/**
* Delete query
*
* @param array $params
*
* @return bool
*/
public static function deleteCacheQuery($params = array())
{
$elastic = Elastic::getInstance();
return $elastic->deleteQuery(self::$esType, $params);
}
/**
* Flush all cache
*
* @return bool
*/
public static function flushCache()
{
$params[] = array('key' => self::$primaryKey, 'value' => array(0, null), 'comparison' => 'between');
return self::deleteCacheQuery($params);
}
} |
| #14 | Model\Products::getCacheQuery(Array([0] => Array([key] => status, [value] => 1, [comparison] => =), [1] => Array([key] => category_id, [value] => Array(14), [comparison] => in)), Array([updated_at] => desc), 0, 30) /srv/www/subdomain-sangiare/xe/app/models/Traits/MysqlTrait.php (208) <?php
namespace Model\Traits;
use Core\Debug;
use Model\Adapter\Mysql;
trait MysqlTrait
{
/**
* Save
*
* @param object $object
* @param bool $sync
* @param bool $saveAt
*
* @return object
* @throws \Exception
*/
public static function save($object, $sync = true, $saveAt = true)
{
$_object = self::get($object->{self::$primaryKey});
if ($_object) {
$object = self::_update($object, $sync, $saveAt);
} else {
$object = self::_insert($object, $sync, $saveAt);
}
return $object;
}
/**
* Insert
*
* @param object $object
* @param bool $sync
* @param bool $saveAt
*
* @return object|null
* @throws \Exception
*/
public static function _insert($object, $sync = true, $saveAt = true)
{
if (!empty($saveAt)) {
if (property_exists($object, 'created_at')) {
$object->created_at = time();
}
if (property_exists($object, 'updated_at')) {
$object->updated_at = time();
}
if (property_exists($object, 'modified_date')) {
$object->modified_date = time();
}
}
$id = Mysql::insertGetId(self::$table, (array)$object);
if ($id) {
$object->{self::$primaryKey} = $id;
// Sync cache Elastic Search
if ($sync && !empty(self::$esSync)) {
self::setCache($object);
}
return $object;
}
return null;
}
/**
* Update
*
* @param object $object
* @param bool $sync
* @param bool $saveAt
*
* @return object|null
* @throws \Exception
*/
public static function _update($object, $sync = true, $saveAt = true)
{
if (!empty($saveAt)) {
if (property_exists($object, 'updated_at')) {
$object->updated_at = time();
}
if (property_exists($object, 'modified_date')) {
$object->modified_date = time();
}
}
$where[self::$primaryKey] = $object->{self::$primaryKey};
if (Mysql::update(self::$table, (array)$object, $where)) {
// Sync cache Elastic Search
if ($sync && !empty(self::$esSync)) {
self::setCache($object);
}
return $object;
}
return null;
}
/**
* Get by ID
*
* @param integer $id
* @param bool $getCacheEs
*
* @return object|null
*/
public static function get($id, $cacheEs = true)
{
// get cache Elastic Search
if (!empty(self::$esSync) && !empty($cacheEs)) {
$object = self::getCache($id);
if (!empty($object)) {
return $object;
}
}
$object = self::getById(self::$table, self::$primaryKey, $id);
if (!empty($object)) {
// Sync cache Elastic Search
if (!empty(self::$esSync) && !empty($cacheEs)) {
self::setCache($object);
}
}
return $object;
}
/**
* Get Query
*
* @param array $params
* @param array $sort
*
* @return object|null
*/
public static function getQuery($params = array(), $sort = array())
{
if(!empty(self::$esSync)) {
$object = self::getCacheQuery($params, $sort, 0, 1);
if (!empty($object) && count($object) > 0) {
return array_shift($object);
}
}
$object = self::query(self::$table, self::$primaryKey, $params, $sort, 0, 1);
if (!empty($object)) {
$object = array_shift($object);
// set cache Elastic Search
if(!empty(self::$esSync)) {
self::setCache($object);
}
}
return $object;
}
/**
* Get list by ID
*
* @param array $listId
* @param array $sort
*
* @return array
*/
public static function getList($listId = array(), $sort = array())
{
$limit = count($listId);
$listObject = array();
if (!is_array($listId) || count($listId) == 0) {
return $listObject;
}
$params = array();
$params[] = array('key' => self::$primaryKey, 'value' => $listId, 'comparison' => 'in');
if (!empty(self::$esSync)) {
$listObject = self::getCacheQuery($params, $sort, 0, $limit);
if (!empty($listObject)) {
return $listObject;
}
}
$_listObject = self::query(self::$table, self::$primaryKey, $params, $sort, 0, $limit);
foreach ($_listObject as $object) {
if (!empty(self::$esSync)) {
self::setCache($object);
}
$listObject[$object->{self::$primaryKey}] = $object;
}
return $listObject;
}
/**
* Get list
*
* @param array $params | array('field' => array('value' => $value, 'comparison' => '=')
* $params['field'] = array('value' => $value, 'comparison' => '=')
* @param array $sort
* @param int $offset
* @param int $limit
*
* @return array
*/
public static function getListQuery($params = array(), $sort = array(), $offset = 0, $limit = 10)
{
$listObject = array();
// Get cache Elasticsearch
if (!empty(self::$esSync)) {
$listObject = self::getCacheQuery($params, $sort, $offset, $limit);
if (!empty($listObject)) {
return $listObject;
}
}
$_listObject = self::query(self::$table, self::$primaryKey, $params, $sort, $offset, $limit);
foreach ($_listObject as $object) {
if (!empty(self::$esSync)) {
self::setCache($object);
}
$listObject[$object->{self::$primaryKey}] = $object;
}
return $listObject;
}
/**
* Get list All
*
* @param array $params | array('field' => array('value' => $value, 'comparison' => '=')
* $params['field'] = array('value' => $value, 'comparison' => '=')
* @param array $sort
*
* @return array
*/
public static function getListQueryAll($params = array(), $sort = array())
{
$listObject = array();
// Get cache Elastic Search
if (!empty(self::$esSync)) {
$listObject = self::getCacheQuery($params, $sort, 0, 10000);
if (!empty($listObject)) {
return $listObject;
}
}
$_listObject = self::query(self::$table, self::$primaryKey, $params, $sort, 0, 10000);
foreach ($_listObject as $object) {
if (!empty(self::$esSync)) {
self::setCache($object);
}
$listObject[$object->{self::$primaryKey}] = $object;
}
return $listObject;
}
/**
* Get total Province
*
* @param array $params
*
* @return array|int
*/
public static function getTotal($params = array())
{
// Get cache Elastic Search
if (!empty(self::$esSync)) {
$total = self::getCacheCount($params);
if ($total > 0) {
return $total;
}
}
return (int)self::count(self::$table, $params);
}
/**
* Delete
*
* @param array $params
*
* @return bool
*/
public static function _delete($params)
{
if (self::delete(self::$table, $params)) {
if (!empty(self::$esSync)) {
self::deleteCacheQuery($params);
}
return true;
}
return false;
}
/**
* Delete
*
* @param integer $id
*
* @return bool
*/
public static function _deleteById($id)
{
$params = array();
$params[] = array('key' => self::$primaryKey, 'value' => $id);
if (self::delete(self::$table, $params)) {
if (!empty(self::$esSync)) {
self::deleteCacheQuery($params);
}
return true;
}
return false;
}
} |
| #15 | Model\Products::getListQuery(Array([0] => Array([key] => status, [value] => 1, [comparison] => =), [1] => Array([key] => category_id, [value] => Array(14), [comparison] => in)), Array([updated_at] => desc), 0, 30) /srv/www/subdomain-sangiare/xe/app/modules/Index/Controller/IndexController.php (56) <?php
namespace Index\Controller;
use Core\App;
use Core\Debug;
use Core\FrontendController;
use Library\Firebase;
use Library\Notification;
use Library\OAuth;
use Library\Sms as SmsLib;
use Model\Banner;
use Model\Products;
use Library\Category as CategoryLib;
class IndexController extends FrontendController
{
public function clearCacheAction()
{
$files = glob(APP_PATH . '/data/cache/volt/*');
foreach ($files as $file) {
if (is_file($file))
unlink($file);
}
echo "Done";
}
public function indexAction()
{
/*$testSendSms = $this->request->getQuery('debug');
if (!empty($testSendSms)) {
// Create User OTP
$otpCode = OAuth::createOtpCode();
//$otpCode = "000000";
$message = OAuth::getOtpMessage($otpCode);
// Send SMS OTP to Phone
$smsLib = new SmsLib();
$send = $smsLib::send('0975484789', $message);
Debug::pr($send);
}*/
// $params = array();
// $params[] = array('key' => 'status', 'value' => 1, 'comparison' => '=');
// $params[] = array('key' => 'category', 'value' => 1, 'comparison' => '=');
//$params[] = array('key' => 'updated_at', 'value' => time() - 60 * 60 * 12, 'comparison' => '<');
$dealProduct = array();
// for ($i = 1; $i < 12; $i++) {
$dealProduct = Products::getListQuery(
[
array('key' => 'status', 'value' => 1, 'comparison' => '='),
array('key' => 'category_id', 'value' => [1,2,3,4,5,6,7,8,9,10,11,12,13,14], 'comparison' => 'in')
]
, ["updated_at" => "desc"], 0, 30
);
// $dealProduct = array_merge($dealProduct, $dealProduct_);
// }
$homeProduct = array();
/*foreach(\Model\Category::getMainMenu() as $cId => $c) {
$homeProduct[$cId] = Products::getListQuery(array(array('key' => 'category_ids', 'value' => [$cId], 'comparison' => 'in'), array('key' => 'status', 'value' => 1, 'comparison' => '=')), ["updated_at"=>"desc"], 0, 18);
}*/
// $banners = Banner::getListQuery([array('key' => 'type', 'value' => 'category', 'comparison' => '=')], array('sort' => 'ASC'), 0, 7);
$listBanner = array();
// foreach ($banners as $b) {
// $listBanner[] =
// [
// 'id' => $b->id,
// 'name' => $b->name,
// 'image' => $b->image,
// 'url' => $b->link
// ];
// }
for($i=1;$i<5;$i++)
$listBanner[] =
[
'id' => 1,
'name' => "sgr",
'image' => "/img/banner/bn-0$i.jpg",
'url' => "/app"
];
shuffle($listBanner);
$listBanner = array_slice($listBanner, 0, 12);
$this->view->listCategory = CategoryLib::getCategoryMenuV2();
$this->view->listBanner = $listBanner;
$this->view->homeProduct = $homeProduct;
$this->view->dealProduct = $dealProduct;
}
}
|
| #16 | Index\Controller\IndexController->indexAction() |
| #17 | Phalcon\Dispatcher->callActionMethod(Object(Index\Controller\IndexController), indexAction, Array()) |
| #18 | Phalcon\Dispatcher->dispatch() /srv/www/subdomain-sangiare/xe/app/Bootstrap.php (314) <?php
namespace Core;
use Application\Cache\Manager as CacheManager;
/**
* Bootstrap
* @copyright Copyright (c) 2011 - 2014 Aleksandr Torosh (http://wezoom.com.ua)
* @author Aleksandr Torosh <webtorua@gmail.com>
*/
class Bootstrap
{
public function run()
{
$di = new \Phalcon\DI\FactoryDefault();
// Config
require_once APPLICATION_PATH . '/modules/Cms/Config.php';
$config = \Cms\Config::get();
$di->set('config', $config);
// Registry
$registry = new \Phalcon\Registry();
$di->set('registry', $registry);
// Loader
$loader = new \Phalcon\Loader();
$loader->registerNamespaces($config->loader->namespaces->toArray());
$loader->registerDirs([APPLICATION_PATH . "/plugins/"]);
//$loader->registerFiles([APPLICATION_PATH . '/../vendor/autoload.php']);
$loader->register();
// Database
$db = new \Phalcon\Db\Adapter\Pdo\Mysql([
"host" => $config->database->host,
"username" => $config->database->username,
"password" => $config->database->password,
"dbname" => $config->database->dbname,
"charset" => $config->database->charset,
]);
$di->set('db', $db);
// View
$this->initView($di);
// URL
$url = new \Phalcon\Mvc\Url();
$url->setBasePath($config->application->basePath);
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri($config->application->staticUri);
$di->set('url', $url);
// Cache
$this->initCache($di);
// CMS
//$cmsModel = new \Cms\Model\Configuration();
//$registry->cms = $cmsModel->getConfig();
// Application
$application = new \Phalcon\Mvc\Application();
$application->registerModules($config->modules->toArray());
// Events Manager, Dispatcher
$this->initEventManager($di);
// Session
$session = new \Phalcon\Session\Adapter\Files();
$session->start();
$di->set('session', $session);
$acl = new \Application\Acl\DefaultAcl();
$di->set('acl', $acl);
// JS Assets
$this->initAssetsManager($di);
// Flash helper
$flash = new \Phalcon\Flash\Session([
'error' => 'alert alert-danger',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
'warning' => 'alert alert-warning',
]);
$di->set('flash', $flash);
$flashSession = new \Phalcon\Flash\Session([
'error' => 'alert alert-danger flashSession',
'success' => 'alert alert-success flashSession',
'notice' => 'alert alert-info flashSession',
'warning' => 'alert alert-warning flashSession',
]);
$di->set('flashSession', $flashSession);
$di->set('helper', new \Application\Mvc\Helper());
// Routing
$this->initRouting($application, $di);
$application->setDI($di);
// Main dispatching process
$response = $this->dispatch($di);
$response->send();
}
private function initRouting($application, $di)
{
$router = new \Application\Mvc\Router\DefaultRouter();
$router->setDi($di);
foreach ($application->getModules() as $module) {
$routesClassName = str_replace('Module', 'Routes', $module['className']);
if (class_exists($routesClassName)) {
$routesClass = new $routesClassName();
$router = $routesClass->init($router);
}
$initClassName = str_replace('Module', 'Init', $module['className']);
if (class_exists($initClassName)) {
new $initClassName();
}
}
$di->set('router', $router);
}
private function initAssetsManager($di)
{
$config = $di->get('config');
$assetsManager = new \Application\Assets\Manager();
$js_collection = $assetsManager->collection('js')
->setLocal(true)
->addFilter(new \Phalcon\Assets\Filters\Jsmin())
->setTargetPath(ROOT . '/assets/js.js')
->setTargetUri('assets/js.js')
->join(true);
if ($config->assets->js) {
foreach ($config->assets->js as $js) {
$js_collection->addJs(ROOT . '/' . $js);
}
}
// Admin JS Assets
$assetsManager->collection('modules-admin-js')
->setLocal(true)
->addFilter(new \Phalcon\Assets\Filters\Jsmin())
->setTargetPath(ROOT . '/assets/modules-admin.js')
->setTargetUri('assets/modules-admin.js')
->join(true);
// Admin LESS Assets
$assetsManager->collection('modules-admin-less')
->setLocal(true)
->addFilter(new \Application\Assets\Filter\Less())
->setTargetPath(ROOT . '/assets/modules-admin.less')
->setTargetUri('assets/modules-admin.less')
->join(true)
->addCss(APPLICATION_PATH . '/modules/Admin/assets/admin.less');
$di->set('assets', $assetsManager);
}
private function initEventManager($di)
{
$eventsManager = new \Phalcon\Events\Manager();
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) use ($di) {
new \Plugin\CheckPoint($di->get('request'));
new \Plugin\Localization($dispatcher);
new \Plugin\AdminLocalization($di->get('config'));
new \Plugin\Acl($di->get('acl'), $dispatcher, $di->get('view'));
new \Plugin\MobileDetect($di->get('session'), $di->get('view'), $di->get('request'));
new \Plugin\Layout($di->get('view'), $dispatcher);
});
$eventsManager->attach("dispatch:afterDispatchLoop", function ($event, $dispatcher) use ($di) {
new \Plugin\Title($di);
});
// Profiler
$config = $di->get('config');
if (!empty($config->application->profilter)) {
$profiler = new \Phalcon\Db\Profiler();
$di->set('profiler', $profiler);
$eventsManager->attach('db', function ($event, $db) use ($profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($db->getSQLStatement());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
}
$db = $di->get('db');
$db->setEventsManager($eventsManager);
$dispatcher->setEventsManager($eventsManager);
$di->set('dispatcher', $dispatcher);
}
private function initView($di)
{
$view = new \Phalcon\Mvc\View();
define('MAIN_VIEW_PATH', '../../../views/');
$view->setMainView(MAIN_VIEW_PATH . 'main');
//$view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/');
$view->setLayout('main');
$view->setPartialsDir(MAIN_VIEW_PATH . '/partials/');
// Volt
$volt = new \Application\Mvc\View\Engine\Volt($view, $di);
$volt->setOptions(['compiledPath' => APPLICATION_PATH . '/../data/cache/volt/']);
$volt->initCompiler();
$phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di);
$viewEngines = [
".volt" => $volt,
".phtml" => $phtml,
];
$view->registerEngines($viewEngines);
$ajax = $di->get('request')->getQuery('_ajax');
if ($ajax) {
$view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
}
$di->set('view', $view);
return $view;
}
private function initCache($di)
{
$config = $di->get('config');
$cacheFrontend = new \Phalcon\Cache\Frontend\Data([
"lifetime" => 60,
"prefix" => HOST_HASH,
]);
$cache = null;
switch ($config->cache) {
case 'file':
$cache = new \Phalcon\Cache\Backend\File($cacheFrontend, [
"cacheDir" => APPLICATION_PATH . "/../data/cache/backend/"
]);
break;
case 'memcache':
$cache = new \Phalcon\Cache\Backend\Memcache(
$cacheFrontend, [
"host" => $config->memcache->host,
"port" => $config->memcache->port,
]);
break;
case 'memcached':
$cache = new \Phalcon\Cache\Backend\Libmemcached(
$cacheFrontend, [
"host" => $config->memcached->host,
"port" => $config->memcached->port,
]);
break;
}
$di->set('cache', $cache, true);
$di->set('modelsCache', $cache, true);
\Application\Widget\Proxy::$cache = $cache; // Modules Widget System
$modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory();
$di->set('modelsMetadata', $modelsMetadata);
$di->set('cacheManager', new CacheManager());
}
private function dispatch($di)
{
$router = $di['router'];
$router->handle();
$view = $di['view'];
$dispatcher = $di['dispatcher'];
$response = $di['response'];
$dispatcher->setModuleName($router->getModuleName());
$dispatcher->setControllerName($router->getControllerName());
$dispatcher->setActionName($router->getActionName());
$dispatcher->setParams($router->getParams());
$moduleName = \Application\Utils\ModuleName::camelize($router->getModuleName());
$ModuleClassName = $moduleName . '\Module';
if (class_exists($ModuleClassName)) {
$module = new $ModuleClassName;
$module->registerAutoloaders();
$module->registerServices($di);
}
$view->start();
$config = $di['config'];
if (!empty($config->application->debug)) {
$debug = new \Phalcon\Debug();
$debug->listen();
$dispatcher->dispatch();
} else {
try {
$dispatcher->dispatch();
} catch (\Phalcon\Exception $e) {
// Errors catching
$view->setViewsDir(__DIR__ . '/modules/Index/views/');
$view->setPartialsDir('');
$view->e = $e;
if ($e instanceof \Phalcon\Mvc\Dispatcher\Exception) {
$response->setStatusCode(404, 'Not Found');
$view->partial('error/error404');
} else {
$response->setStatusCode(503, 'Service Unavailable');
$view->partial('error/error503');
}
return $response;
}
}
$view->render(
$dispatcher->getControllerName(),
$dispatcher->getActionName(),
$dispatcher->getParams()
);
$view->finish();
// AJAX
$request = $di['request'];
$_ajax = $request->getQuery('_ajax');
if ($_ajax) {
$contents = $view->getContent();
$return = new \stdClass();
$return->html = $contents;
$return->title = $di->get('helper')->title()->get();
$return->success = true;
if ($view->bodyClass) {
$return->bodyClass = $view->bodyClass;
}
$headers = $response->getHeaders()->toArray();
if (isset($headers[404]) || isset($headers[503])) {
$return->success = false;
}
$response->setContentType('application/json', 'UTF-8');
$response->setContent(json_encode($return));
} else {
$response->setContent($view->getContent());
}
return $response;
}
}
|
| #19 | Core\Bootstrap->dispatch(Object(Phalcon\Di\FactoryDefault)) /srv/www/subdomain-sangiare/xe/app/Bootstrap.php (105) <?php
namespace Core;
use Application\Cache\Manager as CacheManager;
/**
* Bootstrap
* @copyright Copyright (c) 2011 - 2014 Aleksandr Torosh (http://wezoom.com.ua)
* @author Aleksandr Torosh <webtorua@gmail.com>
*/
class Bootstrap
{
public function run()
{
$di = new \Phalcon\DI\FactoryDefault();
// Config
require_once APPLICATION_PATH . '/modules/Cms/Config.php';
$config = \Cms\Config::get();
$di->set('config', $config);
// Registry
$registry = new \Phalcon\Registry();
$di->set('registry', $registry);
// Loader
$loader = new \Phalcon\Loader();
$loader->registerNamespaces($config->loader->namespaces->toArray());
$loader->registerDirs([APPLICATION_PATH . "/plugins/"]);
//$loader->registerFiles([APPLICATION_PATH . '/../vendor/autoload.php']);
$loader->register();
// Database
$db = new \Phalcon\Db\Adapter\Pdo\Mysql([
"host" => $config->database->host,
"username" => $config->database->username,
"password" => $config->database->password,
"dbname" => $config->database->dbname,
"charset" => $config->database->charset,
]);
$di->set('db', $db);
// View
$this->initView($di);
// URL
$url = new \Phalcon\Mvc\Url();
$url->setBasePath($config->application->basePath);
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri($config->application->staticUri);
$di->set('url', $url);
// Cache
$this->initCache($di);
// CMS
//$cmsModel = new \Cms\Model\Configuration();
//$registry->cms = $cmsModel->getConfig();
// Application
$application = new \Phalcon\Mvc\Application();
$application->registerModules($config->modules->toArray());
// Events Manager, Dispatcher
$this->initEventManager($di);
// Session
$session = new \Phalcon\Session\Adapter\Files();
$session->start();
$di->set('session', $session);
$acl = new \Application\Acl\DefaultAcl();
$di->set('acl', $acl);
// JS Assets
$this->initAssetsManager($di);
// Flash helper
$flash = new \Phalcon\Flash\Session([
'error' => 'alert alert-danger',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
'warning' => 'alert alert-warning',
]);
$di->set('flash', $flash);
$flashSession = new \Phalcon\Flash\Session([
'error' => 'alert alert-danger flashSession',
'success' => 'alert alert-success flashSession',
'notice' => 'alert alert-info flashSession',
'warning' => 'alert alert-warning flashSession',
]);
$di->set('flashSession', $flashSession);
$di->set('helper', new \Application\Mvc\Helper());
// Routing
$this->initRouting($application, $di);
$application->setDI($di);
// Main dispatching process
$response = $this->dispatch($di);
$response->send();
}
private function initRouting($application, $di)
{
$router = new \Application\Mvc\Router\DefaultRouter();
$router->setDi($di);
foreach ($application->getModules() as $module) {
$routesClassName = str_replace('Module', 'Routes', $module['className']);
if (class_exists($routesClassName)) {
$routesClass = new $routesClassName();
$router = $routesClass->init($router);
}
$initClassName = str_replace('Module', 'Init', $module['className']);
if (class_exists($initClassName)) {
new $initClassName();
}
}
$di->set('router', $router);
}
private function initAssetsManager($di)
{
$config = $di->get('config');
$assetsManager = new \Application\Assets\Manager();
$js_collection = $assetsManager->collection('js')
->setLocal(true)
->addFilter(new \Phalcon\Assets\Filters\Jsmin())
->setTargetPath(ROOT . '/assets/js.js')
->setTargetUri('assets/js.js')
->join(true);
if ($config->assets->js) {
foreach ($config->assets->js as $js) {
$js_collection->addJs(ROOT . '/' . $js);
}
}
// Admin JS Assets
$assetsManager->collection('modules-admin-js')
->setLocal(true)
->addFilter(new \Phalcon\Assets\Filters\Jsmin())
->setTargetPath(ROOT . '/assets/modules-admin.js')
->setTargetUri('assets/modules-admin.js')
->join(true);
// Admin LESS Assets
$assetsManager->collection('modules-admin-less')
->setLocal(true)
->addFilter(new \Application\Assets\Filter\Less())
->setTargetPath(ROOT . '/assets/modules-admin.less')
->setTargetUri('assets/modules-admin.less')
->join(true)
->addCss(APPLICATION_PATH . '/modules/Admin/assets/admin.less');
$di->set('assets', $assetsManager);
}
private function initEventManager($di)
{
$eventsManager = new \Phalcon\Events\Manager();
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) use ($di) {
new \Plugin\CheckPoint($di->get('request'));
new \Plugin\Localization($dispatcher);
new \Plugin\AdminLocalization($di->get('config'));
new \Plugin\Acl($di->get('acl'), $dispatcher, $di->get('view'));
new \Plugin\MobileDetect($di->get('session'), $di->get('view'), $di->get('request'));
new \Plugin\Layout($di->get('view'), $dispatcher);
});
$eventsManager->attach("dispatch:afterDispatchLoop", function ($event, $dispatcher) use ($di) {
new \Plugin\Title($di);
});
// Profiler
$config = $di->get('config');
if (!empty($config->application->profilter)) {
$profiler = new \Phalcon\Db\Profiler();
$di->set('profiler', $profiler);
$eventsManager->attach('db', function ($event, $db) use ($profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($db->getSQLStatement());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
}
$db = $di->get('db');
$db->setEventsManager($eventsManager);
$dispatcher->setEventsManager($eventsManager);
$di->set('dispatcher', $dispatcher);
}
private function initView($di)
{
$view = new \Phalcon\Mvc\View();
define('MAIN_VIEW_PATH', '../../../views/');
$view->setMainView(MAIN_VIEW_PATH . 'main');
//$view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/');
$view->setLayout('main');
$view->setPartialsDir(MAIN_VIEW_PATH . '/partials/');
// Volt
$volt = new \Application\Mvc\View\Engine\Volt($view, $di);
$volt->setOptions(['compiledPath' => APPLICATION_PATH . '/../data/cache/volt/']);
$volt->initCompiler();
$phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di);
$viewEngines = [
".volt" => $volt,
".phtml" => $phtml,
];
$view->registerEngines($viewEngines);
$ajax = $di->get('request')->getQuery('_ajax');
if ($ajax) {
$view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
}
$di->set('view', $view);
return $view;
}
private function initCache($di)
{
$config = $di->get('config');
$cacheFrontend = new \Phalcon\Cache\Frontend\Data([
"lifetime" => 60,
"prefix" => HOST_HASH,
]);
$cache = null;
switch ($config->cache) {
case 'file':
$cache = new \Phalcon\Cache\Backend\File($cacheFrontend, [
"cacheDir" => APPLICATION_PATH . "/../data/cache/backend/"
]);
break;
case 'memcache':
$cache = new \Phalcon\Cache\Backend\Memcache(
$cacheFrontend, [
"host" => $config->memcache->host,
"port" => $config->memcache->port,
]);
break;
case 'memcached':
$cache = new \Phalcon\Cache\Backend\Libmemcached(
$cacheFrontend, [
"host" => $config->memcached->host,
"port" => $config->memcached->port,
]);
break;
}
$di->set('cache', $cache, true);
$di->set('modelsCache', $cache, true);
\Application\Widget\Proxy::$cache = $cache; // Modules Widget System
$modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory();
$di->set('modelsMetadata', $modelsMetadata);
$di->set('cacheManager', new CacheManager());
}
private function dispatch($di)
{
$router = $di['router'];
$router->handle();
$view = $di['view'];
$dispatcher = $di['dispatcher'];
$response = $di['response'];
$dispatcher->setModuleName($router->getModuleName());
$dispatcher->setControllerName($router->getControllerName());
$dispatcher->setActionName($router->getActionName());
$dispatcher->setParams($router->getParams());
$moduleName = \Application\Utils\ModuleName::camelize($router->getModuleName());
$ModuleClassName = $moduleName . '\Module';
if (class_exists($ModuleClassName)) {
$module = new $ModuleClassName;
$module->registerAutoloaders();
$module->registerServices($di);
}
$view->start();
$config = $di['config'];
if (!empty($config->application->debug)) {
$debug = new \Phalcon\Debug();
$debug->listen();
$dispatcher->dispatch();
} else {
try {
$dispatcher->dispatch();
} catch (\Phalcon\Exception $e) {
// Errors catching
$view->setViewsDir(__DIR__ . '/modules/Index/views/');
$view->setPartialsDir('');
$view->e = $e;
if ($e instanceof \Phalcon\Mvc\Dispatcher\Exception) {
$response->setStatusCode(404, 'Not Found');
$view->partial('error/error404');
} else {
$response->setStatusCode(503, 'Service Unavailable');
$view->partial('error/error503');
}
return $response;
}
}
$view->render(
$dispatcher->getControllerName(),
$dispatcher->getActionName(),
$dispatcher->getParams()
);
$view->finish();
// AJAX
$request = $di['request'];
$_ajax = $request->getQuery('_ajax');
if ($_ajax) {
$contents = $view->getContent();
$return = new \stdClass();
$return->html = $contents;
$return->title = $di->get('helper')->title()->get();
$return->success = true;
if ($view->bodyClass) {
$return->bodyClass = $view->bodyClass;
}
$headers = $response->getHeaders()->toArray();
if (isset($headers[404]) || isset($headers[503])) {
$return->success = false;
}
$response->setContentType('application/json', 'UTF-8');
$response->setContent(json_encode($return));
} else {
$response->setContent($view->getContent());
}
return $response;
}
}
|
| #20 | Core\Bootstrap->run() /srv/www/subdomain-sangiare/xe/public/index.php (50) <?php
date_default_timezone_set('Asia/Ho_Chi_Minh');
chdir(dirname(__DIR__));
define('ROOT', __DIR__);
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', realpath('..'));
define('APPLICATION_PATH', __DIR__ . '/../app');
define('HOST_HASH', substr(md5($_SERVER['HTTP_HOST']), 0, 12));
$production = array('sangiare.vn');
$staging = array('staging.sangiare.vn');
$host = $_SERVER['HTTP_HOST'];
/*
if (isset($_SERVER['APPLICATION_ENV'])) {
$applicationEnv = ($_SERVER['APPLICATION_ENV'] ? $_SERVER['APPLICATION_ENV'] : 'production');
} else {
$applicationEnv = (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production');
}
define('APPLICATION_ENV', $applicationEnv);*/
if (in_array($host, $production)) {
define('APPLICATION_ENV', 'production');
error_reporting(0);
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 0);
} else if (in_array($host, $staging)) {
define('APPLICATION_ENV', 'staging');
ini_set('display_errors', 1);
error_reporting(1);
} else {
define('APPLICATION_ENV', 'development');
ini_set('display_errors', 1);
error_reporting(E_ALL);
}
require_once ROOT . '/../vendor/autoload.php';
/**
* Environment variables
*/
$dotEnv = \Dotenv\Dotenv::createUnsafeImmutable(__DIR__ . '/../');
$dotEnv->load();
//try {
require_once APPLICATION_PATH . '/Bootstrap.php';
$bootstrap = new Core\Bootstrap();
$bootstrap->run();
//} catch (\Exception $e) {
// header('Location: https://sangiare.vn/');
// exit();
//} |
| Key | Value |
|---|
| Key | Value |
|---|---|
| USER | nginx |
| HOME | /var/lib/nginx |
| HTTP_HOST | xe.sangiare.vn |
| HTTP_ACCEPT_ENCODING | gzip, br, zstd, deflate |
| HTTP_USER_AGENT | Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com) |
| HTTP_ACCEPT | */* |
| REDIRECT_STATUS | 200 |
| SERVER_NAME | xe.sangiare.vn |
| SERVER_PORT | 443 |
| SERVER_ADDR | 203.162.54.96 |
| REMOTE_PORT | 7555 |
| REMOTE_ADDR | 216.73.216.103 |
| SERVER_SOFTWARE | nginx/1.16.1 |
| GATEWAY_INTERFACE | CGI/1.1 |
| HTTPS | on |
| REQUEST_SCHEME | https |
| SERVER_PROTOCOL | HTTP/1.1 |
| DOCUMENT_ROOT | /srv/www/subdomain-sangiare/xe/public |
| DOCUMENT_URI | /index.php |
| REQUEST_URI | / |
| SCRIPT_NAME | /index.php |
| CONTENT_LENGTH | |
| CONTENT_TYPE | |
| REQUEST_METHOD | GET |
| QUERY_STRING | |
| SCRIPT_FILENAME | /srv/www/subdomain-sangiare/xe/public/index.php |
| FCGI_ROLE | RESPONDER |
| PHP_SELF | /index.php |
| REQUEST_TIME_FLOAT | 1775212176.2709 |
| REQUEST_TIME | 1775212176 |
| APP_NAME | SANGIARE |
| APP_ENV | development |
| APP_PATH | / |
| APP_BASE_URL | http://local.sangiare.vn/ |
| APP_STATIC_URL | http://local.sangiare.vn/ |
| APP_STATIC_MEDIA | https://cdn.sangiare.vn/ |
| APP_PROFILTER | true |
| APP_DEBUG | true |
| DB_DRIVE | Mysql |
| DB_HOST | 203.162.54.96 |
| DB_USER | mannm |
| DB_PASS | minhmanit@11 |
| DB_NAME | sgr |
| DB_CHARSET | utf8 |
| ELASTIC_HOST | 203.162.54.96 |
| ELASTIC_PORT | 8888 |
| ELASTIC_USER | elastic |
| ELASTIC_PASS | sangiare2020 |
| ELASTIC_INDEX | sgr |
| REDIS_HOST | localhost |
| REDIS_PORT | 6379 |
| REDIS_PREFIX | sgr_ |
| REDIS_ENABLE | true |
| REDIS_DEFAULT_TTL | 3600 |
| REDIS_SESSION_HOST | localhost |
| REDIS_SESSION_PORT | 6379 |
| REDIS_SESSION_PREFIX | sgr_session_ |
| REDIS_SESSION_ENABLE | true |
| REDIS_SESSION_DEFAULT_TTL | 3600 |
| REDIS_CACHE_HTML_HOST | localhost |
| REDIS_CACHE_HTML_PORT | 6379 |
| REDIS_CACHE_HTML_PREFIX | sgr_cache_html_ |
| REDIS_CACHE_HTML_ENABLE | true |
| REDIS_CACHE_HTML_DEFAULT_TTL | 3600 |
| SESSION_REDIS_KEY | SANGIARE_SESSID |
| SESSION_USER_LOGIN_KEY | sgr_user_login |
| COOKIE_DOMAIN | .sangiare.vn |
| MAIL_HOST | email-smtp.us-east-1.amazonaws.com |
| MAIL_EMAIL | hotro@sgr |
| MAIL_USER | AKIAJHMETDCGPZWWZIAQ |
| MAIL_PASS | AvUu9vWhIYCoDdlRfsyUVXkgq2/dGOSatteoXRn+wIWi |
| MAIL_PORT | |
| MAIL_SECURITY | |
| MAIL_NAME | |
| SMS_DOMAIN | |
| SMS_BRAND_NAME | |
| SMS_CLIENT_ID | |
| SMS_SECRET | |
| SMS_ACCESS_TOKEN_URL | |
| SMS_BRAND_NAME_OTP_URL | |
| SMS_BRAND_NAME_OTP_SCOPE | |
| VNPAY_VERSION | |
| VNPAY_TMN_CODE | |
| VNPAY_HASH_SECRET | |
| VNPAY_API_URL | |
| VNPAY_RETURN_URL | |
| MOMO_WEB_VERSION | |
| MOMO_WEB_PARTNER_CODE | |
| MOMO_WEB_ACCESS_KEY | |
| MOMO_WEB_SECRET_KEY | |
| MOMO_WEB_API | |
| MOMO_APP_PARTNER_CODE | |
| MOMO_APP_ISO_SCHEME_ID | |
| MOMO_APP_PUBLIC_KEY | |
| MOMO_APP_API_ENDPOINT | |
| MOMO_APP_QUERY_STATUS_API_ENDPOINT | |
| MOMO_APP_REFUND_API_ENDPOINT | |
| FACEBOOK_APP_ID | |
| FACEBOOK_APP_SECRET | |
| FACEBOOK_SCOPE | |
| FACEBOOK_PARAMETER | |
| GOOGLE_WEB_CLIENT_ID | |
| GOOGLE_WEB_CLIENT_SECRET | |
| GOOGLE_WEB_PARAMETER | |
| GOOGLE_WEB_MAP_API_KEY | |
| GOOGLE_IOS_CLIENT_ID | |
| GOOGLE_IOS_SCHEME | |
| GOOGLE_IOS_BUNDLE_ID | |
| GOOGLE_ANDROID_CLIENT_ID | |
| GOOGLE_ANDROID_PACKAGE_ID | |
| LOG_PATH | logs |
| LOG_FILE | error.log |
| LOG_MYSQL | log_mysql.log |
| LOG_ELASTIC | log_elastic.log |
| LOG_REDIS | log_redis.log |
| LOG_WORKER | log_worker.log |
| LOG_REST | log_rest.log |
| LOG_ORDER | log_order.log |
| # | Path |
|---|---|
| 0 | /srv/www/subdomain-sangiare/xe/public/index.php |
| 1 | /srv/www/subdomain-sangiare/xe/vendor/autoload.php |
| 2 | /srv/www/subdomain-sangiare/xe/vendor/composer/autoload_real.php |
| 3 | /srv/www/subdomain-sangiare/xe/vendor/composer/platform_check.php |
| 4 | /srv/www/subdomain-sangiare/xe/vendor/composer/ClassLoader.php |
| 5 | /srv/www/subdomain-sangiare/xe/vendor/composer/autoload_static.php |
| 6 | /srv/www/subdomain-sangiare/xe/vendor/symfony/deprecation-contracts/function.php |
| 7 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-php80/bootstrap.php |
| 8 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-mbstring/bootstrap.php |
| 9 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-ctype/bootstrap.php |
| 10 | /srv/www/subdomain-sangiare/xe/vendor/ralouphie/getallheaders/src/getallheaders.php |
| 11 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-php81/bootstrap.php |
| 12 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-intl-grapheme/bootstrap.php |
| 13 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-intl-normalizer/bootstrap.php |
| 14 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-php73/bootstrap.php |
| 15 | /srv/www/subdomain-sangiare/xe/vendor/symfony/polyfill-php73/Php73.php |
| 16 | /srv/www/subdomain-sangiare/xe/vendor/symfony/string/Resources/functions.php |
| 17 | /srv/www/subdomain-sangiare/xe/vendor/cakephp/core/functions.php |
| 18 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/guzzle/src/functions_include.php |
| 19 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/guzzle/src/functions.php |
| 20 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/functions_include.php |
| 21 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/functions.php |
| 22 | /srv/www/subdomain-sangiare/xe/vendor/swiftmailer/swiftmailer/lib/swift_required.php |
| 23 | /srv/www/subdomain-sangiare/xe/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php |
| 24 | /srv/www/subdomain-sangiare/xe/vendor/phpseclib/phpseclib/phpseclib/bootstrap.php |
| 25 | /srv/www/subdomain-sangiare/xe/vendor/symfony/var-dumper/Resources/functions/dump.php |
| 26 | /srv/www/subdomain-sangiare/xe/vendor/amphp/amp/lib/functions.php |
| 27 | /srv/www/subdomain-sangiare/xe/vendor/cakephp/utility/bootstrap.php |
| 28 | /srv/www/subdomain-sangiare/xe/vendor/cakephp/utility/Inflector.php |
| 29 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient-services/autoload.php |
| 30 | /srv/www/subdomain-sangiare/xe/vendor/psy/psysh/src/functions.php |
| 31 | /srv/www/subdomain-sangiare/xe/vendor/facebook/graph-sdk/src/Facebook/polyfills.php |
| 32 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/aliases.php |
| 33 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Client.php |
| 34 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Service.php |
| 35 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AccessToken/Revoke.php |
| 36 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AccessToken/Verify.php |
| 37 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Model.php |
| 38 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Utils/UriTemplate.php |
| 39 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AuthHandler/Guzzle6AuthHandler.php |
| 40 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AuthHandler/Guzzle7AuthHandler.php |
| 41 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AuthHandler/Guzzle5AuthHandler.php |
| 42 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/AuthHandler/AuthHandlerFactory.php |
| 43 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Http/Batch.php |
| 44 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Http/MediaFileUpload.php |
| 45 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Http/REST.php |
| 46 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Task/Retryable.php |
| 47 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Task/Exception.php |
| 48 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Exception.php |
| 49 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Task/Runner.php |
| 50 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Collection.php |
| 51 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Service/Exception.php |
| 52 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Service/Resource.php |
| 53 | /srv/www/subdomain-sangiare/xe/vendor/google/apiclient/src/Task/Composer.php |
| 54 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Dotenv.php |
| 55 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/RepositoryBuilder.php |
| 56 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php |
| 57 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php |
| 58 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php |
| 59 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php |
| 60 | /srv/www/subdomain-sangiare/xe/vendor/phpoption/phpoption/src/PhpOption/Some.php |
| 61 | /srv/www/subdomain-sangiare/xe/vendor/phpoption/phpoption/src/PhpOption/Option.php |
| 62 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php |
| 63 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php |
| 64 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php |
| 65 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php |
| 66 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php |
| 67 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/AdapterRepository.php |
| 68 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Repository/RepositoryInterface.php |
| 69 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Store/StoreBuilder.php |
| 70 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Store/FileStore.php |
| 71 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Store/StoreInterface.php |
| 72 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Store/File/Paths.php |
| 73 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/Parser.php |
| 74 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/ParserInterface.php |
| 75 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Loader/Loader.php |
| 76 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Loader/LoaderInterface.php |
| 77 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Store/File/Reader.php |
| 78 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Util/Str.php |
| 79 | /srv/www/subdomain-sangiare/xe/vendor/graham-campbell/result-type/src/Success.php |
| 80 | /srv/www/subdomain-sangiare/xe/vendor/graham-campbell/result-type/src/Result.php |
| 81 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Util/Regex.php |
| 82 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/Lines.php |
| 83 | /srv/www/subdomain-sangiare/xe/vendor/phpoption/phpoption/src/PhpOption/None.php |
| 84 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/EntryParser.php |
| 85 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/Lexer.php |
| 86 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/Value.php |
| 87 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Parser/Entry.php |
| 88 | /srv/www/subdomain-sangiare/xe/vendor/vlucas/phpdotenv/src/Loader/Resolver.php |
| 89 | /srv/www/subdomain-sangiare/xe/app/Bootstrap.php |
| 90 | /srv/www/subdomain-sangiare/xe/app/modules/Cms/Config.php |
| 91 | /srv/www/subdomain-sangiare/xe/app/config/environment/development.php |
| 92 | /srv/www/subdomain-sangiare/xe/app/config/global.php |
| 93 | /srv/www/subdomain-sangiare/xe/app/config/modules.php |
| 94 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Loader/Modules.php |
| 95 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Mvc/View/Engine/Volt.php |
| 96 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Widget/Proxy.php |
| 97 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Cache/Manager.php |
| 98 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Acl/DefaultAcl.php |
| 99 | /srv/www/subdomain-sangiare/xe/app/config/acl.php |
| 100 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Assets/Manager.php |
| 101 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Assets/Filter/Less.php |
| 102 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Mvc/Helper.php |
| 103 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Mvc/Router/DefaultRouter.php |
| 104 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Routes.php |
| 105 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/BannerRouter.php |
| 106 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/CategoryRouter.php |
| 107 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/CustomerRouter.php |
| 108 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/IndexRouter.php |
| 109 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/MerchantRouter.php |
| 110 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/OrderRouter.php |
| 111 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/ProductRouter.php |
| 112 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/PushNotificationRouter.php |
| 113 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/SystemRouter.php |
| 114 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/ToolsRouter.php |
| 115 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/UserRouter.php |
| 116 | /srv/www/subdomain-sangiare/xe/app/modules/Admin/Router/UploadRouter.php |
| 117 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Routes.php |
| 118 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/AuthRouter.php |
| 119 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/BannerRouter.php |
| 120 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/CategoryRouter.php |
| 121 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/CheckoutRouter.php |
| 122 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/CommonRouter.php |
| 123 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/CustomerRouter.php |
| 124 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/IndexRouter.php |
| 125 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/IpnRouter.php |
| 126 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/NotificationRouter.php |
| 127 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/ProductRouter.php |
| 128 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/ShopRouter.php |
| 129 | /srv/www/subdomain-sangiare/xe/app/modules/Api/Router/UserRouter.php |
| 130 | /srv/www/subdomain-sangiare/xe/app/modules/Blog/Routes.php |
| 131 | /srv/www/subdomain-sangiare/xe/app/modules/Checkout/Routes.php |
| 132 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Routes.php |
| 133 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Router/AppRouter.php |
| 134 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Router/AuthRouter.php |
| 135 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Router/NotificationRouter.php |
| 136 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Router/StaticRouter.php |
| 137 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Router/UserRouter.php |
| 138 | /srv/www/subdomain-sangiare/xe/app/modules/Product/Routes.php |
| 139 | /srv/www/subdomain-sangiare/xe/app/modules/Product/Router/IndexRouter.php |
| 140 | /srv/www/subdomain-sangiare/xe/app/modules/Product/Router/ShopRouter.php |
| 141 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Utils/ModuleName.php |
| 142 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Module.php |
| 143 | /srv/www/subdomain-sangiare/xe/app/plugins/CheckPoint.php |
| 144 | /srv/www/subdomain-sangiare/xe/app/plugins/Localization.php |
| 145 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Mvc/Helper/CmsCache.php |
| 146 | /srv/www/subdomain-sangiare/xe/app/modules/Cms/Model/Translate.php |
| 147 | /srv/www/subdomain-sangiare/xe/app/plugins/AdminLocalization.php |
| 148 | /srv/www/subdomain-sangiare/xe/data/translations/admin/en.php |
| 149 | /srv/www/subdomain-sangiare/xe/app/plugins/Acl.php |
| 150 | /srv/www/subdomain-sangiare/xe/app/plugins/MobileDetect.php |
| 151 | /srv/www/subdomain-sangiare/xe/vendor/mobiledetect/mobiledetectlib/Mobile_Detect.php |
| 152 | /srv/www/subdomain-sangiare/xe/app/plugins/Layout.php |
| 153 | /srv/www/subdomain-sangiare/xe/app/modules/Index/Controller/IndexController.php |
| 154 | /srv/www/subdomain-sangiare/xe/app/core/FrontendController.php |
| 155 | /srv/www/subdomain-sangiare/xe/app/modules/Application/Mvc/Controller.php |
| 156 | /srv/www/subdomain-sangiare/xe/app/libraries/OAuth.php |
| 157 | /srv/www/subdomain-sangiare/xe/app/core/App.php |
| 158 | /srv/www/subdomain-sangiare/xe/app/core/Session.php |
| 159 | /srv/www/subdomain-sangiare/xe/app/core/Redis/Redis.php |
| 160 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Client.php |
| 161 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/ClientInterface.php |
| 162 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/Options.php |
| 163 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/OptionsInterface.php |
| 164 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/ClusterOption.php |
| 165 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/OptionInterface.php |
| 166 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/Aggregate/RedisCluster.php |
| 167 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/Aggregate/ClusterInterface.php |
| 168 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/AggregateConnectionInterface.php |
| 169 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/ConnectionInterface.php |
| 170 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/ConnectionFactoryOption.php |
| 171 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/Factory.php |
| 172 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/FactoryInterface.php |
| 173 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Cluster/RedisStrategy.php |
| 174 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Cluster/ClusterStrategy.php |
| 175 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Cluster/StrategyInterface.php |
| 176 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Cluster/Hash/CRC16.php |
| 177 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Cluster/Hash/HashGeneratorInterface.php |
| 178 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/Parameters.php |
| 179 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/ParametersInterface.php |
| 180 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/StreamConnection.php |
| 181 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/AbstractConnection.php |
| 182 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Connection/NodeConnectionInterface.php |
| 183 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/ProfileOption.php |
| 184 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Profile/Factory.php |
| 185 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Profile/RedisVersion320.php |
| 186 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Profile/RedisProfile.php |
| 187 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Profile/ProfileInterface.php |
| 188 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Configuration/PrefixOption.php |
| 189 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Command/Processor/KeyPrefixProcessor.php |
| 190 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Command/Processor/ProcessorInterface.php |
| 191 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Command/StringGet.php |
| 192 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Command/Command.php |
| 193 | /srv/www/subdomain-sangiare/xe/vendor/predis/predis/src/Command/CommandInterface.php |
| 194 | /srv/www/subdomain-sangiare/xe/app/models/Products.php |
| 195 | /srv/www/subdomain-sangiare/xe/app/models/Adapter/Mysql.php |
| 196 | /srv/www/subdomain-sangiare/xe/app/models/Traits/ElasticTrait.php |
| 197 | /srv/www/subdomain-sangiare/xe/app/models/Traits/MysqlTrait.php |
| 198 | /srv/www/subdomain-sangiare/xe/app/models/Adapter/Elastic.php |
| 199 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ClientBuilder.php |
| 200 | /srv/www/subdomain-sangiare/xe/vendor/psr/log/Psr/Log/NullLogger.php |
| 201 | /srv/www/subdomain-sangiare/xe/vendor/psr/log/Psr/Log/AbstractLogger.php |
| 202 | /srv/www/subdomain-sangiare/xe/vendor/psr/log/Psr/Log/LoggerInterface.php |
| 203 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Client/CurlHandler.php |
| 204 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Client/CurlFactory.php |
| 205 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Client/CurlMultiHandler.php |
| 206 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Client/Middleware.php |
| 207 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/SmartSerializer.php |
| 208 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/SerializerInterface.php |
| 209 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/ConnectionFactory.php |
| 210 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/ConnectionFactoryInterface.php |
| 211 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/Selectors/RoundRobinSelector.php |
| 212 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/Selectors/SelectorInterface.php |
| 213 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php |
| 214 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/ConnectionInterface.php |
| 215 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/StaticNoPingConnectionPool.php |
| 216 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/AbstractConnectionPool.php |
| 217 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/ConnectionPoolInterface.php |
| 218 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php |
| 219 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Client.php |
| 220 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/IndicesNamespace.php |
| 221 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/AbstractNamespace.php |
| 222 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/ClusterNamespace.php |
| 223 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/NodesNamespace.php |
| 224 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/SnapshotNamespace.php |
| 225 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/CatNamespace.php |
| 226 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/IngestNamespace.php |
| 227 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/TasksNamespace.php |
| 228 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/Indices/Exists.php |
| 229 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/AbstractEndpoint.php |
| 230 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/BooleanRequestWrapper.php |
| 231 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Core.php |
| 232 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/CompletedFutureArray.php |
| 233 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/CompletedFutureValue.php |
| 234 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/FutureInterface.php |
| 235 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/PromiseInterface.php |
| 236 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/PromisorInterface.php |
| 237 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/FutureArrayInterface.php |
| 238 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Exception/ConnectException.php |
| 239 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Exception/RingException.php |
| 240 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/FutureArray.php |
| 241 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/MagicFutureTrait.php |
| 242 | /srv/www/subdomain-sangiare/xe/vendor/guzzlehttp/ringphp/src/Future/BaseFutureTrait.php |
| 243 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/FulfilledPromise.php |
| 244 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/ExtendedPromiseInterface.php |
| 245 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/CancellablePromiseInterface.php |
| 246 | /srv/www/subdomain-sangiare/xe/vendor/psr/log/Psr/Log/LogLevel.php |
| 247 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/MaxRetriesException.php |
| 248 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/TransportException.php |
| 249 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/ElasticsearchException.php |
| 250 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/Curl/CouldNotConnectToHost.php |
| 251 | /srv/www/subdomain-sangiare/xe/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/NoNodesAvailableException.php |
| 252 | /srv/www/subdomain-sangiare/xe/vendor/react/promise/src/RejectedPromise.php |
| Memory | |
|---|---|
| Usage | 4194304 |