Passed
Push — master ( 654348...8ec1ee )
by Dāvis
03:00
created

GuzzleCollector::collect()   C

Complexity

Conditions 9
Paths 21

Size

Total Lines 63
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 37
nc 21
nop 3
dl 0
loc 63
rs 6.6149
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Sludio\HelperBundle\Guzzle\DataCollector;
4
5
use Sludio\HelperBundle\Guzzle\GuzzleHttp\History\History;
6
use Sludio\HelperBundle\Guzzle\GuzzleHttp\Middleware\CacheMiddleware;
7
use Sludio\HelperBundle\Guzzle\GuzzleHttp\Middleware\MockMiddleware;
8
use GuzzleHttp\Exception\RequestException;
9
use Psr\Http\Message\StreamInterface;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
13
14
class GuzzleCollector extends DataCollector
15
{
16
    const MAX_BODY_SIZE = 0x10000;
17
18
    private $maxBodySize;
19
    private $history;
20
    private $curlFormatter = null;
21
22
    /**
23
     * Constructor.
24
     *
25
     * @param int $maxBodySize The max body size to store in the profiler storage
26
     */
27
    public function __construct($maxBodySize = self::MAX_BODY_SIZE, History $history = null)
28
    {
29
        $this->maxBodySize = $maxBodySize;
30
        $this->history = $history ?: new History();
31
32
        if (class_exists(\Namshi\Cuzzle\Formatter\CurlFormatter::class)) {
33
            $this->curlFormatter = new \Namshi\Cuzzle\Formatter\CurlFormatter();
34
        }
35
36
        $this->data = [];
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function collect(Request $request, Response $response, \Exception $exception = null)
43
    {
44
        $data = [];
45
46
        foreach ($this->history as $request) {
47
            /* @var \Psr\Http\Message\RequestInterface $request */
48
            $transaction = $this->history[$request];
49
            /* @var \Psr\Http\Message\ResponseInterface $response */
50
            $response = $transaction['response'];
51
            /* @var \Exception $error */
52
            $error = $transaction['error'];
53
            /* @var array $info */
54
            $info = $transaction['info'];
55
56
            $req = [
57
                'request' => [
58
                    'method' => $request->getMethod(),
59
                    'version' => $request->getProtocolVersion(),
60
                    'headers' => $request->getHeaders(),
61
                    'body' => $this->cropContent($request->getBody()),
62
                ],
63
                'info' => $info,
64
                'uri' => urldecode($request->getUri()),
65
                'httpCode' => 0,
66
                'error' => null,
67
            ];
68
69
            if ($this->curlFormatter && $request->getBody()->getSize() <= $this->maxBodySize) {
70
                $req['curl'] = $this->curlFormatter->format($request);
71
            }
72
73
            if ($response) {
74
                $req['response'] = [
75
                    'reasonPhrase' => $response->getReasonPhrase(),
76
                    'headers' => $response->getHeaders(),
77
                    'body' => $this->cropContent($response->getBody()),
78
                ];
79
80
                $req['httpCode'] = $response->getStatusCode();
81
82
                if ($response->hasHeader(CacheMiddleware::DEBUG_HEADER)) {
83
                    $req['cache'] = $response->getHeaderLine(CacheMiddleware::DEBUG_HEADER);
84
                }
85
86
                if ($response->hasHeader(MockMiddleware::DEBUG_HEADER)) {
87
                    $req['mock'] = $response->getHeaderLine(MockMiddleware::DEBUG_HEADER);
88
                }
89
            }
90
91
            if ($error && $error instanceof RequestException) {
92
                $req['error'] = [
93
                    'message' => $error->getMessage(),
94
                    'line' => $error->getLine(),
95
                    'file' => $error->getFile(),
96
                    'code' => $error->getCode(),
97
                    'trace' => $error->getTraceAsString(),
98
                ];
99
            }
100
101
            $data[] = $req;
102
        }
103
104
        $this->data = $data;
105
    }
106
107
    private function cropContent(StreamInterface $stream = null)
108
    {
109
        if (null === $stream) {
110
            return '';
111
        }
112
113
        if ($stream->getSize() <= $this->maxBodySize) {
114
            return (string)$stream;
115
        }
116
117
        $stream->seek(0);
118
119
        return '(partial content)'.$stream->read($this->maxBodySize).'(...)';
120
    }
121
122
    public function getErrors()
123
    {
124
        return array_filter($this->data, function($call) {
125
            return 0 === $call['httpCode'] || $call['httpCode'] >= 400;
126
        });
127
    }
128
129
    public function getTotalTime()
130
    {
131
        return array_sum(array_map(function($call) {
132
                return isset($call['info']['total_time']) ? $call['info']['total_time'] : 0;
133
            }, $this->data));
134
    }
135
136
    public function getCalls()
137
    {
138
        return $this->data;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function getName()
145
    {
146
        return 'guzzle';
147
    }
148
}