LoggerSubscriber::onRequestErrored()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Ivory Http Adapter package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\HttpAdapter\Event\Subscriber;
13
14
use Ivory\HttpAdapter\Event\Events;
15
use Ivory\HttpAdapter\Event\Formatter\FormatterInterface;
16
use Ivory\HttpAdapter\Event\MultiRequestCreatedEvent;
17
use Ivory\HttpAdapter\Event\MultiRequestErroredEvent;
18
use Ivory\HttpAdapter\Event\MultiRequestSentEvent;
19
use Ivory\HttpAdapter\Event\RequestCreatedEvent;
20
use Ivory\HttpAdapter\Event\RequestErroredEvent;
21
use Ivory\HttpAdapter\Event\RequestSentEvent;
22
use Ivory\HttpAdapter\Event\Timer\TimerInterface;
23
use Ivory\HttpAdapter\HttpAdapterException;
24
use Ivory\HttpAdapter\HttpAdapterInterface;
25
use Ivory\HttpAdapter\Message\InternalRequestInterface;
26
use Ivory\HttpAdapter\Message\ResponseInterface;
27
use Psr\Log\LoggerInterface;
28
29
/**
30
 * @author GeLo <[email protected]>
31
 */
32
class LoggerSubscriber extends AbstractFormatterSubscriber
33
{
34
    /**
35
     * @var LoggerInterface
36
     */
37
    private $logger;
38
39
    /**
40
     * @param LoggerInterface         $logger
41
     * @param FormatterInterface|null $formatter
42
     * @param TimerInterface|null     $timer
43
     */
44 63
    public function __construct(
45
        LoggerInterface $logger,
46
        FormatterInterface $formatter = null,
47
        TimerInterface $timer = null
48
    ) {
49 63
        parent::__construct($formatter, $timer);
50
51 63
        $this->logger = $logger;
52 63
    }
53
54
    /**
55
     * @return LoggerInterface
56
     */
57 18
    public function getLogger()
58
    {
59 18
        return $this->logger;
60
    }
61
62
    /**
63
     * @param RequestCreatedEvent $event
64
     */
65 18
    public function onRequestCreated(RequestCreatedEvent $event)
66
    {
67 18
        $event->setRequest($this->getTimer()->start($event->getRequest()));
68 18
    }
69
70
    /**
71
     * @param RequestSentEvent $event
72
     */
73 9
    public function onRequestSent(RequestSentEvent $event)
74
    {
75 9
        $event->setRequest($this->debug($event->getHttpAdapter(), $event->getRequest(), $event->getResponse()));
0 ignored issues
show
Bug introduced by Eric GELOEN
It seems like $event->getResponse() can be null; however, debug() 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...
76 9
    }
77
78
    /**
79
     * @param RequestErroredEvent $event
80
     */
81 9
    public function onRequestErrored(RequestErroredEvent $event)
82
    {
83 9
        $event->getException()->setRequest($this->error($event->getHttpAdapter(), $event->getException()));
84 9
    }
85
86
    /**
87
     * @param MultiRequestCreatedEvent $event
88
     */
89 18
    public function onMultiRequestCreated(MultiRequestCreatedEvent $event)
90
    {
91 18
        foreach ($event->getRequests() as $request) {
92 18
            $event->removeRequest($request);
93 18
            $event->addRequest($this->getTimer()->start($request));
94 14
        }
95 18
    }
96
97
    /**
98
     * @param MultiRequestSentEvent $event
99
     */
100 9 View Code Duplication
    public function onMultiRequestSent(MultiRequestSentEvent $event)
0 ignored issues
show
Duplication introduced by Sági-Kazár Márk
This method seems to be duplicated in 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...
101
    {
102 9
        foreach ($event->getResponses() as $response) {
103 9
            $request = $this->debug($event->getHttpAdapter(), $response->getParameter('request'), $response);
104
105 9
            $event->removeResponse($response);
106 9
            $event->addResponse($response->withParameter('request', $request));
0 ignored issues
show
Compatibility introduced by Eric GELOEN
$response->withParameter('request', $request) of type object<Ivory\HttpAdapter...ssage\MessageInterface> is not a sub-type of object<Ivory\HttpAdapter...sage\ResponseInterface>. It seems like you assume a child interface of the interface Ivory\HttpAdapter\Message\MessageInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
107 7
        }
108 9
    }
109
110
    /**
111
     * @param MultiRequestErroredEvent $event
112
     */
113 9
    public function onMultiResponseErrored(MultiRequestErroredEvent $event)
114
    {
115 9
        foreach ($event->getExceptions() as $exception) {
116 9
            $exception->setRequest($this->error($event->getHttpAdapter(), $exception));
117 7
        }
118 9
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 9 View Code Duplication
    public static function getSubscribedEvents()
0 ignored issues
show
Duplication introduced by Eric GELOEN
This method seems to be duplicated in 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...
124
    {
125
        return [
126 9
            Events::REQUEST_CREATED       => ['onRequestCreated', 100],
127 7
            Events::REQUEST_SENT          => ['onRequestSent', 100],
128 7
            Events::REQUEST_ERRORED       => ['onRequestErrored', 100],
129 7
            Events::MULTI_REQUEST_CREATED => ['onMultiRequestCreated', 100],
130 7
            Events::MULTI_REQUEST_SENT    => ['onMultiRequestSent', 100],
131 7
            Events::MULTI_REQUEST_ERRORED => ['onMultiResponseErrored', 100],
132 7
        ];
133
    }
134
135
    /**
136
     * @param HttpAdapterInterface     $httpAdapter
137
     * @param InternalRequestInterface $request
138
     * @param ResponseInterface        $response
139
     *
140
     * @return InternalRequestInterface
141
     */
142 18
    private function debug(
143
        HttpAdapterInterface $httpAdapter,
144
        InternalRequestInterface $request,
145
        ResponseInterface $response
146
    ) {
147 18
        $request = $this->getTimer()->stop($request);
148
149 18
        $this->logger->debug(
150 14
            sprintf(
151 18
                'Send "%s %s" in %.2f ms.',
152 18
                $request->getMethod(),
153 18
                (string) $request->getUri(),
154 18
                $request->getParameter(TimerInterface::TIME)
155 14
            ),
156
            [
157 18
                'adapter'  => $httpAdapter->getName(),
158 18
                'request'  => $this->getFormatter()->formatRequest($request),
159 18
                'response' => $this->getFormatter()->formatResponse($response),
160
            ]
161 14
        );
162
163 18
        return $request;
164
    }
165
166
    /**
167
     * @param HttpAdapterInterface $httpAdapter
168
     * @param HttpAdapterException $exception
169
     *
170
     * @return InternalRequestInterface
171
     */
172 18
    private function error(HttpAdapterInterface $httpAdapter, HttpAdapterException $exception)
173
    {
174 18
        $request = $this->getTimer()->stop($exception->getRequest());
0 ignored issues
show
Bug introduced by Eric GELOEN
It seems like $exception->getRequest() can be null; however, stop() 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...
175
176 18
        $this->logger->error(
177 14
            sprintf(
178 18
                'Unable to send "%s %s".',
179 18
                $exception->getRequest()->getMethod(),
180 18
                (string) $exception->getRequest()->getUri()
181 14
            ),
182
            [
183 18
                'adapter'   => $httpAdapter->getName(),
184 18
                'exception' => $this->getFormatter()->formatException($exception),
185 18
                'request'   => $this->getFormatter()->formatRequest($request),
186 18
                'response'  => $exception->hasResponse()
187 18
                    ? $this->getFormatter()->formatResponse($exception->getResponse())
0 ignored issues
show
Bug introduced by Eric GELOEN
It seems like $exception->getResponse() can be null; however, formatResponse() 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...
188 14
                    : null,
189
            ]
190 14
        );
191
192 18
        return $request;
193
    }
194
}
195