Completed
Push — master ( b6d7de...4a06e6 )
by Thibaud
8s
created

PhraseanetSDKDataCollector::sanitizeRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 16
ccs 0
cts 12
cp 0
rs 9.4285
cc 2
eloc 12
nc 2
nop 1
crap 6
1
<?php
2
3
namespace PhraseanetSDK\Profiler;
4
5
use Guzzle\Plugin\History\HistoryPlugin;
6
use Guzzle\Http\Message\RequestInterface;
7
use Guzzle\Http\Message\Response as GuzzleResponse;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
11
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
12
13
/**
14
 * GuzzleDataCollector.
15
 *
16
 * @author Ludovic Fleury <[email protected]>
17
 */
18
class PhraseanetSDKDataCollector extends DataCollector
19
{
20
    /**
21
     * @var HistoryPlugin
22
     */
23
    private $profiler;
24
25 2
    public function __construct(HistoryPlugin $profiler)
26
    {
27 2
        $this->profiler = $profiler;
28 2
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function collect(Request $request, Response $response, \Exception $exception = null)
34
    {
35
        $this->data = array(
36
            'calls'       => array(),
37
            'cache_hits'  => 0,
38
            'error_count' => 0,
39
            'methods'     => array(),
40
            'total_time'  => 0,
41
        );
42
43
        foreach ($this->profiler as $call) {
44
            $this->parseCall($request, $response, $call);
45
        }
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getCalls()
52
    {
53
        return isset($this->data['calls']) ? $this->data['calls'] : array();
54
    }
55
56
    /**
57
     * @return int
58
     */
59
    public function countErrors()
60
    {
61
        return isset($this->data['error_count']) ? $this->data['error_count'] : 0;
62
    }
63
64
    /**
65
     * @return array
66
     */
67
    public function getMethods()
68
    {
69
        return isset($this->data['methods']) ? $this->data['methods'] : array();
70
    }
71
72
    /**
73
     * @return int
74
     */
75
    public function getTotalTime()
76
    {
77
        return isset($this->data['total_time']) ? $this->data['total_time'] : 0;
78
    }
79
80
    /**
81
     * @return int|void
82
     */
83
    public function getCacheHitRatio()
84
    {
85
        $totalCalls = count($this->getCalls());
86
87
        if (! isset($this->data['cache_hits']) || $totalCalls == 0) {
88
            return 0;
89
        }
90
91
        return $this->data['cache_hits'] * 100 / $totalCalls;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 2
    public function getName()
98
    {
99 2
        return 'phrasea-sdk';
100
    }
101
102
    /**
103
     * @param RequestInterface $request
104
     *
105
     * @return array
106
     */
107
    private function sanitizeRequest(RequestInterface $request)
108
    {
109
        $postParameters = $request instanceof EntityEnclosingRequestInterface ? $request->getPostFields() : null;
110
111
        return array(
112
            'method'           => $request->getMethod(),
113
            'protocol_version' => $request->getProtocolVersion(),
114
            'path'             => $request->getPath(),
115
            'scheme'           => $request->getScheme(),
116
            'host'             => $request->getHost(),
117
            'query'            => $request->getQuery(),
118
            'headers'          => $request->getHeaders()->toArray(),
119
            'query_parameters' => $request->getUrl(true)->getQuery(),
120
            'post_parameters'  => $postParameters,
121
        );
122
    }
123
124
    /**
125
     * @param GuzzleResponse $response
126
     *
127
     * @return array
128
     */
129
    private function sanitizeResponse($response)
130
    {
131
        return array(
132
            'statusCode'   => $response->getStatusCode(),
133
            'reasonPhrase' => $response->getReasonPhrase(),
134
            'headers'      => $response->getHeaders()->toArray(),
0 ignored issues
show
Bug introduced by
The method toArray cannot be called on $response->getHeaders() (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
135
        );
136
    }
137
138
    private function parsePhraseanetResponse($data, $response)
139
    {
140
        if ($response->getStatusCode() !== 200) {
141
            return array();
142
        }
143
144
        $parsed = array(
145
            'metadata' => $data->meta
146
        );
147
148
        if (isset($data->response->offset_start)) {
149
            $pageMaxSize = isset($data->response->available_results) ? $data->response->available_results : '-';
150
            $totalResults = isset($data->response->total_results) ? $data->response->total_results : '-';
151
152
            $pagination = array(
153
                'Offset' => $data->response->offset_start,
154
                'Page size' => $data->response->per_page,
155
                'Page max size' => $pageMaxSize,
156
                'Total results' => $totalResults
157
            );
158
159
            $parsed['pagination'] = $pagination;
160
        }
161
162
        return $parsed;
163
    }
164
165
    /**
166
     * @param Request $request
167
     * @param Response $response
168
     * @param $call
169
     */
170
    protected function parseCall(Request $request, Response $response, $call)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
171
    {
172
        $error = false;
173
        $request = $call;
174
        $response = $request->getResponse();
175
176
        $requestContent = null;
177
        if ($request instanceof EntityEnclosingRequestInterface) {
178
            $requestContent = (string)$request->getBody();
179
        }
180
181
        $time = array(
182
            'total' => $response->getInfo('total_time'),
183
            'connection' => $response->getInfo('connect_time'),
184
        );
185
186
187
        $this->data['total_time'] += $response->getInfo('total_time');
188
189
        if (!isset($this->data['methods'][$request->getMethod()])) {
190
            $this->data['methods'][$request->getMethod()] = 0;
191
        }
192
193
        $this->data['methods'][$request->getMethod()]++;
194
195
        if ($response->isError()) {
196
            $this->data['error_count']++;
197
            $error = true;
198
        }
199
200
        if (substr($response->getHeaders()->get('X-Cache', ''), 0, 3) == 'HIT') {
201
            $this->data['cache_hits'] += 1;
202
        }
203
204
        $decodedBody = json_decode($response->getBody(true));
205
206
        if (!$decodedBody) {
207
            $decodedBody = $response->getBody('true');
208
        }
209
210
        $this->data['calls'][] = array(
211
            'request' => $this->sanitizeRequest($request),
212
            'requestContent' => $requestContent,
213
            'response' => $this->sanitizeResponse($response),
214
            'responseContent' => $decodedBody,
215
            'time' => $time,
216
            'error' => $error,
217
            'phraseanet' => $this->parsePhraseanetResponse($decodedBody, $response)
218
        );
219
    }
220
}
221