Completed
Push — master ( fb581e...ebe90c )
by Hannes
03:50 queued 19s
created

Middleware::__invoke()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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