Completed
Pull Request — master (#1465)
by
unknown
20:57
created

Client::request()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 9.0294

Importance

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