Completed
Pull Request — master (#1465)
by
unknown
06:02
created

Client::request()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 9.0368

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 12
cts 13
cp 0.9231
rs 8.0555
c 0
b 0
f 0
cc 9
nc 24
nop 5
crap 9.0368
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 10
     */
45
    public function request($path, $method = Request::GET, $data = [], array $query = [], $contentType = Request::DEFAULT_CONTENT_TYPE)
46 10
    {
47 9
        if ($this->stopwatch) {
48
            $this->stopwatch->start('es_request', 'fos_elastica');
49
        }
50 10
51 10
        $response = parent::request($path, $method, $data, $query, $contentType);
52
53 10
        $transportInfo = $response->getTransferInfo();
54 2
55
        $connection = $this->getLastRequest()->getConnection();
56 9
        $forbiddenHttpCodes = $connection->hasConfig('http_error_codes') ? $connection->getConfig('http_error_codes') : [];
57
58
        if (isset($transportInfo['http_code']) && in_array($transportInfo['http_code'], $forbiddenHttpCodes, true)) {
59 10
            $body = isset($transportInfo['body']) ? $transportInfo['body'] : 'blank';
60 9
            $message = sprintf('Error in transportInfo: response code is %s, response body is %s', $transportInfo['http_code'], $body);
61
            throw new ClientException($message);
62
        }
63 10
64
        $responseData = $response->getData();
65
        if (isset($responseData['took']) && isset($responseData['hits'])) {
66
            $this->logQuery($path, $method, $data, $query, $response->getQueryTime(), $response->getEngineTime(), $responseData['hits']['total']);
67
        } else {
68
            $this->logQuery($path, $method, $data, $query, $response->getQueryTime(), 0, 0);
69
        }
70
71 12
        if ($this->stopwatch) {
72
            $this->stopwatch->stop('es_request');
73 12
        }
74
75
        return $response;
76
    }
77 12
78
    /**
79
     * @param string $name
80
     *
81
     * @return Index|mixed
82
     */
83
    public function getIndex($name)
84
    {
85 13
        if (isset($this->indexCache[$name])) {
86
            return $this->indexCache[$name];
87 13
        }
88 13
89
        return $this->indexCache[$name] = new Index($this, $name);
90
    }
91
92
    /**
93
     * Sets a stopwatch instance for debugging purposes.
94
     *
95
     * @param Stopwatch $stopwatch
96
     */
97
    public function setStopwatch(Stopwatch $stopwatch = null)
98
    {
99
        $this->stopwatch = $stopwatch;
100
    }
101 10
102
    /**
103 10
     * Log the query if we have an instance of ElasticaLogger.
104
     *
105
     * @param string $path
106
     * @param string $method
107 10
     * @param array|string $data
108
     * @param array  $query
109
     * @param int    $queryTime
110 10
     * @param int    $engineMS
111 10
     * @param int    $itemCount
112 10
     */
113 10
    private function logQuery($path, $method, $data, array $query, $queryTime, $engineMS = 0, $itemCount = 0)
114
    {
115
        if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) {
116
            return;
117 10
        }
118 10
119 10
        $connection = $this->getLastRequest()->getConnection();
120
121
        $connectionArray = [
122
            'host' => $connection->getHost(),
123
            'port' => $connection->getPort(),
124
            'transport' => $connection->getTransport(),
125
            'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : [],
126
        ];
127
128
        /** @var ElasticaLogger $logger */
129
        $logger = $this->_logger;
130
        $logger->logQuery($path, $method, $data, $queryTime, $connectionArray, $query, $engineMS, $itemCount);
131
    }
132
}
133