Completed
Push — master ( 6efea1...0e768a )
by Simonas
04:33 queued 10s
created

ElasticsearchProfiler::reset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
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 ONGR\ElasticsearchBundle\Profiler;
13
14
use Monolog\Logger;
15
use ONGR\ElasticsearchBundle\Profiler\Handler\CollectionHandler;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
19
20
/**
21
 * Data collector for profiling elasticsearch bundle.
22
 */
23
class ElasticsearchProfiler implements DataCollectorInterface
24
{
25
    const UNDEFINED_ROUTE = 'undefined_route';
26
27
    /**
28
     * @var Logger[] Watched loggers.
29
     */
30
    private $loggers = [];
31
32
    /**
33
     * @var array Queries array.
34
     */
35
    private $queries = [];
36
37
    /**
38
     * @var int Query count.
39
     */
40
    private $count = 0;
41
42
    /**
43
     * @var float Time all queries took.
44
     */
45
    private $time = .0;
46
47
    /**
48
     * @var array Registered managers.
49
     */
50
    private $managers = [];
51
52
    /**
53
     * Adds logger to look for collector handler.
54
     *
55
     * @param Logger $logger
56
     */
57
    public function addLogger(Logger $logger)
58
    {
59
        $this->loggers[] = $logger;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function collect(Request $request, Response $response, \Exception $exception = null)
66
    {
67
        /** @var Logger $logger */
68
        foreach ($this->loggers as $logger) {
69
            foreach ($logger->getHandlers() as $handler) {
70
                if ($handler instanceof CollectionHandler) {
71
                    $this->handleRecords($this->getRoute($request), $handler->getRecords());
72
                    $handler->clearRecords();
73
                }
74
            }
75
        }
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function reset()
82
    {
83
        $this->queries = [];
84
        $this->count = 0;
85
        $this->time = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $time was declared of type double, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
86
    }
87
88
    /**
89
     * Returns total time queries took.
90
     *
91
     * @return string
92
     */
93
    public function getTime()
94
    {
95
        return round($this->time * 1000, 2);
96
    }
97
98
    /**
99
     * Returns number of queries executed.
100
     *
101
     * @return int
102
     */
103
    public function getQueryCount()
104
    {
105
        return $this->count;
106
    }
107
108
    /**
109
     * Returns information about executed queries.
110
     *
111
     * Eg. keys:
112
     *      'body'    - Request body.
113
     *      'method'  - HTTP method.
114
     *      'uri'     - Uri request was sent.
115
     *      'time'    - Time client took to respond.
116
     *
117
     * @return array
118
     */
119
    public function getQueries()
120
    {
121
        return $this->queries;
122
    }
123
124
    /**
125
     * @return array
126
     */
127
    public function getManagers()
128
    {
129
        if (is_array(reset($this->managers))) {
130
            foreach ($this->managers as $name => &$manager) {
131
                $manager = $name === 'default' ? 'es.manager' : sprintf('es.manager.%s', $name);
132
            }
133
        }
134
135
        return $this->managers;
136
    }
137
138
    /**
139
     * @param array $managers
140
     */
141
    public function setManagers($managers)
142
    {
143
        $this->managers = $managers;
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getName()
150
    {
151
        return 'ongr.profiler';
152
    }
153
154
    /**
155
     * Handles passed records.
156
     *
157
     * @param string $route
158
     * @param array  $records
159
     */
160
    private function handleRecords($route, $records)
161
    {
162
        $this->count += count($records) / 2;
163
        $queryBody = '';
164
        foreach ($records as $record) {
165
            // First record will never have context.
166
            if (!empty($record['context'])) {
167
                $this->time += $record['context']['duration'];
168
                $this->addQuery($route, $record, $queryBody);
169
            } else {
170
                $position = strpos($record['message'], ' -d');
171
                $queryBody = $position !== false ? substr($record['message'], $position + 3) : '';
172
            }
173
        }
174
    }
175
176
    /**
177
     * Adds query to collected data array.
178
     *
179
     * @param string $route
180
     * @param array  $record
181
     * @param string $queryBody
182
     */
183
    private function addQuery($route, $record, $queryBody)
184
    {
185
        parse_str(parse_url($record['context']['uri'], PHP_URL_QUERY), $httpParameters);
186
        $body = json_decode(trim($queryBody, " '\r\t\n"));
187
        $this->queries[$route][] = array_merge(
188
            [
189
                'body' => $body !== null ? json_encode($body, JSON_PRETTY_PRINT) : '',
190
                'method' => $record['context']['method'],
191
                'httpParameters' => $httpParameters,
192
                'time' => $record['context']['duration'] * 1000,
193
            ],
194
            array_diff_key(parse_url($record['context']['uri']), array_flip(['query']))
195
        );
196
    }
197
198
    /**
199
     * Returns route name from request.
200
     *
201
     * @param Request $request
202
     *
203
     * @return string
204
     */
205
    private function getRoute(Request $request)
206
    {
207
        $route = $request->attributes->get('_route');
208
209
        return empty($route) ? self::UNDEFINED_ROUTE : $route;
210
    }
211
}
212