Middleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

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
nc 1
nop 1
crap 1
1
<?php
2
3
namespace GuzzleHttp\Profiling;
4
5
use GuzzleHttp\Exception\RequestException;
6
use GuzzleHttp\Promise\PromiseInterface;
7
use Psr\Http\Client\ClientExceptionInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
class Middleware
12
{
13
    /**
14
     * @var Profiler
15
     */
16
    private $profiler;
17
18
    /**
19
     * Public constructor.
20
     *
21
     * @param Profiler $profiler
22
     */
23 5
    public function __construct(Profiler $profiler)
24
    {
25 5
        $this->profiler = $profiler;
26 5
    }
27
28
    /**
29
     * @param callable $handler
30
     *
31
     * @return callable
32
     */
33 5
    public function __invoke(callable $handler): callable
34
    {
35
        return function(RequestInterface $request, array $options) use ($handler): PromiseInterface {
36
            // Set starting time.
37 4
            $start = microtime(true);
38
39 4
            return $handler($request, $options)
40
                ->then(function(ResponseInterface $response) use ($start, $request) {
41
                    // After
42 1
                    $this->profiler->add($start, microtime(true), $request, $response);
43
44 1
                    return $response;
45
                }, function(ClientExceptionInterface $exception) use ($start, $request) {
46 2
                    $response = $exception instanceof RequestException ? $exception->getResponse() : null;
47 2
                    $this->profiler->add($start, microtime(true), $request, $response);
48
49 2
                    throw $exception;
50 4
                });
51 5
        };
52
    }
53
}
54