Completed
Push — master ( 720695...de9ede )
by Fabien
14:35
created

ProfileClient   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 71.43%

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 9
dl 0
loc 190
ccs 60
cts 84
cp 0.7143
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 3
B sendAsyncRequest() 0 40 3
B sendRequest() 0 30 4
A collectRequestInformations() 0 9 1
A collectResponseInformations() 0 6 1
A collectExceptionInformations() 0 9 2
A getStopwatchEventName() 0 12 2
1
<?php
2
3
namespace Http\HttplugBundle\Collector;
4
5
use Http\Client\Common\FlexibleHttpClient;
6
use Http\Client\Exception\HttpException;
7
use Http\Client\HttpAsyncClient;
8
use Http\Client\HttpClient;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Symfony\Component\Stopwatch\Stopwatch;
12
use Symfony\Component\Stopwatch\StopwatchEvent;
13
14
/**
15
 * The ProfileClient decorates any client that implement both HttpClient and HttpAsyncClient interfaces to gather target
16
 * url and response status code.
17
 *
18
 * @author Fabien Bourigault <[email protected]>
19
 *
20
 * @internal
21
 */
22
class ProfileClient implements HttpClient, HttpAsyncClient
23
{
24
    /**
25
     * @var HttpClient|HttpAsyncClient
26
     */
27
    private $client;
28
29
    /**
30
     * @var Collector
31
     */
32
    private $collector;
33
34
    /**
35
     * @var Formatter
36
     */
37
    private $formatter;
38
39
    /**
40
     * @var Stopwatch
41
     */
42
    private $stopwatch;
43
44
    /**
45
     * @var array
46
     */
47
    private $eventNames = [];
48
49
    /**
50
     * @param HttpClient|HttpAsyncClient $client    The client to profile. Client must implement both HttpClient and
51
     *                                              HttpAsyncClient interfaces.
52
     * @param Collector                  $collector
53
     * @param Formatter                  $formatter
54
     * @param Stopwatch                  $stopwatch
55
     */
56 16
    public function __construct($client, Collector $collector, Formatter $formatter, Stopwatch $stopwatch)
57
    {
58 16
        if (!($client instanceof HttpClient && $client instanceof HttpAsyncClient)) {
59
            throw new \RuntimeException(sprintf(
60
                '%s first argument must implement %s and %s. Consider using %s.',
61
                    __METHOD__,
62
                    HttpClient::class,
63
                    HttpAsyncClient::class,
64
                    FlexibleHttpClient::class
65
            ));
66
        }
67 16
        $this->client = $client;
68 16
        $this->collector = $collector;
69 16
        $this->formatter = $formatter;
70 16
        $this->stopwatch = $stopwatch;
71 16
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 3
    public function sendAsyncRequest(RequestInterface $request)
77
    {
78 3
        $activateStack = true;
79 3
        $stack = $this->collector->getActiveStack();
80 3
        if ($stack === null) {
81
            //When using a discovered client not wrapped in a PluginClient, we don't have a stack from StackPlugin. So
82
            //we create our own stack and activate it!
83
            $stack = new Stack('Default', $this->formatter->formatRequest($request));
84
            $this->collector->addStack($stack);
85
            $this->collector->activateStack($stack);
86
            $activateStack = false;
87
        }
88
89 3
        $this->collectRequestInformations($request, $stack);
90 3
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
91
92
        $onFulfilled = function (ResponseInterface $response) use ($event, $stack) {
93 2
            $this->collectResponseInformations($response, $event, $stack);
94
95 2
            return $response;
96 3
        };
97
98 3
        $onRejected = function (\Exception $exception) use ($event, $stack) {
99 1
            $this->collectExceptionInformations($exception, $event, $stack);
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
        } finally {
109 3
            $event->stop();
110 3
            if ($activateStack) {
111
                //We only activate the stack when created by the StackPlugin.
112 3
                $this->collector->activateStack($stack);
113 3
            }
114 3
        }
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 3
    public function sendRequest(RequestInterface $request)
121
    {
122 3
        $stack = $this->collector->getActiveStack();
123 3
        if ($stack === null) {
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 3
        $this->collectRequestInformations($request, $stack);
131 3
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
132
133
        try {
134 3
            $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 3
            $this->collectResponseInformations($response, $event, $stack);
136
137 3
            return $response;
138
        } catch (\Exception $e) {
139
            $this->collectExceptionInformations($e, $event, $stack);
140
141
            throw $e;
142
        } 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 3
            $event->stop();
148 3
        }
149
    }
150
151
    /**
152
     * @param RequestInterface $request
153
     * @param Stack            $stack
154
     */
155 6
    private function collectRequestInformations(RequestInterface $request, Stack $stack)
156
    {
157 6
        $stack->setRequestTarget($request->getRequestTarget());
158 6
        $stack->setRequestMethod($request->getMethod());
159 6
        $stack->setRequestScheme($request->getUri()->getScheme());
160 6
        $stack->setRequestHost($request->getUri()->getHost());
161 6
        $stack->setClientRequest($this->formatter->formatRequest($request));
162 6
        $stack->setCurlCommand($this->formatter->formatAsCurlCommand($request));
163 6
    }
164
165
    /**
166
     * @param ResponseInterface $response
167
     * @param StopwatchEvent    $event
168
     * @param Stack             $stack
169
     */
170 5
    private function collectResponseInformations(ResponseInterface $response, StopwatchEvent $event, Stack $stack)
171
    {
172 5
        $stack->setDuration($event->getDuration());
173 5
        $stack->setResponseCode($response->getStatusCode());
174 5
        $stack->setClientResponse($this->formatter->formatResponse($response));
175 5
    }
176
177
    /**
178
     * @param \Exception     $exception
179
     * @param StopwatchEvent $event
180
     * @param Stack          $stack
181
     */
182 1
    private function collectExceptionInformations(\Exception $exception, StopwatchEvent $event, Stack $stack)
183
    {
184 1
        if ($exception instanceof HttpException) {
185
            $this->collectResponseInformations($exception->getResponse(), $event, $stack);
186
        }
187
188 1
        $stack->setDuration($event->getDuration());
189 1
        $stack->setClientException($this->formatter->formatException($exception));
190 1
    }
191
192
    /**
193
     * Generates the event name.
194
     *
195
     * @param RequestInterface $request
196
     *
197
     * @return string
198
     */
199 6
    private function getStopwatchEventName(RequestInterface $request)
200
    {
201 6
        $name = sprintf('%s %s', $request->getMethod(), $request->getUri());
202
203 6
        if (isset($this->eventNames[$name])) {
204
            $name .= sprintf(' [#%d]', ++$this->eventNames[$name]);
205
        } else {
206 6
            $this->eventNames[$name] = 1;
207
        }
208
209 6
        return $name;
210
    }
211
}
212