ProfileClient::collectRequestInformations()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 8
cts 8
cp 1
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Http\HttplugBundle\Collector;
6
7
use Http\Client\Common\FlexibleHttpClient;
8
use Http\Client\Common\VersionBridgeClient;
9
use Http\Client\Exception\HttpException;
10
use Http\Client\HttpAsyncClient;
11
use Http\Client\HttpClient;
12
use Psr\Http\Client\ClientInterface;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Symfony\Component\Stopwatch\Stopwatch;
16
use Symfony\Component\Stopwatch\StopwatchEvent;
17
18
/**
19
 * The ProfileClient decorates any client that implement both HttpClient and HttpAsyncClient interfaces to gather target
20
 * url and response status code.
21
 *
22
 * @author Fabien Bourigault <[email protected]>
23
 *
24
 * @internal
25
 */
26
class ProfileClient implements HttpClient, HttpAsyncClient
27
{
28
    use VersionBridgeClient;
29
30
    /**
31
     * @var HttpClient|HttpAsyncClient
32
     */
33
    private $client;
34
35
    /**
36
     * @var Collector
37
     */
38
    private $collector;
39
40
    /**
41
     * @var Formatter
42
     */
43
    private $formatter;
44
45
    /**
46
     * @var Stopwatch
47
     */
48
    private $stopwatch;
49
50
    /**
51
     * @var array
52
     */
53
    private $eventNames = [];
54
55
    /**
56
     * @param HttpClient|HttpAsyncClient $client The client to profile. Client must implement HttpClient or
57
     *                                           HttpAsyncClient interface.
58
     */
59 18
    public function __construct($client, Collector $collector, Formatter $formatter, Stopwatch $stopwatch)
60
    {
61 18 View Code Duplication
        if (!(($client instanceof ClientInterface || $client instanceof HttpClient) && $client instanceof HttpAsyncClient)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
62 3
            $client = new FlexibleHttpClient($client);
63
        }
64
65 18
        $this->client = $client;
66 18
        $this->collector = $collector;
67 18
        $this->formatter = $formatter;
68 18
        $this->stopwatch = $stopwatch;
69 18
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 3
    public function sendAsyncRequest(RequestInterface $request)
75
    {
76 3
        $activateStack = true;
77 3
        $stack = $this->collector->getActiveStack();
78 3
        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
            $activateStack = false;
85
        }
86
87 3
        $this->collectRequestInformations($request, $stack);
88 3
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
89
90
        $onFulfilled = function (ResponseInterface $response) use ($event, $stack) {
91 2
            $this->collectResponseInformations($response, $event, $stack);
92 2
            $event->stop();
93
94 2
            return $response;
95 3
        };
96
97
        $onRejected = function (\Exception $exception) use ($event, $stack) {
98 1
            $this->collectExceptionInformations($exception, $event, $stack);
99 1
            $event->stop();
100
101 1
            throw $exception;
102 3
        };
103
104 3
        $this->collector->deactivateStack($stack);
105
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 3
            if ($activateStack) {
114
                //We only activate the stack when created by the StackPlugin.
115 3
                $this->collector->activateStack($stack);
116
            }
117
        }
118
    }
119
120 5
    protected function doSendRequest(RequestInterface $request)
121
    {
122 5
        $stack = $this->collector->getActiveStack();
123 5
        if (null === $stack) {
124
            //When using a discovered client not wrapped in a PluginClient, we don't have a stack from StackPlugin. So
125
            //we create our own stack but don't activate it.
126
            $stack = new Stack('Default', $this->formatter->formatRequest($request));
127
            $this->collector->addStack($stack);
128
        }
129
130 5
        $this->collectRequestInformations($request, $stack);
131 5
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
132
133
        try {
134 5
            $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 4
            $this->collectResponseInformations($response, $event, $stack);
136
137 4
            return $response;
138 1
        } catch (\Exception $e) {
139
            $this->collectExceptionInformations($e, $event, $stack);
140
141
            throw $e;
142 1
        } catch (\Throwable $e) {
143 1
            $this->collectExceptionInformations($e, $event, $stack);
144
145 1
            throw $e;
146
        } finally {
147 5
            $event->stop();
148
        }
149
    }
150
151 8
    private function collectRequestInformations(RequestInterface $request, Stack $stack)
152
    {
153 8
        $stack->setRequestTarget($request->getRequestTarget());
154 8
        $stack->setRequestMethod($request->getMethod());
155 8
        $stack->setRequestScheme($request->getUri()->getScheme());
156 8
        $stack->setRequestHost($request->getUri()->getHost());
157 8
        $stack->setClientRequest($this->formatter->formatRequest($request));
158 8
        $stack->setCurlCommand($this->formatter->formatAsCurlCommand($request));
159 8
    }
160
161 6
    private function collectResponseInformations(ResponseInterface $response, StopwatchEvent $event, Stack $stack)
162
    {
163 6
        $stack->setDuration($event->getDuration());
164 6
        $stack->setResponseCode($response->getStatusCode());
165 6
        $stack->setClientResponse($this->formatter->formatResponse($response));
166 6
    }
167
168 2
    private function collectExceptionInformations(\Throwable $exception, StopwatchEvent $event, Stack $stack)
169
    {
170 2
        if ($exception instanceof HttpException) {
171
            $this->collectResponseInformations($exception->getResponse(), $event, $stack);
172
        }
173
174 2
        $stack->setDuration($event->getDuration());
175 2
        $stack->setClientException($this->formatter->formatException($exception));
176 2
    }
177
178
    /**
179
     * Generates the event name.
180
     *
181
     * @return string
182
     */
183 8
    private function getStopwatchEventName(RequestInterface $request)
184
    {
185 8
        $name = sprintf('%s %s', $request->getMethod(), $request->getUri());
186
187 8
        if (isset($this->eventNames[$name])) {
188
            $name .= sprintf(' [#%d]', ++$this->eventNames[$name]);
189
        } else {
190 8
            $this->eventNames[$name] = 1;
191
        }
192
193 8
        return $name;
194
    }
195
}
196