Completed
Push — master ( 599e7d...9d208e )
by Tobias
10:32
created

ProfileClient   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 79.45%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 11
dl 0
loc 189
ccs 58
cts 73
cp 0.7945
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A collectRequestInformations() 0 9 1
A collectResponseInformations() 0 6 1
A collectExceptionInformations() 0 9 2
A getStopwatchEventName() 0 12 2
A __construct() 0 11 3
A sendAsyncRequest() 0 45 4
A doSendRequest() 0 30 4
1
<?php
2
3
namespace Http\HttplugBundle\Collector;
4
5
use Http\Client\Common\FlexibleHttpClient;
6
use Http\Client\Common\VersionBridgeClient;
7
use Http\Client\Exception\HttpException;
8
use Http\Client\HttpAsyncClient;
9
use Http\Client\HttpClient;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Symfony\Component\Stopwatch\Stopwatch;
13
use Symfony\Component\Stopwatch\StopwatchEvent;
14
15
/**
16
 * The ProfileClient decorates any client that implement both HttpClient and HttpAsyncClient interfaces to gather target
17
 * url and response status code.
18
 *
19
 * @author Fabien Bourigault <[email protected]>
20
 *
21
 * @internal
22
 */
23
class ProfileClient implements HttpClient, HttpAsyncClient
24
{
25
    use VersionBridgeClient;
26
27
    /**
28
     * @var HttpClient|HttpAsyncClient
29
     */
30
    private $client;
31
32
    /**
33
     * @var Collector
34
     */
35
    private $collector;
36
37
    /**
38
     * @var Formatter
39
     */
40
    private $formatter;
41
42
    /**
43
     * @var Stopwatch
44
     */
45
    private $stopwatch;
46
47
    /**
48
     * @var array
49
     */
50
    private $eventNames = [];
51
52
    /**
53
     * @param HttpClient|HttpAsyncClient $client    The client to profile. Client must implement HttpClient or
54
     *                                              HttpAsyncClient interface.
55
     * @param Collector                  $collector
56 19
     * @param Formatter                  $formatter
57
     * @param Stopwatch                  $stopwatch
58 19
     */
59
    public function __construct($client, Collector $collector, Formatter $formatter, Stopwatch $stopwatch)
60
    {
61
        if (!($client instanceof HttpClient && $client instanceof HttpAsyncClient)) {
62 19
            $client = new FlexibleHttpClient($client);
63 19
        }
64 19
65 19
        $this->client = $client;
66 19
        $this->collector = $collector;
67
        $this->formatter = $formatter;
68
        $this->stopwatch = $stopwatch;
69
    }
70
71 3
    /**
72
     * {@inheritdoc}
73 3
     */
74 3
    public function sendAsyncRequest(RequestInterface $request)
75 3
    {
76
        $activateStack = true;
77
        $stack = $this->collector->getActiveStack();
78
        if (null === $stack) {
79
            //When using a discovered client not wrapped in a PluginClient, we don't have a stack from StackPlugin. So
80
            //we create our own stack and activate it!
81
            $stack = new Stack('Default', $this->formatter->formatRequest($request));
82
            $this->collector->addStack($stack);
83
            $this->collector->activateStack($stack);
84 3
            $activateStack = false;
85 3
        }
86
87 3
        $this->collectRequestInformations($request, $stack);
88 2
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
89
90 2
        $onFulfilled = function (ResponseInterface $response) use ($event, $stack) {
91 3
            $this->collectResponseInformations($response, $event, $stack);
92
            $event->stop();
93 3
94 1
            return $response;
95
        };
96 1
97 3
        $onRejected = function (\Exception $exception) use ($event, $stack) {
98
            $this->collectExceptionInformations($exception, $event, $stack);
99 3
            $event->stop();
100
101
            throw $exception;
102 3
        };
103
104 3
        $this->collector->deactivateStack($stack);
105 3
106
        try {
107 3
            return $this->client->sendAsyncRequest($request)->then($onFulfilled, $onRejected);
0 ignored issues
show
Bug introduced by
The method sendAsyncRequest does only exist in Http\Client\HttpAsyncClient, but not in Http\Client\HttpClient.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
108
        } catch (\Exception $e) {
109
            $event->stop();
110
111
            throw $e;
112
        } finally {
113
            if ($activateStack) {
114
                //We only activate the stack when created by the StackPlugin.
115 3
                $this->collector->activateStack($stack);
116
            }
117 3
        }
118 3
    }
119
120
    protected function doSendRequest(RequestInterface $request)
121
    {
122
        $stack = $this->collector->getActiveStack();
123
        if (null === $stack) {
124
            //When using a discovered client not wrapped in a PluginClient, we don't have a stack from StackPlugin. So
125 3
            //we create our own stack but don't activate it.
126 3
            $stack = new Stack('Default', $this->formatter->formatRequest($request));
127
            $this->collector->addStack($stack);
128
        }
129 3
130 3
        $this->collectRequestInformations($request, $stack);
131
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
132 3
133
        try {
134
            $response = $this->client->sendRequest($request);
0 ignored issues
show
Bug introduced by
The method sendRequest does only exist in Http\Client\HttpClient, but not in Http\Client\HttpAsyncClient.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
135
            $this->collectResponseInformations($response, $event, $stack);
136
137
            return $response;
138
        } catch (\Exception $e) {
139
            $this->collectExceptionInformations($e, $event, $stack);
140
141
            throw $e;
142 3
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
143
            $this->collectExceptionInformations($e, $event, $stack);
144
145
            throw $e;
146
        } finally {
147
            $event->stop();
148
        }
149
    }
150 6
151
    /**
152 6
     * @param RequestInterface $request
153 6
     * @param Stack            $stack
154 6
     */
155 6
    private function collectRequestInformations(RequestInterface $request, Stack $stack)
156 6
    {
157 6
        $stack->setRequestTarget($request->getRequestTarget());
158 6
        $stack->setRequestMethod($request->getMethod());
159
        $stack->setRequestScheme($request->getUri()->getScheme());
160
        $stack->setRequestHost($request->getUri()->getHost());
161
        $stack->setClientRequest($this->formatter->formatRequest($request));
162
        $stack->setCurlCommand($this->formatter->formatAsCurlCommand($request));
163
    }
164
165 5
    /**
166
     * @param ResponseInterface $response
167 5
     * @param StopwatchEvent    $event
168 5
     * @param Stack             $stack
169 5
     */
170 5
    private function collectResponseInformations(ResponseInterface $response, StopwatchEvent $event, Stack $stack)
171
    {
172
        $stack->setDuration($event->getDuration());
173
        $stack->setResponseCode($response->getStatusCode());
174
        $stack->setClientResponse($this->formatter->formatResponse($response));
175
    }
176
177 1
    /**
178
     * @param \Exception     $exception
179 1
     * @param StopwatchEvent $event
180
     * @param Stack          $stack
181
     */
182
    private function collectExceptionInformations(\Exception $exception, StopwatchEvent $event, Stack $stack)
183 1
    {
184 1
        if ($exception instanceof HttpException) {
185 1
            $this->collectResponseInformations($exception->getResponse(), $event, $stack);
186
        }
187
188
        $stack->setDuration($event->getDuration());
189
        $stack->setClientException($this->formatter->formatException($exception));
190
    }
191
192
    /**
193
     * Generates the event name.
194 6
     *
195
     * @param RequestInterface $request
196 6
     *
197
     * @return string
198 6
     */
199
    private function getStopwatchEventName(RequestInterface $request)
200
    {
201 6
        $name = sprintf('%s %s', $request->getMethod(), $request->getUri());
202
203
        if (isset($this->eventNames[$name])) {
204 6
            $name .= sprintf(' [#%d]', ++$this->eventNames[$name]);
205
        } else {
206
            $this->eventNames[$name] = 1;
207
        }
208
209
        return $name;
210
    }
211
}
212