Completed
Pull Request — master (#1465)
by
unknown
04:31
created

Client::request()   B

Complexity

Conditions 8
Paths 20

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8.013

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 16
cts 17
cp 0.9412
rs 8.1954
c 0
b 0
f 0
cc 8
nc 20
nop 5
crap 8.013
1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\ElasticaBundle\Elastica;
13
14
use Elastica\Client as BaseClient;
15
use Elastica\Exception\ClientException;
16
use Elastica\Request;
17
use FOS\ElasticaBundle\Logger\ElasticaLogger;
18
use Symfony\Component\Stopwatch\Stopwatch;
19
20
/**
21
 * Extends the default Elastica client to provide logging for errors that occur
22
 * during communication with ElasticSearch.
23
 *
24
 * @author Gordon Franke <[email protected]>
25
 */
26
class Client extends BaseClient
27
{
28
    /**
29
     * Stores created indexes to avoid recreation.
30
     *
31
     * @var array
32
     */
33
    private $indexCache = [];
34
35
    /**
36
     * Symfony's debugging Stopwatch.
37
     *
38
     * @var Stopwatch|null
39
     */
40
    private $stopwatch;
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 11
    public function request($path, $method = Request::GET, $data = [], array $query = [], $contentType = Request::DEFAULT_CONTENT_TYPE)
46
    {
47 11
        if ($this->stopwatch) {
48 9
            $this->stopwatch->start('es_request', 'fos_elastica');
49
        }
50
51 11
        $response = parent::request($path, $method, $data, $query, $contentType);
52 11
        $responseData = $response->getData();
53
54 11
        $transportInfo = $response->getTransferInfo();
55 11
        $connection = $this->getLastRequest()->getConnection();
56 11
        $forbiddenHttpCodes = $connection->hasConfig('http_error_codes') ? $connection->getConfig('http_error_codes') : [];
57
58 11
        if (isset($transportInfo['http_code']) && in_array($transportInfo['http_code'], $forbiddenHttpCodes, true)) {
59 1
            $message = sprintf('Error in transportInfo: response code is %s, response body is %s', $transportInfo['http_code'], $responseData);
60
            throw new ClientException($message);
61
        }
62
63 10
        if (isset($responseData['took']) && isset($responseData['hits'])) {
64 2
            $this->logQuery($path, $method, $data, $query, $response->getQueryTime(), $response->getEngineTime(), $responseData['hits']['total']);
65
        } else {
66 9
            $this->logQuery($path, $method, $data, $query, $response->getQueryTime(), 0, 0);
67
        }
68
69 10
        if ($this->stopwatch) {
70 9
            $this->stopwatch->stop('es_request');
71
        }
72
73 10
        return $response;
74
    }
75
76
    /**
77
     * @param string $name
78
     *
79
     * @return Index|mixed
80
     */
81 11
    public function getIndex($name)
82
    {
83 11
        if (isset($this->indexCache[$name])) {
84
            return $this->indexCache[$name];
85
        }
86
87 11
        return $this->indexCache[$name] = new Index($this, $name);
88
    }
89
90
    /**
91
     * Sets a stopwatch instance for debugging purposes.
92
     *
93
     * @param Stopwatch $stopwatch
94
     */
95 12
    public function setStopwatch(Stopwatch $stopwatch = null)
96
    {
97 12
        $this->stopwatch = $stopwatch;
98 12
    }
99
100
    /**
101
     * Log the query if we have an instance of ElasticaLogger.
102
     *
103
     * @param string $path
104
     * @param string $method
105
     * @param array|string $data
106
     * @param array  $query
107
     * @param int    $queryTime
108
     * @param int    $engineMS
109
     * @param int    $itemCount
110
     */
111 10
    private function logQuery($path, $method, $data, array $query, $queryTime, $engineMS = 0, $itemCount = 0)
112
    {
113 10
        if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) {
114
            return;
115
        }
116
117 10
        $connection = $this->getLastRequest()->getConnection();
118
119
        $connectionArray = [
120 10
            'host' => $connection->getHost(),
121 10
            'port' => $connection->getPort(),
122 10
            'transport' => $connection->getTransport(),
123 10
            'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : [],
124
        ];
125
126
        /** @var ElasticaLogger $logger */
127 10
        $logger = $this->_logger;
128 10
        $logger->logQuery($path, $method, $data, $queryTime, $connectionArray, $query, $engineMS, $itemCount);
129 10
    }
130
}
131