Completed
Pull Request — master (#63)
by Thibaud
03:10
created

parsePhraseanetResponse()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 26
ccs 0
cts 15
cp 0
rs 8.439
cc 5
eloc 15
nc 6
nop 2
crap 30
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
            $error = false;
45
            $request = $call;
46
            $response = $request->getResponse();
47
48
            $requestContent = null;
49
            if ($request instanceof EntityEnclosingRequestInterface) {
50
                $requestContent = (string) $request->getBody();
51
            }
52
53
            $time = array(
54
                'total' => $response->getInfo('total_time'),
55
                'connection' => $response->getInfo('connect_time'),
56
            );
57
58
59
            $this->data['total_time'] += $response->getInfo('total_time');
60
61
            if (!isset($this->data['methods'][$request->getMethod()])) {
62
                $this->data['methods'][$request->getMethod()] = 0;
63
            }
64
65
            $this->data['methods'][$request->getMethod()]++;
66
67
            if ($response->isError()) {
68
                $this->data['error_count']++;
69
                $error = true;
70
            }
71
72
            if (substr($response->getHeaders()->get('X-Cache', ''), 0, 3) == 'HIT') {
73
                $this->data['cache_hits'] += 1;
74
            }
75
76
            $decodedBody = json_decode($response->getBody(true));
77
78
            if (! $decodedBody) {
79
                $decodedBody = $response->getBody('true');
80
            }
81
82
            $this->data['calls'][] = array(
83
                'request' => $this->sanitizeRequest($request),
84
                'requestContent' => $requestContent,
85
                'response' => $this->sanitizeResponse($response),
86
                'responseContent' => $decodedBody,
87
                'time' => $time,
88
                'error' => $error,
89
                'phraseanet' => $this->parsePhraseanetResponse($decodedBody, $response)
90
            );
91
        }
92
    }
93
94
    /**
95
     * @return array
96
     */
97
    public function getCalls()
98
    {
99
        return isset($this->data['calls']) ? $this->data['calls'] : array();
100
    }
101
102
    /**
103
     * @return int
104
     */
105
    public function countErrors()
106
    {
107
        return isset($this->data['error_count']) ? $this->data['error_count'] : 0;
108
    }
109
110
    /**
111
     * @return array
112
     */
113
    public function getMethods()
114
    {
115
        return isset($this->data['methods']) ? $this->data['methods'] : array();
116
    }
117
118
    /**
119
     * @return int
120
     */
121
    public function getTotalTime()
122
    {
123
        return isset($this->data['total_time']) ? $this->data['total_time'] : 0;
124
    }
125
126
    /**
127
     * @return int|void
128
     */
129
    public function getCacheHitRatio()
130
    {
131
        $totalCalls = count($this->getCalls());
132
133
        if (! isset($this->data['cache_hits']) || $totalCalls == 0) {
134
            return 0;
135
        }
136
137
        return $this->data['cache_hits'] * 100 / $totalCalls;
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 2
    public function getName()
144
    {
145 2
        return 'phrasea-sdk';
146
    }
147
148
    /**
149
     * @param RequestInterface $request
150
     *
151
     * @return array
152
     */
153
    private function sanitizeRequest(RequestInterface $request)
154
    {
155
        $postParameters = $request instanceof EntityEnclosingRequestInterface ? $request->getPostFields() : null;
156
157
        return array(
158
            'method'           => $request->getMethod(),
159
            'protocol_version' => $request->getProtocolVersion(),
160
            'path'             => $request->getPath(),
161
            'scheme'           => $request->getScheme(),
162
            'host'             => $request->getHost(),
163
            'query'            => $request->getQuery(),
164
            'headers'          => $request->getHeaders()->toArray(),
165
            'query_parameters' => $request->getUrl(true)->getQuery(),
166
            'post_parameters'  => $postParameters,
167
        );
168
    }
169
170
    /**
171
     * @param GuzzleResponse $response
172
     *
173
     * @return array
174
     */
175
    private function sanitizeResponse($response)
176
    {
177
        return array(
178
            'statusCode'   => $response->getStatusCode(),
179
            'reasonPhrase' => $response->getReasonPhrase(),
180
            '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...
181
        );
182
    }
183
184
    private function parsePhraseanetResponse($data, $response)
185
    {
186
        if ($response->getStatusCode() !== 200) {
187
            return array();
188
        }
189
190
        $parsed = array(
191
            'metadata' => $data->meta
192
        );
193
194
        if (isset($data->response->offset_start)) {
195
            $pageMaxSize = isset($data->response->available_results) ? $data->response->available_results : '-';
196
            $totalResults = isset($data->response->total_results) ? $data->response->total_results : '-';
197
198
            $pagination = array(
199
                'Offset' => $data->response->offset_start,
200
                'Page size' => $data->response->per_page,
201
                'Page max size' => $pageMaxSize,
202
                'Total results' => $totalResults
203
            );
204
205
            $parsed['pagination'] = $pagination;
206
        }
207
208
        return $parsed;
209
    }
210
}
211