Completed
Push — master ( a9ef82...23e03c )
by GBProd
02:36
created

Client::request()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.9256

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 22
ccs 10
cts 15
cp 0.6667
rs 8.6737
cc 5
eloc 13
nc 8
nop 4
crap 5.9256
1
<?php
2
3
namespace GBProd\ElasticaBundle\Elastica;
4
5
use Elastica\Client as BaseClient;
6
use Elastica\Request;
7
use GBProd\ElasticaBundle\Logger\ElasticaLogger;
8
use Symfony\Component\Stopwatch\Stopwatch;
9
10
/**
11
 * Extends the default Elastica client to provide logging for errors that occur
12
 * during communication with ElasticSearch.
13
 *
14
 * @author Gordon Franke <[email protected]>
15
 */
16
class Client extends BaseClient
17
{
18
    /**
19
     * Stores created indexes to avoid recreation.
20
     *
21
     * @var array
22
     */
23
    private $indexCache = array();
24
25
    /**
26
     * Symfony's debugging Stopwatch.
27
     *
28
     * @var Stopwatch|null
29
     */
30
    private $stopwatch;
31
32
    /**
33
     * @param string $path
34
     * @param string $method
35
     * @param array  $data
36
     * @param array  $query
37
     *
38
     * @return \Elastica\Response
39
     */
40 1
    public function request($path, $method = Request::GET, $data = array(), array $query = array())
41
    {
42 1
        if ($this->stopwatch) {
43
            $this->stopwatch->start('es_request', 'fos_elastica');
44
        }
45
46 1
        $start = microtime(true);
47 1
        $response = parent::request($path, $method, $data, $query);
48 1
        $responseData = $response->getData();
49
50 1
        if (isset($responseData['took']) && isset($responseData['hits'])) {
51 1
            $this->logQuery($path, $method, $data, $query, $start, $response->getEngineTime(), $responseData['hits']['total']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
52 1
        } else {
53
            $this->logQuery($path, $method, $data, $query, $start, 0, 0);
54
        }
55
56 1
        if ($this->stopwatch) {
57
            $this->stopwatch->stop('es_request');
58
        }
59
60 1
        return $response;
61
    }
62
63
    public function getIndex($name)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
64
    {
65
        if (isset($this->indexCache[$name])) {
66
            return $this->indexCache[$name];
67
        }
68
69
        return $this->indexCache[$name] = new Index($this, $name);
70
    }
71
72
    /**
73
     * Sets a stopwatch instance for debugging purposes.
74
     *
75
     * @param Stopwatch $stopwatch
0 ignored issues
show
Documentation introduced by
Should the type for parameter $stopwatch not be null|Stopwatch?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
76
     */
77
    public function setStopwatch(Stopwatch $stopwatch = null)
78
    {
79
        $this->stopwatch = $stopwatch;
80
    }
81
82
    /**
83
     * Log the query if we have an instance of ElasticaLogger.
84
     *
85
     * @param string $path
86
     * @param string $method
87
     * @param array  $data
88
     * @param array  $query
89
     * @param int    $start
90
     */
91 1
    private function logQuery($path, $method, $data, array $query, $start, $engineMS = 0, $itemCount = 0)
92
    {
93 1
        if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
94
            return;
95
        }
96
97 1
        $time = microtime(true) - $start;
98 1
        $connection = $this->getLastRequest()->getConnection();
99
100
        $connection_array = array(
101 1
            'host' => $connection->getHost(),
102 1
            'port' => $connection->getPort(),
103 1
            'transport' => $connection->getTransport(),
104 1
            'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : array(),
105 1
        );
106
107 1
        $this->_logger->logQuery($path, $method, $data, $time, $connection_array, $query, $engineMS, $itemCount);
108 1
    }
109
}
110