Phalcon Framework 1.3.4

Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost: Failed to connect to localhost port 9200: Connection refused

/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/AbstractConnection.php (323)
#0Elasticsearch\Connections\AbstractConnection->throwCurlException(7, Failed to connect to localhost port 9200: Connection refused)
<?php
/**
 * User: zach
 * Date: 6/17/13
 * Time: 10:39 AM
 */
 
namespace Elasticsearch\Connections;
 
 
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\Authentication401Exception;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\TransportException;
use \Guzzle\Http\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Exception\ServerErrorResponseException;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Psr\Log\LoggerInterface;
 
class GuzzleConnection extends AbstractConnection implements ConnectionInterface
{
    /** @var  Client */
    private $guzzle;
 
    private $lastRequest = array();
 
 
    /**
     * @param array                    $hostDetails
     * @param array                    $connectionParams Array of connection parameters
     * @param \Psr\Log\LoggerInterface $log              logger object
     * @param \Psr\Log\LoggerInterface $trace            logger object (for curl traces)
     *
     * @throws \Elasticsearch\Common\Exceptions\InvalidArgumentException
     * @return \Elasticsearch\Connections\GuzzleConnection
     */
    public function __construct($hostDetails, $connectionParams, LoggerInterface $log, LoggerInterface $trace)
    {
        if (isset($connectionParams['guzzleClient']) !== true) {
            $log->critical('guzzleClient must be set in connectionParams');
            throw new InvalidArgumentException('guzzleClient must be set in connectionParams');
        }
 
        if (isset($hostDetails['port']) !== true) {
            $hostDetails['port'] = 9200;
        }
 
        if (isset($hostDetails['scheme']) !== true) {
            $hostDetails['scheme'] = 'http';
        }
 
        $this->guzzle = $connectionParams['guzzleClient'];
        unset($connectionParams['guzzleClient']);
 
        if (isset($connectionParams['connectionParams'])) {
            $this->connectionParams += $connectionParams['connectionParams'];
        }
 
        parent::__construct($hostDetails, $connectionParams, $log, $trace);
 
    }
 
    /**
     * Returns the transport schema
     *
     * @return string
     */
    public function getTransportSchema()
    {
        return $this->transportSchema;
    }
 
 
    /**
     * Perform an HTTP request on the cluster
     *
     * @param string      $method HTTP method to use for request
     * @param string      $uri    HTTP URI to use for request
     * @param null|string $params Optional URI parameters
     * @param null|string $body   Optional request body
     * @param array       $options
     *
     * @return array
     */
    public function performRequest($method, $uri, $params = null, $body = null, $options = array())
    {
 
        $uri = $this->getURI($uri, $params);
 
        $options += $this->connectionParams;
        $request = $this->buildGuzzleRequest($method, $uri, $body, $options);
        $response = $this->sendRequest($request, $body);
 
        return array(
            'status' => $response->getStatusCode(),
            'text'   => $response->getBody(true),
            'info'   => $response->getInfo(),
        );
 
    }
 
 
    /**
     * @return array
     */
    public function getLastRequestInfo()
    {
        return $this->lastRequest;
    }
 
 
    /**
     * @param string $uri
     * @param array $params
     *
     * @return string
     */
    private function getURI($uri, $params)
    {
        $uri = $this->host . $uri;
 
        if (isset($params) === true) {
            $uri .= '?' . http_build_query($params);
        }
 
        return $uri;
    }
 
 
    /**
     * @param string $method
     * @param string $uri
     * @param string $body
     * @param array $options
     *
     * @return Request
     */
    private function buildGuzzleRequest($method, $uri, $body, $options = array())
    {
        if ($method === 'GET' && isset($body) === true) {
            $method = 'POST';
        }
 
        if (isset($body) === true) {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => $body,
                'options' => $options,
                'method'  => $method
            ));
 
            /** @var EntityEnclosingRequest $request */
            $request = $this->guzzle->$method($uri, array('content-type' => 'application/json'), $body, $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
 
        } else {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => null,
                'options' => $options,
                'method'  => $method
            ));
            $request = $this->guzzle->$method($uri, array(), array(), $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
        }
 
        return $request;
    }
 
 
    /**
     * @param Request $request
     *
     * @param string  $body
     *
     * @throws \Elasticsearch\Common\Exceptions\TransportException
     * @return \Guzzle\Http\Message\Response
     */
    private function sendRequest(Request $request, $body)
    {
        try {
            $request->send();
        } catch (ServerErrorResponseException $exception) {
            $this->process5xxError($request, $exception, $body);
 
        } catch (ClientErrorResponseException $exception) {
            $this->process4xxError($request, $exception, $body);
 
        } catch (CurlException $exception) {
           $this->processCurlError($exception);
 
        } catch (\Exception $exception) {
            $error = 'Unexpected error: ' . $exception->getMessage();
            $this->log->critical($error);
            throw new TransportException($error);
        }
 
        $this->processSuccessfulRequest($request, $body);
        return $request->getResponse();
    }
 
 
    /**
     * @param Request                      $request
     * @param ServerErrorResponseException $exception
     * @param string                       $body
     *
     * @throws \Elasticsearch\Common\Exceptions\RoutingMissingException
     * @throws \Elasticsearch\Common\Exceptions\NoShardAvailableException
     * @throws \Guzzle\Http\Exception\ServerErrorResponseException
     * @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException
     */
    private function process5xxError(Request $request, ServerErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
        $this->log->error($exceptionText);
 
        if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
            throw new RoutingMissingException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/',$responseBody) === 1) {
            throw new NoDocumentsToGetException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
            throw new NoShardAvailableException($responseBody, $statusCode, $exception);
        } else {
            throw new \Elasticsearch\Common\Exceptions\ServerErrorResponseException($responseBody, $statusCode, $exception);
        }
 
 
    }
 
 
    private function process4xxError(Request $request, ClientErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
 
        if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
            throw new AlreadyExpiredException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 401) {
            throw new Authentication401Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 403) {
            throw new Forbidden403Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 404) {
            throw new Missing404Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 409) {
            throw new Conflict409Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
            throw new ScriptLangNotSupportedException($responseBody. $statusCode);
        } elseif ($statusCode === 400) {
            throw new BadRequest400Exception($responseBody, $statusCode, $exception);
        }
    }
 
 
    /**
     * @param Request    $request
     * @param \Exception $exception
     * @param string     $body
     */
    private function logErrorDueToFailure(Request $request, \Exception $exception, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $info         = $response->getInfo();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $info;
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestFail(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $response->getInfo('total_time'),
            $response->getStatusCode(),
            $responseBody,
            $exception->getMessage()
        );
    }
 
 
    /**
     * @param CurlException $exception\
     */
    private function processCurlError(CurlException $exception)
    {
        $error = 'Curl error: ' . $exception->getMessage();
        $this->log->error($error);
        $this->throwCurlException($exception->getErrorNo(), $exception->getError());
    }
 
    /**
     * @param Request $request
     * @param string  $body
     */
    private function processSuccessfulRequest(Request $request, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $response->getInfo();
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestSuccess(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $status,
            $responseBody,
            $response->getInfo('total_time')
        );
    }
}
#1Elasticsearch\Connections\GuzzleConnection->processCurlError(Object(Guzzle\Http\Exception\CurlException))
<?php
/**
 * User: zach
 * Date: 6/17/13
 * Time: 10:39 AM
 */
 
namespace Elasticsearch\Connections;
 
 
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\Authentication401Exception;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\TransportException;
use \Guzzle\Http\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Exception\ServerErrorResponseException;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Psr\Log\LoggerInterface;
 
class GuzzleConnection extends AbstractConnection implements ConnectionInterface
{
    /** @var  Client */
    private $guzzle;
 
    private $lastRequest = array();
 
 
    /**
     * @param array                    $hostDetails
     * @param array                    $connectionParams Array of connection parameters
     * @param \Psr\Log\LoggerInterface $log              logger object
     * @param \Psr\Log\LoggerInterface $trace            logger object (for curl traces)
     *
     * @throws \Elasticsearch\Common\Exceptions\InvalidArgumentException
     * @return \Elasticsearch\Connections\GuzzleConnection
     */
    public function __construct($hostDetails, $connectionParams, LoggerInterface $log, LoggerInterface $trace)
    {
        if (isset($connectionParams['guzzleClient']) !== true) {
            $log->critical('guzzleClient must be set in connectionParams');
            throw new InvalidArgumentException('guzzleClient must be set in connectionParams');
        }
 
        if (isset($hostDetails['port']) !== true) {
            $hostDetails['port'] = 9200;
        }
 
        if (isset($hostDetails['scheme']) !== true) {
            $hostDetails['scheme'] = 'http';
        }
 
        $this->guzzle = $connectionParams['guzzleClient'];
        unset($connectionParams['guzzleClient']);
 
        if (isset($connectionParams['connectionParams'])) {
            $this->connectionParams += $connectionParams['connectionParams'];
        }
 
        parent::__construct($hostDetails, $connectionParams, $log, $trace);
 
    }
 
    /**
     * Returns the transport schema
     *
     * @return string
     */
    public function getTransportSchema()
    {
        return $this->transportSchema;
    }
 
 
    /**
     * Perform an HTTP request on the cluster
     *
     * @param string      $method HTTP method to use for request
     * @param string      $uri    HTTP URI to use for request
     * @param null|string $params Optional URI parameters
     * @param null|string $body   Optional request body
     * @param array       $options
     *
     * @return array
     */
    public function performRequest($method, $uri, $params = null, $body = null, $options = array())
    {
 
        $uri = $this->getURI($uri, $params);
 
        $options += $this->connectionParams;
        $request = $this->buildGuzzleRequest($method, $uri, $body, $options);
        $response = $this->sendRequest($request, $body);
 
        return array(
            'status' => $response->getStatusCode(),
            'text'   => $response->getBody(true),
            'info'   => $response->getInfo(),
        );
 
    }
 
 
    /**
     * @return array
     */
    public function getLastRequestInfo()
    {
        return $this->lastRequest;
    }
 
 
    /**
     * @param string $uri
     * @param array $params
     *
     * @return string
     */
    private function getURI($uri, $params)
    {
        $uri = $this->host . $uri;
 
        if (isset($params) === true) {
            $uri .= '?' . http_build_query($params);
        }
 
        return $uri;
    }
 
 
    /**
     * @param string $method
     * @param string $uri
     * @param string $body
     * @param array $options
     *
     * @return Request
     */
    private function buildGuzzleRequest($method, $uri, $body, $options = array())
    {
        if ($method === 'GET' && isset($body) === true) {
            $method = 'POST';
        }
 
        if (isset($body) === true) {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => $body,
                'options' => $options,
                'method'  => $method
            ));
 
            /** @var EntityEnclosingRequest $request */
            $request = $this->guzzle->$method($uri, array('content-type' => 'application/json'), $body, $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
 
        } else {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => null,
                'options' => $options,
                'method'  => $method
            ));
            $request = $this->guzzle->$method($uri, array(), array(), $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
        }
 
        return $request;
    }
 
 
    /**
     * @param Request $request
     *
     * @param string  $body
     *
     * @throws \Elasticsearch\Common\Exceptions\TransportException
     * @return \Guzzle\Http\Message\Response
     */
    private function sendRequest(Request $request, $body)
    {
        try {
            $request->send();
        } catch (ServerErrorResponseException $exception) {
            $this->process5xxError($request, $exception, $body);
 
        } catch (ClientErrorResponseException $exception) {
            $this->process4xxError($request, $exception, $body);
 
        } catch (CurlException $exception) {
           $this->processCurlError($exception);
 
        } catch (\Exception $exception) {
            $error = 'Unexpected error: ' . $exception->getMessage();
            $this->log->critical($error);
            throw new TransportException($error);
        }
 
        $this->processSuccessfulRequest($request, $body);
        return $request->getResponse();
    }
 
 
    /**
     * @param Request                      $request
     * @param ServerErrorResponseException $exception
     * @param string                       $body
     *
     * @throws \Elasticsearch\Common\Exceptions\RoutingMissingException
     * @throws \Elasticsearch\Common\Exceptions\NoShardAvailableException
     * @throws \Guzzle\Http\Exception\ServerErrorResponseException
     * @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException
     */
    private function process5xxError(Request $request, ServerErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
        $this->log->error($exceptionText);
 
        if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
            throw new RoutingMissingException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/',$responseBody) === 1) {
            throw new NoDocumentsToGetException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
            throw new NoShardAvailableException($responseBody, $statusCode, $exception);
        } else {
            throw new \Elasticsearch\Common\Exceptions\ServerErrorResponseException($responseBody, $statusCode, $exception);
        }
 
 
    }
 
 
    private function process4xxError(Request $request, ClientErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
 
        if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
            throw new AlreadyExpiredException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 401) {
            throw new Authentication401Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 403) {
            throw new Forbidden403Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 404) {
            throw new Missing404Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 409) {
            throw new Conflict409Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
            throw new ScriptLangNotSupportedException($responseBody. $statusCode);
        } elseif ($statusCode === 400) {
            throw new BadRequest400Exception($responseBody, $statusCode, $exception);
        }
    }
 
 
    /**
     * @param Request    $request
     * @param \Exception $exception
     * @param string     $body
     */
    private function logErrorDueToFailure(Request $request, \Exception $exception, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $info         = $response->getInfo();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $info;
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestFail(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $response->getInfo('total_time'),
            $response->getStatusCode(),
            $responseBody,
            $exception->getMessage()
        );
    }
 
 
    /**
     * @param CurlException $exception\
     */
    private function processCurlError(CurlException $exception)
    {
        $error = 'Curl error: ' . $exception->getMessage();
        $this->log->error($error);
        $this->throwCurlException($exception->getErrorNo(), $exception->getError());
    }
 
    /**
     * @param Request $request
     * @param string  $body
     */
    private function processSuccessfulRequest(Request $request, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $response->getInfo();
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestSuccess(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $status,
            $responseBody,
            $response->getInfo('total_time')
        );
    }
}
#2Elasticsearch\Connections\GuzzleConnection->sendRequest(Object(Guzzle\Http\Message\EntityEnclosingRequest), {"query":{"filtered":{"filter":{"bool":{"must":[{"term":{"active":"Y"}}]}}}},"from":0,"size":10,"sort":[{"logo":{"order":"desc"}},{"business_name.raw":{"order":"asc"}}]})
<?php
/**
 * User: zach
 * Date: 6/17/13
 * Time: 10:39 AM
 */
 
