Completed
Push — master ( f507c1...3a0383 )
by Tobias
06:33
created

ProfileClient::getStopwatchEventName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 6
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 13
    public function __construct($client, Collector $collector, Formatter $formatter, Stopwatch $stopwatch)
57
    {
58 13
        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
        $this->client = $client;
68
        $this->collector = $collector;
69
        $this->formatter = $formatter;
70
        $this->stopwatch = $stopwatch;
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function sendAsyncRequest(RequestInterface $request)
77
    {
78
        $stack = $this->collector->getActiveStack();
79
80
        $this->collectRequestInformations($request, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 78 can be null; however, Http\HttplugBundle\Colle...ctRequestInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
81
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
82
83
        $onFulfilled = function (ResponseInterface $response) use ($event, $stack) {
84
            $this->collectResponseInformations($response, $event, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 78 can be null; however, Http\HttplugBundle\Colle...tResponseInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
85
86
            return $response;
87
        };
88
89
        $onRejected = function (\Exception $exception) use ($event, $stack) {
90
            $this->collectExceptionInformations($exception, $event, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 78 can be null; however, Http\HttplugBundle\Colle...ExceptionInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
91
92
            throw $exception;
93
        };
94
95
        $this->collector->deactivateStack($stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 78 can be null; however, Http\HttplugBundle\Colle...ctor::deactivateStack() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
96
97
        try {
98
            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...
99
        } finally {
100
            $event->stop();
101
            $this->collector->activateStack($stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 78 can be null; however, Http\HttplugBundle\Colle...lector::activateStack() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
102
        }
103
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108
    public function sendRequest(RequestInterface $request)
109
    {
110
        $stack = $this->collector->getActiveStack();
111
112
        $this->collectRequestInformations($request, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 110 can be null; however, Http\HttplugBundle\Colle...ctRequestInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
113
        $event = $this->stopwatch->start($this->getStopwatchEventName($request));
114
115
        try {
116
            $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...
117
            $this->collectResponseInformations($response, $event, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 110 can be null; however, Http\HttplugBundle\Colle...tResponseInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
118
119
            return $response;
120
        } catch (\Exception $e) {
121
            $this->collectExceptionInformations($e, $event, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 110 can be null; however, Http\HttplugBundle\Colle...ExceptionInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
122
123
            throw $e;
124
        } 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...
125
            $this->collectExceptionInformations($e, $event, $stack);
0 ignored issues
show
Bug introduced by
It seems like $stack defined by $this->collector->getActiveStack() on line 110 can be null; however, Http\HttplugBundle\Colle...ExceptionInformations() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
126
127
            throw $e;
128
        } finally {
129
            $event->stop();
130
        }
131
    }
132
133
    /**
134
     * @param RequestInterface $request
135
     * @param Stack            $stack
136
     */
137
    private function collectRequestInformations(RequestInterface $request, Stack $stack)
138
    {
139
        $stack->setRequestTarget($request->getRequestTarget());
140
        $stack->setRequestMethod($request->getMethod());
141
        $stack->setRequestScheme($request->getUri()->getScheme());
142
        $stack->setRequestHost($request->getUri()->getHost());
143
        $stack->setClientRequest($this->formatter->formatRequest($request));
144
        $stack->setCurlCommand($this->formatter->formatAsCurlCommand($request));
145
    }
146
147
    /**
148
     * @param ResponseInterface $response
149
     * @param StopwatchEvent    $event
150
     * @param Stack             $stack
151
     */
152
    private function collectResponseInformations(ResponseInterface $response, StopwatchEvent $event, Stack $stack)
153
    {
154
        $stack->setDuration($event->getDuration());
155
        $stack->setResponseCode($response->getStatusCode());
156
        $stack->setClientResponse($this->formatter->formatResponse($response));
157
    }
158
159
    /**
160
     * @param \Exception     $exception
161
     * @param StopwatchEvent $event
162
     * @param Stack          $stack
163
     */
164
    private function collectExceptionInformations(\Exception $exception, StopwatchEvent $event, Stack $stack)
165
    {
166
        if ($exception instanceof HttpException) {
167
            $this->collectResponseInformations($exception->getResponse(), $event, $stack);
168
        }
169
170
        $stack->setDuration($event->getDuration());
171
        $stack->setClientException($this->formatter->formatException($exception));
172
    }
173
174
    /**
175
     * Generates the event name.
176
     *
177
     * @param RequestInterface $request
178
     *
179
     * @return string
180
     */
181
    private function getStopwatchEventName(RequestInterface $request)
182
    {
183
        $name = sprintf('%s %s', $request->getMethod(), $request->getUri());
184
185
        if (isset($this->eventNames[$name])) {
186
            $name .= sprintf(' [#%d]', ++$this->eventNames[$name]);
187
        } else {
188
            $this->eventNames[$name] = 1;
189
        }
190
191
        return $name;
192
    }
193
}
194