namespace Elasticsearch\Connections;
 
 
use Elasticsearch\Common\Exceptions\AlreadyExpiredException;
use Elasticsearch\Common\Exceptions\Authentication401Exception;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Conflict409Exception;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Elasticsearch\Common\Exceptions\NoShardAvailableException;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\ScriptLangNotSupportedException;
use Elasticsearch\Common\Exceptions\TransportException;
use \Guzzle\Http\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Exception\ServerErrorResponseException;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Psr\Log\LoggerInterface;
 
class GuzzleConnection extends AbstractConnection implements ConnectionInterface
{
    /** @var  Client */
    private $guzzle;
 
    private $lastRequest = array();
 
 
    /**
     * @param array                    $hostDetails
     * @param array                    $connectionParams Array of connection parameters
     * @param \Psr\Log\LoggerInterface $log              logger object
     * @param \Psr\Log\LoggerInterface $trace            logger object (for curl traces)
     *
     * @throws \Elasticsearch\Common\Exceptions\InvalidArgumentException
     * @return \Elasticsearch\Connections\GuzzleConnection
     */
    public function __construct($hostDetails, $connectionParams, LoggerInterface $log, LoggerInterface $trace)
    {
        if (isset($connectionParams['guzzleClient']) !== true) {
            $log->critical('guzzleClient must be set in connectionParams');
            throw new InvalidArgumentException('guzzleClient must be set in connectionParams');
        }
 
        if (isset($hostDetails['port']) !== true) {
            $hostDetails['port'] = 9200;
        }
 
        if (isset($hostDetails['scheme']) !== true) {
            $hostDetails['scheme'] = 'http';
        }
 
        $this->guzzle = $connectionParams['guzzleClient'];
        unset($connectionParams['guzzleClient']);
 
        if (isset($connectionParams['connectionParams'])) {
            $this->connectionParams += $connectionParams['connectionParams'];
        }
 
        parent::__construct($hostDetails, $connectionParams, $log, $trace);
 
    }
 
    /**
     * Returns the transport schema
     *
     * @return string
     */
    public function getTransportSchema()
    {
        return $this->transportSchema;
    }
 
 
    /**
     * Perform an HTTP request on the cluster
     *
     * @param string      $method HTTP method to use for request
     * @param string      $uri    HTTP URI to use for request
     * @param null|string $params Optional URI parameters
     * @param null|string $body   Optional request body
     * @param array       $options
     *
     * @return array
     */
    public function performRequest($method, $uri, $params = null, $body = null, $options = array())
    {
 
        $uri = $this->getURI($uri, $params);
 
        $options += $this->connectionParams;
        $request = $this->buildGuzzleRequest($method, $uri, $body, $options);
        $response = $this->sendRequest($request, $body);
 
        return array(
            'status' => $response->getStatusCode(),
            'text'   => $response->getBody(true),
            'info'   => $response->getInfo(),
        );
 
    }
 
 
    /**
     * @return array
     */
    public function getLastRequestInfo()
    {
        return $this->lastRequest;
    }
 
 
    /**
     * @param string $uri
     * @param array $params
     *
     * @return string
     */
    private function getURI($uri, $params)
    {
        $uri = $this->host . $uri;
 
        if (isset($params) === true) {
            $uri .= '?' . http_build_query($params);
        }
 
        return $uri;
    }
 
 
    /**
     * @param string $method
     * @param string $uri
     * @param string $body
     * @param array $options
     *
     * @return Request
     */
    private function buildGuzzleRequest($method, $uri, $body, $options = array())
    {
        if ($method === 'GET' && isset($body) === true) {
            $method = 'POST';
        }
 
        if (isset($body) === true) {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => $body,
                'options' => $options,
                'method'  => $method
            ));
 
            /** @var EntityEnclosingRequest $request */
            $request = $this->guzzle->$method($uri, array('content-type' => 'application/json'), $body, $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
 
        } else {
            $this->lastRequest = array( 'request' => array(
                'uri'     => $uri,
                'body'    => null,
                'options' => $options,
                'method'  => $method
            ));
            $request = $this->guzzle->$method($uri, array(), array(), $options);
            if (isset($options['auth'])) {
                $request->setAuth($options['auth'][0],$options['auth'][1],$options['auth'][2]);
            }
        }
 
        return $request;
    }
 
 
    /**
     * @param Request $request
     *
     * @param string  $body
     *
     * @throws \Elasticsearch\Common\Exceptions\TransportException
     * @return \Guzzle\Http\Message\Response
     */
    private function sendRequest(Request $request, $body)
    {
        try {
            $request->send();
        } catch (ServerErrorResponseException $exception) {
            $this->process5xxError($request, $exception, $body);
 
        } catch (ClientErrorResponseException $exception) {
            $this->process4xxError($request, $exception, $body);
 
        } catch (CurlException $exception) {
           $this->processCurlError($exception);
 
        } catch (\Exception $exception) {
            $error = 'Unexpected error: ' . $exception->getMessage();
            $this->log->critical($error);
            throw new TransportException($error);
        }
 
        $this->processSuccessfulRequest($request, $body);
        return $request->getResponse();
    }
 
 
    /**
     * @param Request                      $request
     * @param ServerErrorResponseException $exception
     * @param string                       $body
     *
     * @throws \Elasticsearch\Common\Exceptions\RoutingMissingException
     * @throws \Elasticsearch\Common\Exceptions\NoShardAvailableException
     * @throws \Guzzle\Http\Exception\ServerErrorResponseException
     * @throws \Elasticsearch\Common\Exceptions\NoDocumentsToGetException
     */
    private function process5xxError(Request $request, ServerErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
        $this->log->error($exceptionText);
 
        if ($statusCode === 500 && strpos($responseBody, "RoutingMissingException") !== false) {
            throw new RoutingMissingException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && preg_match('/ActionRequestValidationException.+ no documents to get/',$responseBody) === 1) {
            throw new NoDocumentsToGetException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
            throw new NoShardAvailableException($responseBody, $statusCode, $exception);
        } else {
            throw new \Elasticsearch\Common\Exceptions\ServerErrorResponseException($responseBody, $statusCode, $exception);
        }
 
 
    }
 
 
    private function process4xxError(Request $request, ClientErrorResponseException $exception, $body)
    {
        $this->logErrorDueToFailure($request, $exception, $body);
 
        $statusCode    = $request->getResponse()->getStatusCode();
        $exceptionText = $exception->getMessage();
        $responseBody  = $request->getResponse()->getBody(true);
 
        $exceptionText = "$statusCode Server Exception: $exceptionText\n$responseBody";
 
        if ($statusCode === 400 && strpos($responseBody, "AlreadyExpiredException") !== false) {
            throw new AlreadyExpiredException($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 401) {
            throw new Authentication401Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 403) {
            throw new Forbidden403Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 404) {
            throw new Missing404Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 409) {
            throw new Conflict409Exception($responseBody, $statusCode, $exception);
        } elseif ($statusCode === 400 && strpos($responseBody, 'script_lang not supported') !== false) {
            throw new ScriptLangNotSupportedException($responseBody. $statusCode);
        } elseif ($statusCode === 400) {
            throw new BadRequest400Exception($responseBody, $statusCode, $exception);
        }
    }
 
 
    /**
     * @param Request    $request
     * @param \Exception $exception
     * @param string     $body
     */
    private function logErrorDueToFailure(Request $request, \Exception $exception, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $info         = $response->getInfo();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $info;
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestFail(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $response->getInfo('total_time'),
            $response->getStatusCode(),
            $responseBody,
            $exception->getMessage()
        );
    }
 
 
    /**
     * @param CurlException $exception\
     */
    private function processCurlError(CurlException $exception)
    {
        $error = 'Curl error: ' . $exception->getMessage();
        $this->log->error($error);
        $this->throwCurlException($exception->getErrorNo(), $exception->getError());
    }
 
    /**
     * @param Request $request
     * @param string  $body
     */
    private function processSuccessfulRequest(Request $request, $body)
    {
        $response     = $request->getResponse();
        $headers      = $request->getHeaders()->getAll();
        $responseBody = $response->getBody(true);
        $status       = $response->getStatusCode();
 
        $this->lastRequest['response']['body']    = $responseBody;
        $this->lastRequest['response']['info']    = $response->getInfo();
        $this->lastRequest['response']['status']  = $status;
 
        $this->logRequestSuccess(
            $request->getMethod(),
            $request->getUrl(),
            $body,
            $headers,
            $status,
            $responseBody,
            $response->getInfo('total_time')
        );
    }
}
#3Elasticsearch\Connections\GuzzleConnection->performRequest(GET, /findmyrice2/el_company/_search, Array(), {"query":{"filtered":{"filter":{"bool":{"must":[{"term":{"active":"Y"}}]}}}},"from":0,"size":10,"sort":[{"logo":{"order":"desc"}},{"business_name.raw":{"order":"asc"}}]})
<?php
/**
 * User: zach
 * Date: 5/1/13
 * Time: 9:51 PM
 */
 
namespace Elasticsearch;
 
use Elasticsearch\Common\Exceptions\TransportException;
use Elasticsearch\Common\Exceptions;
use Elasticsearch\ConnectionPool\AbstractConnectionPool;
use Elasticsearch\Connections\AbstractConnection;
use Elasticsearch\Connections\ConnectionInterface;
use Elasticsearch\Serializers\SerializerInterface;
use Psr\Log\LoggerInterface;
 
/**
 * Class Transport
 *
 * @category Elasticsearch
 * @package  Elasticsearch
 * @author   Zachary Tong <zachary.tong@elasticsearch.com>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
 * @link     http://elasticsearch.org
 */
class Transport
{
    /**
     * @var \Pimple\Container
     */
    private $params;
 
    /**
     * @var AbstractConnectionPool
     */
    private $connectionPool;
 
    /**
     * @var array Array of seed nodes provided by the user
     */
    private $seeds = array();
 
    /**
     * @var SerializerInterface
     */
    private $serializer;
 
    /**
     * @var LoggerInterface
     */
    private $log;
 
    /** @var  int */
    private $retryAttempts;
 
    /** @var  AbstractConnection */
    private $lastConnection;
 
 
    /**
     * Transport class is responsible for dispatching requests to the
     * underlying cluster connections
     *
     * @param array                    $hosts  Array of hosts in cluster
     * @param \Pimple\Container        $params DIC containing dependencies
     * @param \Psr\Log\LoggerInterface $log    Monolog logger object
     *
     * @throws Common\Exceptions\InvalidArgumentException
     */
    public function __construct($hosts, $params, LoggerInterface $log)
    {
        $this->log = $log;
 
        if (is_array($hosts) !== true) {
            $this->log->critical('Hosts parameter must be an array');
            throw new Exceptions\InvalidArgumentException('Hosts parameter must be an array');
        }
 
        $this->params     = $params;
        $this->serializer = $params['serializer'];
 
        $this->seeds = $hosts;
        $this->setConnections($hosts);
 
        if (isset($this->params['retries']) !== true || $this->params['retries'] === null) {
            $this->params['retries'] = count($hosts) -1;
        }
 
        if ($params['sniffOnStart'] === true) {
            $this->log->notice('Sniff on Start.');
            $this->connectionPool->scheduleCheck();
        }
 
    }
 
 
    /**
     * Creates Connection objects and instantiates a ConnectionPool object
     *
     * @param array $hosts Assoc array of hosts to add to connection pool
     *
     * @return void
     */
    public function setConnections($hosts)
    {
        // Merge in the initial seed list (union not array_merge).
        $hosts = $hosts + $this->seeds;
 
        $connections = $this->hostsToConnections($hosts);
 
        $this->connectionPool  = $this->params['connectionPool']($connections);
 
    }
 
 
    /**
     * 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
     *
     * @throws Common\Exceptions\NoNodesAvailableException|\Exception
     * @internal param null $maxRetries Optional number of retries
     *
     * @return array
     */
    public function performRequest($method, $uri, $params = null, $body = null)
    {
        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;
 
        try {
            if (isset($body) === true) {
                $body = $this->serializer->serialize($body);
            }
 
            $response = $connection->performRequest(
                $method,
                $uri,
                $params,
                $body
            );
 
            $connection->markAlive();
            $this->retryAttempts = 0;
 
            $data = $this->serializer->deserialize($response['text'], $response['info']);
 
            return array(
                'status' => $response['status'],
                'data'   => $data,
                'info'   => $response['info'],
            );
 
        } catch (Exceptions\Curl\OperationTimeoutException $exception) {
            $this->connectionPool->scheduleCheck();
            $caughtException = $exception;
 
        } catch (Exceptions\ClientErrorResponseException $exception) {
            throw $exception;   //We need 4xx errors to go straight to the user, no retries
 
        } catch (Exceptions\ServerErrorResponseException $exception) {
            throw $exception;   //We need 5xx errors to go straight to the user, no retries
 
        } catch (TransportException $exception) {
            $connection->markDead();
            $this->connectionPool->scheduleCheck();
            $caughtException = $exception;
        }
 
        $shouldRetry = $this->shouldRetry($method, $uri, $params, $body);
        if ($shouldRetry === true) {
            return $this->performRequest($method, $uri, $params, $body);
        }
 
        if ($caughtException !== null) {
            throw $caughtException;
        }
 
        return $response;
    }
 
 
    /**
     * @param $method
     * @param $uri
     * @param $params
     * @param $body
     *
     * @return bool
     */
    public function shouldRetry($method, $uri, $params, $body)
    {
        if ($this->retryAttempts < $this->params['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 AbstractConnection
     */
    public function getLastConnection()
    {
        return $this->lastConnection;
    }
 
 
    /**
     * Convert host arrays into connections
     *
     * @param array $hosts Assoc array of host values
     *
     * @return AbstractConnection[]
     */
    private function hostsToConnections($hosts)
    {
        $connections = array();
        foreach ($hosts as $host) {
            $connections[] = $this->params['connection'](
                $host
            );
        }
 
        return $connections;
 
    }
 
 
}
#4Elasticsearch\Transport->performRequest(GET, /findmyrice2/el_company/_search, Array(), Array([query] => Array([filtered] => Array([filter] => Array())), [from] => 0, [size] => 10, [sort] => Array([0] => Array([logo] => Array()), [1] => Array([business_name.raw] => Array()))))
<?php
/**
 * User: zach
 * Date: 5/31/13
 * Time: 9:49 AM
 */
 
namespace Elasticsearch\Endpoints;
 
 
use Elasticsearch\Common\Exceptions\UnexpectedValueException;
use Elasticsearch\Transport;
 
/**
 * Class AbstractEndpoint
 * @package Elasticsearch\Endpoints
 */
abstract class AbstractEndpoint
{
    /** @var array  */
    protected $params = array();
 
    /** @var  string */
    protected $index = null;
 
    /** @var  string */
    protected $type = null;
 
    /** @var  string|int */
    protected $id = null;
 
    /** @var  string */
    protected $method = null;
 
    /** @var  array */
    protected $body = null;
 
    /** @var \Elasticsearch\Transport  */
    private $transport = null;
 
    /** @var array  */
    private $ignore = null;
 
 
    /**
     * @return string[]
     */
    abstract protected function getParamWhitelist();
 
 
    /**
     * @return string
     */
    abstract protected function getURI();
 
 
    /**
     * @return string
     */
    abstract protected function getMethod();
 
    /**
     * @param Transport $transport
     */
    public function __construct($transport)
    {
        $this->transport = $transport;
    }
 
 
    /**
     *
     * @throws \Exception
     * @return array
     */
    public function performRequest()
    {
        $result = array();
 
        try {
            $result =  $this->transport->performRequest(
                $this->getMethod(),
                $this->getURI(),
                $this->params,
                $this->getBody()
            );
        } catch (\Exception $exception) {
            $code = $exception->getCode();
            if ($this->ignore === null) {
                throw $exception;
            } else if (array_search($code, $this->ignore) === false) {
                throw $exception;
            } else {
                //TODO return null or dedicated object here instead?
                return array('data' => $exception->getMessage());
            }
        }
 
        return $result;
 
    }
 
    /**
     * Set the parameters for this endpoint
     *
     * @param string[] $params Array of parameters
     * @return $this
     */
    public function setParams($params)
    {
        if (is_object($params) === true) {
            $params = (array)$params;
        }
 
        $this->checkUserParams($params);
        $params = $this->convertCustom($params);
        $this->params = $this->convertArraysToStrings($params);
        $this->extractIgnore();
        return $this;
    }
 
 
    /**
     * @param string $index
     *
     * @return $this
     */
    public function setIndex($index)
    {
        if ($index === null) {
            return $this;
        }
 
        if (is_array($index) === true) {
            $index = array_map('trim', $index);
            $index = implode(",", $index);
        }
 
        $this->index = urlencode($index);
        return $this;
    }
 
 
    /**
     * @param string $type
     *
     * @return $this
     */
    public function setType($type)
    {
        if ($type === null) {
            return $this;
        }
 
        if (is_array($type) === true) {
            $type = array_map('trim', $type);
            $type = implode(",", $type);
        }
 
        $this->type = urlencode($type);
        return $this;
    }
 
 
    /**
     * @param int|string $docID
     *
     * @return $this
     */
    public function setID($docID)
    {
        if ($docID === null) {
            return $this;
        }
 
        $this->id = urlencode($docID);
        return $this;
    }
 
 
    /**
     * @return array
     */
    protected function getBody()
    {
        return $this->body;
    }
 
 
    /**
     * @param string $endpoint
     *
     * @return string
     */
    protected function getOptionalURI($endpoint)
    {
        $uri = array();
        $uri[] = $this->getOptionalIndex();
        $uri[] = $this->getOptionalType();
        $uri[] = $endpoint;
        $uri =  array_filter($uri);
 
       return '/' . implode('/', $uri);
    }
 
 
    /**
     * @return string
     */
    private function getOptionalIndex()
    {
        if (isset($this->index) === true){
            return $this->index;
        } else {
            return '_all';
        }
    }
 
 
    /**
     * @return string
     */
    private function getOptionalType()
    {
        if (isset($this->type) === true){
            return $this->type;
        } else {
            return '';
        }
    }
 
 
 
    /**
     * @param array $params
     *
     * @throws \Elasticsearch\Common\Exceptions\UnexpectedValueException
     */
    private function checkUserParams($params)
    {
        try {
            $this->ifParamsInvalidThrowException($params);
        } catch (UnexpectedValueException $exception) {
            throw $exception;
        }
    }
 
    /**
     * Check if param is in whitelist
     *
     * @param array $params    Assoc array of parameters
     *
     * @throws \Elasticsearch\Common\Exceptions\UnexpectedValueException
     *
     */
    private function ifParamsInvalidThrowException($params)
    {
        if (isset($params) !== true) {
            return; //no params, just return.
        }
 
        $whitelist = array_merge($this->getParamWhitelist(), array('ignore', 'custom', 'curlOpts', 'filter_path'));
 
        foreach ($params as $key => $value) {
            if (array_search($key, $whitelist) === false) {
                throw new UnexpectedValueException(sprintf(
                    '"%s" is not a valid parameter. Allowed parameters are: "%s"',
                    $key,
                    implode('", "', $whitelist)
                ));
            }
        }
 
    }
 
 
    private function extractIgnore()
    {
        if (isset($this->params['ignore']) === true) {
            $this->ignore = explode(",", $this->params['ignore']);
            unset($this->params['ignore']);
        }
    }
 
    private function convertCustom($params)
    {
        if (isset($params['custom']) === true) {
            foreach ($params['custom'] as $k => $v) {
                $params[$k] = $v;
            }
            unset($params['custom']);
        }
        return $params;
    }
 
 
    private function convertArraysToStrings($params)
    {
        foreach ($params as &$param) {
            if (is_array($param) === true) {
                if ($this->isNestedArray($param) !== true){
                    $param = implode(",", $param);
                }
 
            }
        }
 
        return $params;
    }
 
    private function isNestedArray($a) {
        foreach ($a as $v) {
            if (is_array($v)) {
                return true;
            }
        }
        return false;
    }
 
}
#5Elasticsearch\Endpoints\AbstractEndpoint->performRequest()
<?php
/**
 * User: zach
 * Date: 5/1/13
 * Time: 11:41 AM
 */
 
namespace Elasticsearch;
 
use Elasticsearch\Common\DICBuilder;
use Elasticsearch\Common\EmptyLogger;
use Elasticsearch\Common\Exceptions;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\Common\Exceptions\RoutingMissingException;
use Elasticsearch\Common\Exceptions\UnexpectedValueException;
use Elasticsearch\Endpoints;
use Elasticsearch\Namespaces\CatNamespace;
use Elasticsearch\Namespaces\ClusterNamespace;
use Elasticsearch\Namespaces\IndicesNamespace;
use Elasticsearch\Namespaces\NodesNamespace;
use Elasticsearch\Namespaces\SnapshotNamespace;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;
 
/**
 * Class Client
 *
 * @category Elasticsearch
 * @package  Elasticsearch
 * @author   Zachary Tong <zachary.tong@elasticsearch.com>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
 * @link     http://elasticsearch.org
 */
class Client
{
 
    /**
     * @var Transport
     */
    public $transport;
 
    /**
     * @var \Pimple\Container
     */
    protected $params;
 
    /**
     * @var IndicesNamespace
     */
    protected $indices;
 
    /**
     * @var ClusterNamespace
     */
    protected $cluster;
 
    /**
     * @var NodesNamespace
     */
    protected $nodes;
 
    /**
     * @var SnapshotNamespace
     */
    protected $snapshot;
 
    /**
     * @var CatNamespace
     */
    protected $cat;
 
 
    protected $customNamespaces = array();
 
    /** @var  callback */
    protected $dicEndpoints;
 
 
    /**
     * Client constructor
     *
     * @param array $params Array of injectable parameters
     * @throws Common\Exceptions\RuntimeException
     */
    public function __construct($params = array())
    {
        if (!extension_loaded('curl') || !function_exists('curl_multi_exec')) {
            throw new Exceptions\RuntimeException("curl_multi_exec() function is required for the client.");
        }
 
        $this->setParams($params);
        $this->setLogging();
        $this->transport      = $this->params['transport'];
        $this->indices        = $this->params['indicesNamespace'];
        $this->cluster        = $this->params['clusterNamespace'];
        $this->nodes          = $this->params['nodesNamespace'];
        $this->snapshot       = $this->params['snapshotNamespace'];
        $this->cat            = $this->params['catNamespace'];
 
        if (isset($this->params['customNamespaces']) === true) {
            foreach ($this->params['customNamespaces'] as $name => $ns) {
                $this->customNamespaces[$name] = $this->params[$name];
            }
        }
 
 
        $this->dicEndpoints   = $this->params['endpoint'];
    }
 
 
    /**
     *
     *
     * @return array
     */
    public function info()
    {
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Info $endpoint */
        $endpoint = $endpointBuilder('Info');
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    public function ping()
    {
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Ping $endpoint */
        $endpoint = $endpointBuilder('Ping');
 
        try {
            $response = $endpoint->performRequest();
        } catch (Missing404Exception $exception) {
            return false;
        }
 
        if (isset($response['status']) === true && $response['status'] === 200) {
            return true;
        } else {
            return false;
        }
    }
 
 
    /**
     * $params['id']              = (string) The document ID (Required)
     *        ['index']           = (string) The name of the index (Required)
     *        ['type']            = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required)
     *        ['ignore_missing']  = ??
     *        ['fields']          = (list) A comma-separated list of fields to return in the response
     *        ['parent']          = (string) The ID of the parent document
     *        ['preference']      = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['realtime']        = (boolean) Specify whether to perform the operation in realtime or search mode
     *        ['refresh']         = (boolean) Refresh the shard containing the document before performing the operation
     *        ['routing']         = (string) Specific routing value
     *        ['_source']         = (list) True or false to return the _source field or not, or a list of fields to return
     *        ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field
     *        ['_source_include'] = (list) A list of fields to extract and return from the _source field
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function get($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Get $endpoint */
        $endpoint = $endpointBuilder('Get');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']             = (string) The document ID (Required)
     *        ['index']          = (string) The name of the index (Required)
     *        ['type']           = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required)
     *        ['ignore_missing'] = ??
     *        ['parent']         = (string) The ID of the parent document
     *        ['preference']     = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['realtime']       = (boolean) Specify whether to perform the operation in realtime or search mode
     *        ['refresh']        = (boolean) Refresh the shard containing the document before performing the operation
     *        ['routing']        = (string) Specific routing value
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function getSource($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Get $endpoint */
        $endpoint = $endpointBuilder('Get');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->returnOnlySource();
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']           = (string) The document ID (Required)
     *        ['index']        = (string) The name of the index (Required)
     *        ['type']         = (string) The type of the document (Required)
     *        ['consistency']  = (enum) Specific write consistency setting for the operation
     *        ['parent']       = (string) ID of parent document
     *        ['refresh']      = (boolean) Refresh the index after performing the operation
     *        ['replication']  = (enum) Specific replication type
     *        ['routing']      = (string) Specific routing value
     *        ['timeout']      = (time) Explicit operation timeout
     *        ['version_type'] = (enum) Specific version type
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function delete($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Delete $endpoint */
        $endpoint = $endpointBuilder('Delete');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     *
     * $params[''] @todo finish the rest of these params
     *        ['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 array $params
     *
     * @return array
     */
    public function deleteByQuery($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\DeleteByQuery $endpoint */
        $endpoint = $endpointBuilder('DeleteByQuery');
        $endpoint->setIndex($index)
                ->setType($type)
                ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']              = (list) A comma-separated list of indices to restrict the results
     *        ['type']               = (list) A comma-separated list of types to restrict the results
     *        ['min_score']          = (number) Include only documents with a specific `_score` value in the result
     *        ['preference']         = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['routing']            = (string) Specific routing value
     *        ['source']             = (string) The URL-encoded query definition (instead of using the request body)
     *        ['body']               = (array) A query to restrict the results (optional)
     *        ['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 count($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Count $endpoint */
        $endpoint = $endpointBuilder('Count');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['index']              = (list) A comma-separated list of indices to restrict the results
     *        ['type']               = (list) A comma-separated list of types to restrict the results
     *        ['id']                 = (string) ID of document
     *        ['ignore_unavailable'] = (boolean) Whether specified concrete indices should be ignored when unavailable (missing or closed)
     *        ['preference']         = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['routing']            = (string) Specific routing value
     *        ['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)
     *        ['body']               = (array) A query to restrict the results (optional)
     *        ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed)
     *        ['percolate_index']    = (string) The index to count percolate the document into. Defaults to index.
     *        ['expand_wildcards']   = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both.
     *        ['version']            = (number) Explicit version number for concurrency control
     *        ['version_type']       = (enum) Specific version type
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function countPercolate($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type  = $this->extractArgument($params, 'type');
        $id    = $this->extractArgument($params, 'id');
        $body  = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\CountPercolate $endpoint */
        $endpoint = $endpointBuilder('CountPercolate');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setID($id)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']        = (string) The name of the index with a registered percolator query (Required)
     *        ['type']         = (string) The document type (Required)
     *        ['prefer_local'] = (boolean) With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
     *        ['body']         = (array) The document (`doc`) to percolate against registered queries; optionally also a `query` to limit the percolation to specific registered queries
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function percolate($params)
    {
        $index = $this->extractArgument($params, 'index');
        $type  = $this->extractArgument($params, 'type');
        $id    = $this->extractArgument($params, 'id');
        $body  = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Percolate $endpoint */
        $endpoint = $endpointBuilder('Percolate');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setID($id)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']              = (string) Default index for items which don't provide one
     *        ['type']               = (string) Default document type for items which don't provide one
     *        ['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']   = (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 mpercolate($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type = $this->extractArgument($params, 'type');
        $body = $this->extractArgument($params, 'body');
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\MPercolate $endpoint */
        $endpoint = $endpointBuilder('MPercolate');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']            = (string) Default index for items which don't provide one
     *        ['type']             = (string) Default document type for items which don't provide one
     *        ['term_statistics']  = (boolean) Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['field_statistics'] = (boolean) Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['fields']           = (list) A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['offsets']          = (boolean) Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['positions']        = (boolean) Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['payloads']         = (boolean) Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['preference']       = (string) Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['routing']          = (string) Specific routing value. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['parent']           = (string) Parent id of documents. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['realtime']         = (boolean) Specifies if request is real-time as opposed to near-real-time (default: true).
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function termvector($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type  = $this->extractArgument($params, 'type');
        $id    = $this->extractArgument($params, 'id');
        $body  = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\TermVector $endpoint */
        $endpoint = $endpointBuilder('TermVector');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setID($id)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * Redirect to termvector, this is just a naming difference depending on version
     */
    public function termvectors($params = array())
    {
        return $this->termvector($params);
    }
 
 
    /**
     * $params['index']            = (string) Default index for items which don't provide one
     *        ['type']             = (string) Default document type for items which don't provide one
     *        ['ids']              = (list) A comma-separated list of documents ids. You must define ids as parameter or set \"ids\" or \"docs\" in the request body
     *        ['term_statistics']  = (boolean) Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['field_statistics'] = (boolean) Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['fields']           = (list) A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['offsets']          = (boolean) Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['positions']        = (boolean) Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"."
     *        ['payloads']         = (boolean) Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['preference']       = (string) Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['routing']          = (string) Specific routing value. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['parent']           = (string) Parent id of documents. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\".
     *        ['realtime']         = (boolean) Specifies if request is real-time as opposed to near-real-time (default: true).
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function mtermvectors($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type  = $this->extractArgument($params, 'type');
        $body  = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\MTermVectors $endpoint */
        $endpoint = $endpointBuilder('MTermVectors');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']         = (string) The document ID (Required)
     *        ['index']      = (string) The name of the index (Required)
     *        ['type']       = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required)
     *        ['parent']     = (string) The ID of the parent document
     *        ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['realtime']   = (boolean) Specify whether to perform the operation in realtime or search mode
     *        ['refresh']    = (boolean) Refresh the shard containing the document before performing the operation
     *        ['routing']    = (string) Specific routing value
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function exists($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Exists $endpoint */
        $endpoint = $endpointBuilder('Exists');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type);
        $endpoint->setParams($params);
 
        try {
            $response = $endpoint->performRequest();
        } catch (Missing404Exception $exception) {
            return false;
        } catch (RoutingMissingException $exception) {
            return false;
        }
 
 
        if ($response['status'] === 200) {
            return true;
        } else {
            return false;
        }
    }
 
 
    /**
     * $params['id']                     = (string) The document ID (Required)
     *        ['index']                  = (string) The name of the index (Required)
     *        ['type']                   = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required)
     *        ['boost_terms']            = (number) The boost factor
     *        ['max_doc_freq']           = (number) The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored
     *        ['max_query_terms']        = (number) The maximum query terms to be included in the generated query
     *        ['max_word_len']           = (number) The minimum length of the word: longer words will be ignored
     *        ['min_doc_freq']           = (number) The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored
     *        ['min_term_freq']          = (number) The term frequency as percent: terms with lower occurrence in the source document will be ignored
     *        ['min_word_len']           = (number) The minimum length of the word: shorter words will be ignored
     *        ['mlt_fields']             = (list) Specific fields to perform the query against
     *        ['percent_terms_to_match'] = (number) How many terms have to match in order to consider the document a match (default: 0.3)
     *        ['routing']                = (string) Specific routing value
     *        ['search_from']            = (number) The offset from which to return results
     *        ['search_indices']         = (list) A comma-separated list of indices to perform the query against (default: the index containing the document)
     *        ['search_query_hint']      = (string) The search query hint
     *        ['search_scroll']          = (string) A scroll search request definition
     *        ['search_size']            = (number) The number of documents to return (default: 10)
     *        ['search_source']          = (string) A specific search request definition (instead of using the request body)
     *        ['search_type']            = (string) Specific search type (eg. `dfs_then_fetch`, `count`, etc)
     *        ['search_types']           = (list) A comma-separated list of types to perform the query against (default: the same type as the document)
     *        ['stop_words']             = (list) A list of stop words to be ignored
     *        ['body']                   = (array) A specific search request definition
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function mlt($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Mlt $endpoint */
        $endpoint = $endpointBuilder('Mlt');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']           = (string) The name of the index
     *        ['type']            = (string) The type of the document
     *        ['fields']          = (list) A comma-separated list of fields to return in the response
     *        ['parent']          = (string) The ID of the parent document
     *        ['preference']      = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['realtime']        = (boolean) Specify whether to perform the operation in realtime or search mode
     *        ['refresh']         = (boolean) Refresh the shard containing the document before performing the operation
     *        ['routing']         = (string) Specific routing value
     *        ['body']            = (array) Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.
     *        ['_source']         = (list) True or false to return the _source field or not, or a list of fields to return
     *        ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field
     *        ['_source_include'] = (list) A list of fields to extract and return from the _source field
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function mget($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Mget $endpoint */
        $endpoint = $endpointBuilder('Mget');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']       = (list) A comma-separated list of index names to use as default
     *        ['type']        = (list) A comma-separated list of document types to use as default
     *        ['search_type'] = (enum) Search operation type
     *        ['body']        = (array|string) The request definitions (metadata-search request definition pairs), separated by newlines
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function msearch($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Msearch $endpoint */
        $endpoint = $endpointBuilder('Msearch');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']        = (string) The name of the index (Required)
     *        ['type']         = (string) The type of the document (Required)
     *        ['id']           = (string) Specific document ID (when the POST method is used)
     *        ['consistency']  = (enum) Explicit write consistency setting for the operation
     *        ['parent']       = (string) ID of the parent document
     *        ['percolate']    = (string) Percolator queries to execute while indexing the document
     *        ['refresh']      = (boolean) Refresh the index after performing the operation
     *        ['replication']  = (enum) Specific replication type
     *        ['routing']      = (string) Specific routing value
     *        ['timeout']      = (time) Explicit operation timeout
     *        ['timestamp']    = (time) Explicit timestamp for the document
     *        ['ttl']          = (duration) Expiration time for the document
     *        ['version']      = (number) Explicit version number for concurrency control
     *        ['version_type'] = (enum) Specific version type
     *        ['body']         = (array) The document
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function create($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Index $endpoint */
        $endpoint = $endpointBuilder('Index');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->setBody($body)
                 ->createIfAbsent();
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']       = (string) Default index for items which don't provide one
     *        ['type']        = (string) Default document type for items which don't provide one
     *        ['consistency'] = (enum) Explicit write consistency setting for the operation
     *        ['refresh']     = (boolean) Refresh the index after performing the operation
     *        ['replication'] = (enum) Explicitly set the replication type
     *        ['body']        = (string) Default document type for items which don't provide one
     *        ['fields']      = (list) Default comma-separated list of fields to return in the response for updates
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function bulk($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Bulk $endpoint */
        $endpoint = $endpointBuilder('Bulk');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']        = (string) The name of the index (Required)
     *        ['type']         = (string) The type of the document (Required)
     *        ['id']           = (string) Specific document ID (when the POST method is used)
     *        ['consistency']  = (enum) Explicit write consistency setting for the operation
     *        ['op_type']      = (enum) Explicit operation type
     *        ['parent']       = (string) ID of the parent document
     *        ['percolate']    = (string) Percolator queries to execute while indexing the document
     *        ['refresh']      = (boolean) Refresh the index after performing the operation
     *        ['replication']  = (enum) Specific replication type
     *        ['routing']      = (string) Specific routing value
     *        ['timeout']      = (time) Explicit operation timeout
     *        ['timestamp']    = (time) Explicit timestamp for the document
     *        ['ttl']          = (duration) Expiration time for the document
     *        ['version']      = (number) Explicit version number for concurrency control
     *        ['version_type'] = (enum) Specific version type
     *        ['body']         = (array) The document
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function index($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Index $endpoint */
        $endpoint = $endpointBuilder('Index');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $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
     *        ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones
     *        ['preference']     = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['routing']        = (string) Specific routing value
     *        ['source']         = (string) The URL-encoded request definition (instead of using request body)
     *        ['body']           = (array) The request definition
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function suggest($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Suggest $endpoint */
        $endpoint = $endpointBuilder('Suggest');
        $endpoint->setIndex($index)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']                       = (string) The document ID (Required)
     *        ['index']                    = (string) The name of the index (Required)
     *        ['type']                     = (string) The type of the document (Required)
     *        ['analyze_wildcard']         = (boolean) Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false)
     *        ['analyzer']                 = (string) The analyzer for the query string query
     *        ['default_operator']         = (enum) The default operator for query string query (AND or OR)
     *        ['df']                       = (string) The default field for query string query (default: _all)
     *        ['fields']                   = (list) A comma-separated list of fields to return in the response
     *        ['lenient']                  = (boolean) Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
     *        ['lowercase_expanded_terms'] = (boolean) Specify whether query terms should be lowercased
     *        ['parent']                   = (string) The ID of the parent document
     *        ['preference']               = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['q']                        = (string) Query in the Lucene query string syntax
     *        ['routing']                  = (string) Specific routing value
     *        ['source']                   = (string) The URL-encoded query definition (instead of using the request body)
     *        ['_source']                  = (list) True or false to return the _source field or not, or a list of fields to return
     *        ['_source_exclude']          = (list) A list of fields to exclude from the returned _source field
     *        ['_source_include']          = (list) A list of fields to extract and return from the _source field
     *        ['body']                     = (string) The URL-encoded query definition (instead of using the request body)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function explain($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Explain $endpoint */
        $endpoint = $endpointBuilder('Explain');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']                    = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
     *        ['type']                     = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types
     *        ['analyzer']                 = (string) The analyzer to use for the query string
     *        ['analyze_wildcard']         = (boolean) Specify whether wildcard and prefix queries should be analyzed (default: false)
     *        ['default_operator']         = (enum) The default operator for query string query (AND or OR)
     *        ['df']                       = (string) The field to use as default where no field prefix is given in the query string
     *        ['explain']                  = (boolean) Specify whether to return detailed information about score computation as part of a hit
     *        ['fields']                   = (list) A comma-separated list of fields to return as part of a hit
     *        ['from']                     = (number) Starting offset (default: 0)
     *        ['ignore_indices']           = (enum) When performed on multiple indices, allows to ignore `missing` ones
     *        ['indices_boost']            = (list) Comma-separated list of index boosts
     *        ['lenient']                  = (boolean) Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
     *        ['lowercase_expanded_terms'] = (boolean) Specify whether query terms should be lowercased
     *        ['preference']               = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['q']                        = (string) Query in the Lucene query string syntax
     *        ['routing']                  = (list) A comma-separated list of specific routing values
     *        ['scroll']                   = (duration) Specify how long a consistent view of the index should be maintained for scrolled search
     *        ['search_type']              = (enum) Search operation type
     *        ['size']                     = (number) Number of hits to return (default: 10)
     *        ['sort']                     = (list) A comma-separated list of <field>:<direction> pairs
     *        ['source']                   = (string) The URL-encoded request definition using the Query DSL (instead of using request body)
     *        ['_source']                  = (list) True or false to return the _source field or not, or a list of fields to return
     *        ['_source_exclude']          = (list) A list of fields to exclude from the returned _source field
     *        ['_source_include']          = (list) A list of fields to extract and return from the _source field
     *        ['stats']                    = (list) Specific 'tag' of the request for logging and statistical purposes
     *        ['suggest_field']            = (string) Specify which field to use for suggestions
     *        ['suggest_mode']             = (enum) Specify suggest mode
     *        ['suggest_size']             = (number) How many suggestions to return in response
     *        ['suggest_text']             = (text) The source text for which the suggestions should be returned
     *        ['timeout']                  = (time) Explicit operation timeout
     *        ['version']                  = (boolean) Specify whether to return document version as part of a hit
     *        ['body']                     = (array|string) The search definition using the Query DSL
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function search($params = array())
    {
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Search $endpoint */
        $endpoint = $endpointBuilder('Search');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['index']                    = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
     *        ['type']                     = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types
     *        ['analyzer']                 = (string) The analyzer to use for the query string
     *        ['analyze_wildcard']         = (boolean) Specify whether wildcard and prefix queries should be analyzed (default: false)
     *        ['default_operator']         = (enum) The default operator for query string query (AND or OR)
     *        ['df']                       = (string) The field to use as default where no field prefix is given in the query string
     *        ['explain']                  = (boolean) Specify whether to return detailed information about score computation as part of a hit
     *        ['fields']                   = (list) A comma-separated list of fields to return as part of a hit
     *        ['from']                     = (number) Starting offset (default: 0)
     *        ['ignore_indices']           = (enum) When performed on multiple indices, allows to ignore `missing` ones
     *        ['indices_boost']            = (list) Comma-separated list of index boosts
     *        ['lenient']                  = (boolean) Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
     *        ['lowercase_expanded_terms'] = (boolean) Specify whether query terms should be lowercased
     *        ['preference']               = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['q']                        = (string) Query in the Lucene query string syntax
     *        ['routing']                  = (list) A comma-separated list of specific routing values
     *        ['scroll']                   = (duration) Specify how long a consistent view of the index should be maintained for scrolled search
     *        ['search_type']              = (enum) Search operation type
     *        ['size']                     = (number) Number of hits to return (default: 10)
     *        ['sort']                     = (list) A comma-separated list of <field>:<direction> pairs
     *        ['source']                   = (string) The URL-encoded request definition using the Query DSL (instead of using request body)
     *        ['_source']                  = (list) True or false to return the _source field or not, or a list of fields to return
     *        ['_source_exclude']          = (list) A list of fields to exclude from the returned _source field
     *        ['_source_include']          = (list) A list of fields to extract and return from the _source field
     *        ['stats']                    = (list) Specific 'tag' of the request for logging and statistical purposes
     *        ['suggest_field']            = (string) Specify which field to use for suggestions
     *        ['suggest_mode']             = (enum) Specify suggest mode
     *        ['suggest_size']             = (number) How many suggestions to return in response
     *        ['suggest_text']             = (text) The source text for which the suggestions should be returned
     *        ['timeout']                  = (time) Explicit operation timeout
     *        ['version']                  = (boolean) Specify whether to return document version as part of a hit
     *        ['body']                     = (array|string) The search definition using the Query DSL
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function searchExists($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type = $this->extractArgument($params, 'type');
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\SearchExists $endpoint */
        $endpoint = $endpointBuilder('SearchExists');
        $endpoint->setIndex($index)
            ->setType($type)
            ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['index']              = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
     *        ['type']               = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types
     *        ['preference']         = (string) Specify the node or shard the operation should be performed on (default: random)
     *        ['routing']            = (string) Specific routing value
     *        ['local']              = (bool) Return local information, do not retrieve the state from master node (default: false)
     *        ['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 searchShards($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type = $this->extractArgument($params, 'type');
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\SearchShards $endpoint */
        $endpoint = $endpointBuilder('SearchShards');
        $endpoint->setIndex($index)
                 ->setType($type);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['index']                    = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
     *        ['type']                     = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function searchTemplate($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $type = $this->extractArgument($params, 'type');
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Search $endpoint */
        $endpoint = $endpointBuilder('SearchTemplate');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['scroll_id'] = (string) The scroll ID for scrolled search
     *        ['scroll']    = (duration) Specify how long a consistent view of the index should be maintained for scrolled search
     *        ['body']      = (string) The scroll ID for scrolled search
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function scroll($params = array())
    {
        $scrollID = $this->extractArgument($params, 'scroll_id');
 
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Scroll $endpoint */
        $endpoint = $endpointBuilder('Scroll');
        $endpoint->setScrollID($scrollID)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['scroll_id'] = (string) The scroll ID for scrolled search
     *        ['scroll']    = (duration) Specify how long a consistent view of the index should be maintained for scrolled search
     *        ['body']      = (string) The scroll ID for scrolled search
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function clearScroll($params = array())
    {
        $scrollID = $this->extractArgument($params, 'scroll_id');
 
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Scroll $endpoint */
        $endpoint = $endpointBuilder('Scroll');
        $endpoint->setScrollID($scrollID)
                 ->setBody($body)
                 ->setClearScroll(true);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']                = (string) Document ID (Required)
     *        ['index']             = (string) The name of the index (Required)
     *        ['type']              = (string) The type of the document (Required)
     *        ['consistency']       = (enum) Explicit write consistency setting for the operation
     *        ['fields']            = (list) A comma-separated list of fields to return in the response
     *        ['lang']              = (string) The script language (default: mvel)
     *        ['parent']            = (string) ID of the parent document
     *        ['percolate']         = (string) Perform percolation during the operation; use specific registered query name, attribute, or wildcard
     *        ['refresh']           = (boolean) Refresh the index after performing the operation
     *        ['replication']       = (enum) Specific replication type
     *        ['retry_on_conflict'] = (number) Specify how many times should the operation be retried when a conflict occurs (default: 0)
     *        ['routing']           = (string) Specific routing value
     *        ['script']            = () The URL-encoded script definition (instead of using request body)
     *        ['timeout']           = (time) Explicit operation timeout
     *        ['timestamp']         = (time) Explicit timestamp for the document
     *        ['ttl']               = (duration) Expiration time for the document
     *        ['version_type']      = (number) Explicit version number for concurrency control
     *        ['body']              = (array) The request definition using either `script` or partial `doc`
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function update($params)
    {
        $id = $this->extractArgument($params, 'id');
 
 
        $index = $this->extractArgument($params, 'index');
 
 
        $type = $this->extractArgument($params, 'type');
 
 
        $body = $this->extractArgument($params, 'body');
 
 
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Update $endpoint */
        $endpoint = $endpointBuilder('Update');
        $endpoint->setID($id)
                 ->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']   = (string) The script ID (Required)
     *        ['lang'] = (string) The script language (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function getScript($params)
    {
        $id = $this->extractArgument($params, 'id');
        $lang = $this->extractArgument($params, 'lang');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Script\Get $endpoint */
        $endpoint = $endpointBuilder('Script\Get');
        $endpoint->setID($id)
                 ->setLang($lang);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['id']   = (string) The script ID (Required)
     *        ['lang'] = (string) The script language (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function deleteScript($params)
    {
        $id = $this->extractArgument($params, 'id');
        $lang = $this->extractArgument($params, 'lang');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Script\Delete $endpoint */
        $endpoint = $endpointBuilder('Script\Delete');
        $endpoint->setID($id)
                 ->setLang($lang);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['id']   = (string) The script ID (Required)
     *        ['lang'] = (string) The script language (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function putScript($params)
    {
        $id   = $this->extractArgument($params, 'id');
        $lang = $this->extractArgument($params, 'lang');
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Script\Put $endpoint */
        $endpoint = $endpointBuilder('Script\Put');
        $endpoint->setID($id)
                 ->setLang($lang)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['id']   = (string) The search template ID (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function getTemplate($params)
    {
        $id = $this->extractArgument($params, 'id');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Template\Get $endpoint */
        $endpoint = $endpointBuilder('Template\Get');
        $endpoint->setID($id);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['id']   = (string) The search template ID (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function deleteTemplate($params)
    {
        $id = $this->extractArgument($params, 'id');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Template\Delete $endpoint */
        $endpoint = $endpointBuilder('Template\Delete');
        $endpoint->setID($id);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['id']   = (string) The search template ID (Required)
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function putTemplate($params)
    {
        $id   = $this->extractArgument($params, 'id');
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\Template\Put $endpoint */
        $endpoint = $endpointBuilder('Template\Put');
        $endpoint->setID($id)
                 ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
    /**
     * $params['index']              = (list) A comma-separated list of indices to restrict the results
     *        ['body']               = (array) Field json objects containing the name and optionally a range to filter out indices result, that have results outside the defined bounds
     *        ['fields']             = (list) A comma-separated list of fields for to get field statistics for (min value, max value, and more)
     *        ['level']              = (enum) Defines if field stats should be returned on a per index level or on a cluster wide level
     *        ['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 fieldStats($params = array())
    {
        $index = $this->extractArgument($params, 'index');
        $body = $this->extractArgument($params, 'body');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\FieldStats $endpoint */
        $endpoint = $endpointBuilder('FieldStats');
        $endpoint->setIndex($index)
            ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
    /**
     * $params['id']                 = (string) ID of the template to render
     *
     * @param $params array Associative array of parameters
     *
     * @return array
     */
    public function renderSearchTemplate($params = array())
    {
        $body = $this->extractArgument($params, 'body');
        $id   = $this->extractArgument($params, 'id');
 
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;
 
        /** @var \Elasticsearch\Endpoints\RenderSearchTemplate $endpoint */
        $endpoint = $endpointBuilder('RenderSearchTemplate');
        $endpoint->setBody($body)
            ->setID($id);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
 
 
 
    /**
     * Operate on the Indices Namespace of commands
     *
     * @return IndicesNamespace
     */
    public function indices()
    {
        return $this->indices;
    }
 
 
    /**
     * Operate on the Cluster namespace of commands
     *
     * @return ClusterNamespace
     */
    public function cluster()
    {
        return $this->cluster;
    }
 
 
    /**
     * Operate on the Nodes namespace of commands
     *
     * @return NodesNamespace
     */
    public function nodes()
    {
        return $this->nodes;
    }
 
 
    /**
     * Operate on the Snapshot namespace of commands
     *
     * @return SnapshotNamespace
     */
    public function snapshot()
    {
        return $this->snapshot;
    }
 
 
    /**
     * Operate on the Cat namespace of commands
     *
     * @return CatNamespace
     */
    public function cat()
    {
        return $this->cat;
    }
 
 
    /**
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws Common\Exceptions\RuntimeException
     */
    public function __call($name, $arguments)
    {
        if (isset($this->customNamespaces[$name]) === true) {
            return $this->customNamespaces[$name];
        }
        throw new Exceptions\RuntimeException("User-defined namespace '$name' could not be found.'");
    }
 
    /**
     * Sets up the DIC parameter object
     *
     * Merges user-specified parameters into the default list, then
     * builds a DIC to house all the information
     *
     * @param array $params Array of user settings
     *
     * @internal param array $hosts Array of hosts
     * @return void
     */
    private function setParams($params)
    {
 
        if (isset($params['hosts']) === true) {
            $hosts = $this->buildHostsFromSeed($params['hosts']);
            unset($params['hosts']);
        } else {
            $hosts = $this->getDefaultHost();
        }
 
        if (isset($params['dic']) !== true) {
            $dicBuilder =  new DICBuilder($hosts, $params);
        } else {
            $dicBuilder = $params['dic']($hosts, $params);
            unset($params['dic']);
        }
 
        /** @var DICBuilder $dicBuilder */
 
        $this->params = $dicBuilder->getDIC();
 
    }
 
 
    /**
     * Sets up the logging object
     * If a user-defined logger is not available, builds a default file logger
     *
     * @return void
     */
    private function setLogging()
    {
        if ($this->params['logging'] !== true) {
            $this->setEmptyLogger();
            return;
        }
 
        if ($this->params['logObject'] === null) {
           $this->setDefaultLogger();
        }
 
        if ($this->params['traceObject'] === null) {
            $this->setDefaultTracer();
        }
 
    }
 
    private function setEmptyLogger()
    {
        $this->params['logObject'] = new EmptyLogger();
        $this->params['traceObject'] = new EmptyLogger();
    }
 
    private function setDefaultLogger()
    {
        $log       = new Logger('log');
        $handler   = new StreamHandler(
            $this->params['logPath'],
            $this->params['logLevel'],
            $this->params['logBubble'],
            $this->params['logPermission']
        );
        $processor = new IntrospectionProcessor();
 
        $log->pushHandler($handler);
        $log->pushProcessor($processor);
 
        $this->params['logObject'] = $log;
    }
 
    private function setDefaultTracer()
    {
        $trace        = new Logger('trace');
        $traceHandler = new StreamHandler(
            $this->params['tracePath'],
            $this->params['traceLevel'],
            $this->params['traceBubble'],
            $this->params['tracePermission']
        );
 
        $trace->pushHandler($traceHandler);
 
        $this->params['traceObject'] = $trace;
    }
 
 
    /**
     * @return array
     */
    private function getDefaultHost()
    {
        return array(array('host' => 'localhost', 'port' => 9200));
    }
 
 
    /**
     * @param array $hosts
     *
     * @return array
     * @throws Common\Exceptions\InvalidArgumentException
     */
    private function buildHostsFromSeed($hosts)
    {
        if (is_array($hosts) === false) {
            throw new Exceptions\InvalidArgumentException('Hosts parameter must be an array of strings');
        }
 
        $finalHosts = array();
        foreach ($hosts as $host) {
            $host = $this->prependMissingScheme($host);
            $finalHosts[] = $this->extractURIParts($host);
        }
 
        return $finalHosts;
    }
 
 
    /**
     * @param array $host
     *
     * @return array
     * @throws Common\Exceptions\InvalidArgumentException
     */
    private function extractURIParts($host)
    {
 
        $parts = parse_url($host);
 
        if ($parts === false) {
            throw new Exceptions\InvalidArgumentException("Could not parse URI");
        }
 
        if (isset($parts['port']) !== true) {
            $parts['port'] = 9200;
        }
 
        return $parts;
    }
 
 
    /**
     * @param string $host
     *
     * @return string
     */
    private function prependMissingScheme($host) {
        if (!filter_var($host, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
            $host = 'http://' . $host;
        }
        return $host;
    }
 
    /**
     * @param array $params
     * @param string $arg
     *
     * @return null|mixed
     */
    public function extractArgument(&$params, $arg)
    {
        if (is_object($params) === true) {
            $params = (array)$params;
        }
 
        if (isset($params[$arg]) === true) {
            $val = $params[$arg];
            unset($params[$arg]);
            return $val;
        } else {
            return null;
        }
    }
 
 
}
#6Elasticsearch\Client->search(Array([index] => findmyrice2, [type] => el_company, [body] => Array([query] => Array([filtered] => Array()), [from] => 0, [size] => 10, [sort] => Array([0] => Array(), [1] => Array()))))
<?php
namespace Findmyrice\Controllers;
 
use Findmyrice\Models\Category;
use Elasticsearch;
use Findmyrice\Models\CompanyFollowers;
use Findmyrice\Models\Countries;
use Findmyrice\Models\ElasticSearchModel;
use Findmyrice\Models\Profile;
 
/**
 * Display the "Categories" page.
 */
class CategoriesController extends ControllerBase
{
    public function initialize()
    {
        $this->view->setTemplateBefore('public');
 
        $this->assets
            ->addJs('js/chosen.jquery.min.js')
            ->addJs('js/jquery-ui.min.js')
            ->addJs('js/search/index.js')
            ->addJs('js/elasticsearch_autocomplete.js')
            ->addcss('css/chosen.min.css')
            ->addCss('css/wingding3.css')
            ->addCss('css/jquery-ui.min.css');
 
        $this->view->default_country = '';
        $this->view->categories = $this->getCategories();
    }
 
    public function indexAction()
    {
        $this->view->setTemplateBefore('public');
        $this->view->login_slider = true;
    }
 
    public function allAction()
    {
        $categories = $this->getCategories();
 
        $geoData = $this->external->getGeoData();
        $country = $geoData['country_name'];
 
        $this->view->categories = $categories;
        $this->view->default_country = $country;
    }
 
    public function categoryAction($slug, $page = 1)
    {
      $this->assets->addJs('js/utilities.js');
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($slug),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
        
        // get query params to filter categories on
        // country, state, city
 
        $queryString = $this->request->getQuery();
        $data['el_city'] = $queryString['lf_city'];
        $data['el_state'] = $queryString['lf_state'];
        $data['business_type'] = $queryString['business_type'];
        // 
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $this->view->pick('categories/companies');
 
        $this->view->companies = $companies;
 
        if (!$category) {
            $this->view->companies = $companies;
        }
 
        $sub_categories = Category::find([
            'conditions' => [
                'parent_id' => (string)$category->_id
            ]
        ]);
 
        $geoData = $this->external->getGeoData();
        $country = $geoData['country_name'];
 
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->categories = $this->getCategories();
        $this->view->default_country = isset($get_data['location']) ? $get_data['location'] : $country;
        $this->view->similar_categories = $sub_categories;
        $this->view->slug2 = '';
 
    }
 
    public function companiesAction($category_slug, $sub_category_slug, $page = 1)
    {
        $this->assets
            ->addCss('css/jquery-ui.css');
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category_slug),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category_slug),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        if (!$category || !$sub_category) {
            return $this->dispatcher->forward(array(
                'controller' => 'error',
                'action' => 'show404'
            ));
        }
 
        $sub_categories = Category::find([
            'conditions' => [
                'parent_id' => (string)$category->_id
            ]
        ]);
 
        $data['el_category'] = $sub_category->name;
        $data['page'] = $page;
 
        $companies = $this->getCompaniesByCategory($data);
 
        $this->view->pick('categories/companies');
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug2 = $sub_category->slug;
        $this->view->similar_categories = $sub_categories;
        $this->view->categories = $this->getCategories();
 
    }
 
    public function countryAction($country, $page = 1)
    {
        $data['el_country'] = $country;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->location = ucfirst($country);
    }
 
    public function stateAction($country, $state, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("/^$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function cityAction($country, $state, $city, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function getCompaniesByLocationAction($country, $state, $city, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function countryCategoryAction($country, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($country);
    }
 
    public function countryStateCategoryAction($country, $state, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->state = ucfirst($state);
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function countryStateCityCategoryAction($country, $state, $city, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->city = ucfirst($city);
        $this->view->state = ucfirst($state);
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function countryCategorySubAction($country, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($country);
    }
 
    public function countryStateCategorySubAction($country, $state, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
        $data['el_category'] = $category->name;
        $data['page'] = $page;
 
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function countryStateCityCategorySubAction($country, $state, $city, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    private function getCompaniesByCategory(array $data)
    {
        $country = isset($data['el_country']) ? $data['el_country'] : '';
        $city = isset($data ['el_city']) ? ($data ['el_city']) : '';
        $state = isset($data['el_state']) ? $data['el_state'] : '';
        $business_type = isset($data['business_type']) ? $data['business_type'] : '';
        $category = isset($data['el_category']) ? $data['el_category'] : '';
        $sub_category = isset($data['el_sub_category']) ? $data['el_sub_category'] : '';
 
        $config = $this->getDI()->get('config');
 
        $clientCompany = new Elasticsearch\Client();
        $searchCompanyParams['index'] = $config['elasticSearch']['company']['index'];
        $searchCompanyParams['type'] = $config['elasticSearch']['company']['type'];
 
        $filter = [];
        $filter["bool"]["must"][]["term"]["active"] = 'Y';
        if($business_type)
            $filter['bool']['must'][]['term']['business_type.raw'] = $business_type;
        if ($category)
            $filter["bool"]["must"][]["query"]['match']["primary_product_service"] = $category;
        if ($sub_category)
            $filter["bool"]["must"][]["query"]['match']["primary_product_service"] = $sub_category;
        if ($country)
            $filter["bool"]["must"][]["query"]['match']["country.raw"] = ucfirst($country);
        if ($state)
            $filter["bool"]["must"][]["query"]['match']["state.raw"] = ucfirst($state);
        if ($city)
            $filter["bool"]["must"][]["query"]['match']["city.raw"] = ucfirst($city);
 
            
        $location_filter = [];
 
        if ($this->request->get('lat') && $this->request->get('lon')) {
            $distance = $this->request->get('distance', null, 0);
            $location_filter = array('geo_distance' => array("distance" => (string)$distance . 'km', "location" => array("lat" => (float)$this->request->get('lat'), "lon" => (float)$this->request->get('lon'))));
        }
 
        if (!empty($location_filter)) {
            $filter['bool']['must'][] = $location_filter;
        }
        $searchCompanyParams['body']['query']['filtered']['filter'] = $filter;
 
        if ($this->request->get('lat') && $this->request->get('lon')) {
            $searchCompanyParams['body']['script_fields']['distance']['params'] = ['lat' => (float)$this->request->get('lat'), 'lon' => (float)$this->request->get('lon')];
            $searchCompanyParams['body']['script_fields']['distance']['script'] = "doc['location'].distanceInKm(lat,lon)";
            $searchCompanyParams['body']['fields'] = '_source';
        }
        $size = 10;
        $from = 0;
        $page = $data['page'];
 
        if ($page) {
            $searchCompanyParams['body']['from'] = ($page - 1) * $size;
            $searchCompanyParams['body']['size'] = $size;
        } else {
            $searchCompanyParams['body']['from'] = $from;
            $searchCompanyParams['body']['size'] = $size;
        }
 
        $searchCompanyParams['body']['sort'][]['logo'] = array('order' => 'desc');
        $searchCompanyParams['body']['sort'][]['business_name.raw'] = array('order' => 'asc');
 
 
        //echo "<pre>";
        //echo json_encode($searchCompanyParams);
        //die;
        
        $result_search_company = $clientCompany->search($searchCompanyParams);
        //echo "<pre>";
        //print_r($result_search_company);
        //die;
        $totalCompanies = $result_search_company["hits"]["total"];
 
        $paging = $this->pagination($totalCompanies, $page, $size);
        $results = $result_search_company['hits']['hits'];
        $company_ids = [];
 
        foreach ($results as $result) {
            $company_ids[] = new \MongoId($result['_id']);
        }
 
        return [
            'companies' => $results,
            'profiles' => Profile::findByIds($company_ids),
            'count' => $totalCompanies,
            'page_dict' => $paging,
            'thumb_url' => $this->config->application->publicUrl,
            'followers' => $this->getFollower($result_search_company['hits']['hits']),
            'from' => ($page - 1) * $size + 1,
            'to' => ($size + ($page - 1) * $size > $totalCompanies) ? $totalCompanies : $size + ($page - 1) * $size
        ];
    }
 
    private function getFollower($companies)
    {
        $identity = $this->auth->getIdentity();
        $followers = [];
        $company_ids = [];
 
        foreach ($companies as $company) {
            $company_ids[] = new \MongoId($company['_id']);
        }
 
        $company_follower = CompanyFollowers::find([
            'conditions' => [
                'company_id' => ['$in' => $company_ids],
                'follower_id' => new \MongoId($identity['id']),
                'status' => true
            ]
        ]);
 
        foreach ($company_follower as $data) {
            $followers[(string)$data->company_id] = true;
        }
 
        return $followers;
 
    }
 
    private function pagination($total, $page = 1, $limit = 10)
    {
        $page_dict = array();
        $total_pages = ceil($total / $limit);
 
        if ($total_pages > 1) {
            if ($page > 1) {
                $page_dict['prev_page'] = $page - 1;
            }
            if ($total_pages <= 5) {
                $page_dict['pages'] = range(1, $total_pages);
            } else {
 
                if ($page < 3) {
                    $page_dict['pages'] = range(1, 5);
                } else {
                    $page_dict['pages'] = range($page - 2, min([$page + 2, $total_pages]));
                }
            }
            if ($page < $total_pages) {
                $page_dict['next_page'] = $page + 1;
            }
        } else {
            $page_dict['pages'] = [];
        }
        $page_dict['cur_page'] = $page;
        $page_dict['total_pages'] = $total_pages;
        return $page_dict;
    }
 
    protected function getCategories()
    {
        $parent_categories = Category::find([
            'conditions' => [
                'parent_id' => ['$eq' => null]
            ],
            'fields' => ['name', 'slug'],
            'sort' => ['name' => 1]
        ]);
 
        $parent_category_ids = [];
        $categories = [];
 
        foreach ($parent_categories as $parent_category) {
            $parent_category_ids[] = (string)$parent_category->_id;
            $categories[(string)$parent_category->_id]['name'] = $parent_category->name;
            $categories[(string)$parent_category->_id]['slug'] = $parent_category->slug;
        }
 
        $child_categories = Category::find([
            'conditions' => [
                'parent_id' => ['$in' => $parent_category_ids]
            ],
            'fields' => ['name', 'parent_id', 'slug'],
            'sort' => ['name' => 1]
        ]);
 
        $child = [];
 
        foreach ($child_categories as $child_category) {
            $child[$child_category->parent_id]['children'][] = [
                'slug' => $child_category->slug,
                'name' => $child_category->name
            ];
        }
 
        $categories = array_merge_recursive($categories, $child);
 
        return $categories;
    }
}
#7Findmyrice\Controllers\CategoriesController->getCompaniesByCategory(Array([el_category] => null, [el_city] => null, [el_state] => null, [business_type] => null, [page] => 1))
<?php
namespace Findmyrice\Controllers;
 
use Findmyrice\Models\Category;
use Elasticsearch;
use Findmyrice\Models\CompanyFollowers;
use Findmyrice\Models\Countries;
use Findmyrice\Models\ElasticSearchModel;
use Findmyrice\Models\Profile;
 
/**
 * Display the "Categories" page.
 */
class CategoriesController extends ControllerBase
{
    public function initialize()
    {
        $this->view->setTemplateBefore('public');
 
        $this->assets
            ->addJs('js/chosen.jquery.min.js')
            ->addJs('js/jquery-ui.min.js')
            ->addJs('js/search/index.js')
            ->addJs('js/elasticsearch_autocomplete.js')
            ->addcss('css/chosen.min.css')
            ->addCss('css/wingding3.css')
            ->addCss('css/jquery-ui.min.css');
 
        $this->view->default_country = '';
        $this->view->categories = $this->getCategories();
    }
 
    public function indexAction()
    {
        $this->view->setTemplateBefore('public');
        $this->view->login_slider = true;
    }
 
    public function allAction()
    {
        $categories = $this->getCategories();
 
        $geoData = $this->external->getGeoData();
        $country = $geoData['country_name'];
 
        $this->view->categories = $categories;
        $this->view->default_country = $country;
    }
 
    public function categoryAction($slug, $page = 1)
    {
      $this->assets->addJs('js/utilities.js');
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($slug),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
        
        // get query params to filter categories on
        // country, state, city
 
        $queryString = $this->request->getQuery();
        $data['el_city'] = $queryString['lf_city'];
        $data['el_state'] = $queryString['lf_state'];
        $data['business_type'] = $queryString['business_type'];
        // 
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $this->view->pick('categories/companies');
 
        $this->view->companies = $companies;
 
        if (!$category) {
            $this->view->companies = $companies;
        }
 
        $sub_categories = Category::find([
            'conditions' => [
                'parent_id' => (string)$category->_id
            ]
        ]);
 
        $geoData = $this->external->getGeoData();
        $country = $geoData['country_name'];
 
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->categories = $this->getCategories();
        $this->view->default_country = isset($get_data['location']) ? $get_data['location'] : $country;
        $this->view->similar_categories = $sub_categories;
        $this->view->slug2 = '';
 
    }
 
    public function companiesAction($category_slug, $sub_category_slug, $page = 1)
    {
        $this->assets
            ->addCss('css/jquery-ui.css');
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category_slug),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category_slug),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        if (!$category || !$sub_category) {
            return $this->dispatcher->forward(array(
                'controller' => 'error',
                'action' => 'show404'
            ));
        }
 
        $sub_categories = Category::find([
            'conditions' => [
                'parent_id' => (string)$category->_id
            ]
        ]);
 
        $data['el_category'] = $sub_category->name;
        $data['page'] = $page;
 
        $companies = $this->getCompaniesByCategory($data);
 
        $this->view->pick('categories/companies');
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug2 = $sub_category->slug;
        $this->view->similar_categories = $sub_categories;
        $this->view->categories = $this->getCategories();
 
    }
 
    public function countryAction($country, $page = 1)
    {
        $data['el_country'] = $country;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->location = ucfirst($country);
    }
 
    public function stateAction($country, $state, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("/^$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function cityAction($country, $state, $city, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->slug = '';
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function getCompaniesByLocationAction($country, $state, $city, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function countryCategoryAction($country, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($country);
    }
 
    public function countryStateCategoryAction($country, $state, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->state = ucfirst($state);
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function countryStateCityCategoryAction($country, $state, $city, $category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->slug = $category->slug;
        $this->view->city = ucfirst($city);
        $this->view->state = ucfirst($state);
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    public function countryCategorySubAction($country, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->location = ucwords($country);
    }
 
    public function countryStateCategorySubAction($country, $state, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
        $data['el_category'] = $category->name;
        $data['page'] = $page;
 
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->location = ucwords($state . ', ' . $country);
    }
 
    public function countryStateCityCategorySubAction($country, $state, $city, $category, $sub_category, $page = 1)
    {
        $data['el_country'] = @ucfirst(str_replace('-', ' ', $country));
        $data['el_state'] = @ucfirst(str_replace('-', ' ', $state));
        $data['el_city'] = @ucfirst(str_replace('-', ' ', $city));
 
        $category = Category::findFirst([
            'conditions' => [
                'slug' => trim($category),
                'parent_id' => null
            ]
        ]);
 
        $sub_category = Category::findFirst([
            'conditions' => [
                'slug' => trim($sub_category),
                'parent_id' => ['$ne' => null]
            ]
        ]);
 
        $data['el_sub_category'] = $sub_category->name;
 
        $data['el_category'] = $category->name;
 
        $data['page'] = $page;
        $companies = $this->getCompaniesByCategory($data);
 
        $country_iso_code = Countries::findFirst([
            'conditions' => [
                'country_name' => new \MongoRegex("$country/i")
            ]
        ])->iso_code;
 
        $this->view->pick('categories/companies');
 
        $this->view->country_code = $country_iso_code;
 
        $this->view->categories = $this->getCategories();
        $this->view->companies = $companies;
        $this->view->category = $category->name;
        $this->view->sub_category = $sub_category->name;
        $this->view->slug = $category->slug;
        $this->view->slug2 = $sub_category->slug;
        $this->view->country = ucfirst($country);
        $this->view->state = ucfirst($state);
        $this->view->city = ucfirst($city);
        $this->view->location = ucwords($city . ', ' . $state . ', ' . $country);
    }
 
    private function getCompaniesByCategory(array $data)
    {
        $country = isset($data['el_country']) ? $data['el_country'] : '';
        $city = isset($data ['el_city']) ? ($data ['el_city']) : '';
        $state = isset($data['el_state']) ? $data['el_state'] : '';
        $business_type = isset($data['business_type']) ? $data['business_type'] : '';
        $category = isset($data['el_category']) ? $data['el_category'] : '';
        $sub_category = isset($data['el_sub_category']) ? $data['el_sub_category'] : '';
 
        $config = $this->getDI()->get('config');
 
        $clientCompany = new Elasticsearch\Client();
        $searchCompanyParams['index'] = $config['elasticSearch']['company']['index'];
        $searchCompanyParams['type'] = $config['elasticSearch']['company']['type'];
 
        $filter = [];
        $filter["bool"]["must"][]["term"]["active"] = 'Y';
        if($business_type)
            $filter['bool']['must'][]['term']['business_type.raw'] = $business_type;
        if ($category)
            $filter["bool"]["must"][]["query"]['match']["primary_product_service"] = $category;
        if ($sub_category)
            $filter["bool"]["must"][]["query"]['match']["primary_product_service"] = $sub_category;
        if ($country)
            $filter["bool"]["must"][]["query"]['match']["country.raw"] = ucfirst($country);
        if ($state)
            $filter["bool"]["must"][]["query"]['match']["state.raw"] = ucfirst($state);
        if ($city)
            $filter["bool"]["must"][]["query"]['match']["city.raw"] = ucfirst($city);
 
            
        $location_filter = [];
 
        if ($this->request->get('lat') && $this->request->get('lon')) {
            $distance = $this->request->get('distance', null, 0);
            $location_filter = array('geo_distance' => array("distance" => (string)$distance . 'km', "location" => array("lat" => (float)$this->request->get('lat'), "lon" => (float)$this->request->get('lon'))));
        }
 
        if (!empty($location_filter)) {
            $filter['bool']['must'][] = $location_filter;
        }
        $searchCompanyParams['body']['query']['filtered']['filter'] = $filter;
 
        if ($this->request->get('lat') && $this->request->get('lon')) {
            $searchCompanyParams['body']['script_fields']['distance']['params'] = ['lat' => (float)$this->request->get('lat'), 'lon' => (float)$this->request->get('lon')];
            $searchCompanyParams['body']['script_fields']['distance']['script'] = "doc['location'].distanceInKm(lat,lon)";
            $searchCompanyParams['body']['fields'] = '_source';
        }
        $size = 10;
        $from = 0;
        $page = $data['page'];
 
        if ($page) {
            $searchCompanyParams['body']['from'] = ($page - 1) * $size;
            $searchCompanyParams['body']['size'] = $size;
        } else {
            $searchCompanyParams['body']['from'] = $from;
            $searchCompanyParams['body']['size'] = $size;
        }
 
        $searchCompanyParams['body']['sort'][]['logo'] = array('order' => 'desc');
        $searchCompanyParams['body']['sort'][]['business_name.raw'] = array('order' => 'asc');
 
 
        //echo "<pre>";
        //echo json_encode($searchCompanyParams);
        //die;
        
        $result_search_company = $clientCompany->search($searchCompanyParams);
        //echo "<pre>";
        //print_r($result_search_company);
        //die;
        $totalCompanies = $result_search_company["hits"]["total"];
 
        $paging = $this->pagination($totalCompanies, $page, $size);
        $results = $result_search_company['hits']['hits'];
        $company_ids = [];
 
        foreach ($results as $result) {
            $company_ids[] = new \MongoId($result['_id']);
        }
 
        return [
            'companies' => $results,
            'profiles' => Profile::findByIds($company_ids),
            'count' => $totalCompanies,
            'page_dict' => $paging,
            'thumb_url' => $this->config->application->publicUrl,
            'followers' => $this->getFollower($result_search_company['hits']['hits']),
            'from' => ($page - 1) * $size + 1,
            'to' => ($size + ($page - 1) * $size > $totalCompanies) ? $totalCompanies : $size + ($page - 1) * $size
        ];
    }
 
    private function getFollower($companies)
    {
        $identity = $this->auth->getIdentity();
        $followers = [];
        $company_ids = [];
 
        foreach ($companies as $company) {
            $company_ids[] = new \MongoId($company['_id']);
        }
 
        $company_follower = CompanyFollowers::find([
            'conditions' => [
                'company_id' => ['$in' => $company_ids],
                'follower_id' => new \MongoId($identity['id']),
                'status' => true
            ]
        ]);
 
        foreach ($company_follower as $data) {
            $followers[(string)$data->company_id] = true;
        }
 
        return $followers;
 
    }
 
    private function pagination($total, $page = 1, $limit = 10)
    {
        $page_dict = array();
        $total_pages = ceil($total / $limit);
 
        if ($total_pages > 1) {
            if ($page > 1) {
                $page_dict['prev_page'] = $page - 1;
            }
            if ($total_pages <= 5) {
                $page_dict['pages'] = range(1, $total_pages);
            } else {
 
                if ($page < 3) {
                    $page_dict['pages'] = range(1, 5);
                } else {
                    $page_dict['pages'] = range($page - 2, min([$page + 2, $total_pages]));
                }
            }
            if ($page < $total_pages) {
                $page_dict['next_page'] = $page + 1;
            }
        } else {
            $page_dict['pages'] = [];
        }
        $page_dict['cur_page'] = $page;
        $page_dict['total_pages'] = $total_pages;
        return $page_dict;
    }
 
    protected function getCategories()
    {
        $parent_categories = Category::find([
            'conditions' => [
                'parent_id' => ['$eq' => null]
            ],
            'fields' => ['name', 'slug'],
            'sort' => ['name' => 1]
        ]);
 
        $parent_category_ids = [];
        $categories = [];
 
        foreach ($parent_categories as $parent_category) {
            $parent_category_ids[] = (string)$parent_category->_id;
            $categories[(string)$parent_category->_id]['name'] = $parent_category->name;
            $categories[(string)$parent_category->_id]['slug'] = $parent_category->slug;
        }
 
        $child_categories = Category::find([
            'conditions' => [
                'parent_id' => ['$in' => $parent_category_ids]
            ],
            'fields' => ['name', 'parent_id', 'slug'],
            'sort' => ['name' => 1]
        ]);
 
        $child = [];
 
        foreach ($child_categories as $child_category) {
            $child[$child_category->parent_id]['children'][] = [
                'slug' => $child_category->slug,
                'name' => $child_category->name
            ];
        }
 
        $categories = array_merge_recursive($categories, $child);
 
        return $categories;
    }
}
#8Findmyrice\Controllers\CategoriesController->categoryAction(beverage-wine, 1)
#9Phalcon\Dispatcher->dispatch()
#10Phalcon\Mvc\Application->handle()
<?php
 
error_reporting(E_ERROR | E_PARSE);
session_cache_expire(0);
 
require('../app/library/infusionsoft-php-sdk-master/Infusionsoft/infusionsoft.php');
 
//try {
/**
 * Define some useful constants
 */
define('BASE_DIR', dirname(__DIR__));
define('APP_DIR', BASE_DIR . '/app');
define('SITE_URL', 'https://findmyrice.com');
define('BUCKET_URL_OLD', 'https://findmyrice.s3-us-west-2.amazonaws.com');
define('BUCKET_URL', 'https://d2yi95dpfml40v.cloudfront.net');
define('AMAZON_AWS_URL', 'https://s3-us-west-2.amazonaws.com');
 
define('ADMIN_PROFILE_ID', '54c0b1faa740f4fafe2ae26c');
define('ADMIN_ASSISTANT_ID', '5538b5ac23e22d70cddb5dbb');
define('USER_PROFILE_ID', '54c0b20ca740f4fafe2ae26d');
define('COMPANY_PROFILE_ID', '54c0b22ba740f4fafe2ae26e');
define('NEWS_CONTRIBUTOR_PROFILE_ID', '54df72e2dd435c45e09d37fb');
define('PARTNER_PROFILE_ID', '55928539152c70b106a7b7dc');
define('ASSOCIATION_ID', '56da8ae9f31e48486bc90edc');
 
define('GRAPH_FACEBOOK_URL', 'https://graph.facebook.com');
define('REDIRECT_FB_URL', SITE_URL . '/session/regFacebook/');
define('REDIRECT_LI_URL', SITE_URL . '/session/regLinkedIn/');
define('REDIRECT_LOGIN_FB_URL', SITE_URL . '/session/loginWithFacebook/');
define('REDIRECT_LOGIN_LI_URL', SITE_URL . '/session/loginWithLinkedIn/');
 
 
define('MEMBERSHIP_TYPE_FREE', 'Free');
define('MEMBERSHIP_TYPE_BASIC', 'Basic');
define('MEMBERSHIP_TYPE_PREMIUM_LIGHT', 'Premium Light');
define('MEMBERSHIP_TYPE_PREMIUM_BUSINESS', 'Premium Business');
 
define('VISIBLE_SECTION', false);
 
// define the application environment
define('APP_ENV', 'PROD'); // PROD(production), DEV(development), TEST(test)
 
/**
 * Read the configuration
 */
$config = include APP_DIR . '/config/config.php';
 
// merge with configuration for the current environment
$config->merge(include APP_DIR . '/config/config-' . mb_strtolower(APP_ENV) . '.php');
 
/**
 * Read auto-loader
 */
include APP_DIR . '/config/loader.php';
 
/**
 * Read services
 */
include APP_DIR . '/config/services.php';
 
$listener = new \Phalcon\Debug();
$listener->listen();
 
/**
 * Handle the request
 */
$application = new \Phalcon\Mvc\Application($di);
 
echo $application->handle()->getContent();
 
//} catch (Exception $e) {
//  echo $e->getMessage(), '<br>';
//  echo nl2br(htmlentities($e->getTraceAsString()));
//}
KeyValue
_url/c/beverage-wine/page/1
KeyValue
USERwww-data
HOME/var/www
FCGI_ROLERESPONDER
QUERY_STRING_url=/c/beverage-wine/page/1
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_FILENAME/var/www/findmyrice/public/index.php
SCRIPT_NAME/index.php
REQUEST_URI/c/beverage-wine/page/1
DOCUMENT_URI/index.php
DOCUMENT_ROOT/var/www/findmyrice/public
SERVER_PROTOCOLHTTP/1.1
GATEWAY_INTERFACECGI/1.1
SERVER_SOFTWAREnginx/1.4.6
REMOTE_ADDR54.160.19.155
REMOTE_PORT53598
SERVER_ADDR10.10.0.6
SERVER_PORT443
SERVER_NAMEfindmyrice.com
HTTPSon
REDIRECT_STATUS200
PATH_INFO
PATH_TRANSLATED/var/www/findmyrice/public
HTTP_USER_AGENTCCBot/2.0 (https://commoncrawl.org/faq/)
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGEen-US,en;q=0.5
HTTP_IF_MODIFIED_SINCEMon, 20 Jan 2020 14:25:32 GMT
HTTP_ACCEPT_ENCODINGbr,gzip
HTTP_HOSTfindmyrice.com
HTTP_CONNECTIONKeep-Alive
PHP_SELF/index.php
REQUEST_TIME_FLOAT1597454870.7501
REQUEST_TIME1597454870
#Path
0/var/www/findmyrice/public/index.php
1/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/infusionsoft.php
2/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/Classloader.php
3/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/xmlrpc.inc
4/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/config.php
5/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/AppPool.php
6/var/www/findmyrice/app/library/infusionsoft-php-sdk-master/Infusionsoft/App.php
7/var/www/findmyrice/app/config/config.php
8/var/www/findmyrice/app/config/config-prod.php
9/var/www/findmyrice/app/config/loader.php
10/var/www/findmyrice/app/vendor/autoload.php
11/var/www/findmyrice/app/vendor/composer/autoload_real.php
12/var/www/findmyrice/app/vendor/composer/ClassLoader.php
13/var/www/findmyrice/app/vendor/composer/include_paths.php
14/var/www/findmyrice/app/vendor/composer/autoload_namespaces.php
15/var/www/findmyrice/app/vendor/composer/autoload_psr4.php
16/var/www/findmyrice/app/vendor/composer/autoload_classmap.php
17/var/www/findmyrice/app/vendor/composer/autoload_files.php
18/var/www/findmyrice/app/vendor/swiftmailer/swiftmailer/lib/swift_required.php
19/var/www/findmyrice/app/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php
20/var/www/findmyrice/app/vendor/guzzlehttp/psr7/src/functions_include.php
21/var/www/findmyrice/app/vendor/guzzlehttp/psr7/src/functions.php
22/var/www/findmyrice/app/config/services.php
23/var/www/findmyrice/app/config/routes.php
24/var/www/findmyrice/app/plugins/IdentifyInvitePlugin.php
25/var/www/findmyrice/app/plugins/RegistrationPlugin.php
26/var/www/findmyrice/app/controllers/CategoriesController.php
27/var/www/findmyrice/app/controllers/ControllerBase.php
28/var/www/findmyrice/app/library/External/External.php
29/var/www/findmyrice/app/models/OnlineUsers.php
30/var/www/findmyrice/app/library/Auth/Auth.php
31/var/www/findmyrice/app/forms/LoginForm.php
32/var/www/findmyrice/app/forms/SignUpUserForm.php
33/var/www/findmyrice/app/vendor/facebook/php-sdk-v4/src/Facebook/FacebookSession.php
34/var/www/findmyrice/app/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRedirectLoginHelper.php
35/var/www/findmyrice/app/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequest.php
36/var/www/findmyrice/app/vendor/linkedinapi/linkedin/LinkedIn/LinkedIn.php
37/var/www/findmyrice/app/library/Acl/Acl.php
38/var/www/findmyrice/app/models/Users.php
39/var/www/findmyrice/app/models/Companies.php
40/var/www/findmyrice/app/models/UsersCompanies.php
41/var/www/findmyrice/app/models/Friends.php
42/var/www/findmyrice/app/models/Category.php
43/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Client.php
44/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/DICBuilder.php
45/var/www/findmyrice/app/vendor/psr/log/Psr/Log/LogLevel.php
46/var/www/findmyrice/app/vendor/pimple/pimple/src/Pimple/Container.php
47/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/ClusterNamespace.php
48/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/AbstractNamespace.php
49/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/IndicesNamespace.php
50/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/NodesNamespace.php
51/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/SnapshotNamespace.php
52/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/CatNamespace.php
53/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/EmptyLogger.php
54/var/www/findmyrice/app/vendor/psr/log/Psr/Log/AbstractLogger.php
55/var/www/findmyrice/app/vendor/psr/log/Psr/Log/LoggerInterface.php
56/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php
57/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/SmartSerializer.php
58/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/ArrayToJSONSerializer.php
59/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/AbstractJsonSerializer.php
60/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Serializers/SerializerInterface.php
61/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/GuzzleConnection.php
62/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/AbstractConnection.php
63/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/ConnectionInterface.php
64/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Client.php
65/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php
66/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.php
67/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php
68/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php
69/var/www/findmyrice/app/vendor/symfony/event-dispatcher/EventSubscriberInterface.php
70/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php
71/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.php
72/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php
73/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php
74/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Version.php
75/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php
76/var/www/findmyrice/app/vendor/symfony/event-dispatcher/EventDispatcher.php
77/var/www/findmyrice/app/vendor/symfony/event-dispatcher/EventDispatcherInterface.php
78/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/StaticNoPingConnectionPool.php
79/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/AbstractConnectionPool.php
80/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/Selectors/RoundRobinSelector.php
81/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/Selectors/SelectorInterface.php
82/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/ConnectionFactory.php
83/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/AbstractFactory.php
84/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/Search.php
85/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/AbstractEndpoint.php
86/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php
87/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.php
88/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php
89/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php
90/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Request.php
91/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php
92/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php
93/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php
94/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php
95/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php
96/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php
97/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php
98/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php
99/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Url.php
100/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php
101/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.php
102/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php
103/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.php
104/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php
105/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php
106/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php
107/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Event.php
108/var/www/findmyrice/app/vendor/symfony/event-dispatcher/Event.php
109/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.php
110/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php
111/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Response.php
112/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.php
113/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php
114/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.php
115/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php
116/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php
117/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php
118/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php
119/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php
120/var/www/findmyrice/app/vendor/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php
121/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/Curl/CouldNotConnectToHost.php
122/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/TransportException.php
123/var/www/findmyrice/app/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Common/Exceptions/ElasticsearchException.php
Memory
Usage3670016