Passed
Push — master ( 654348...8ec1ee )
by Dāvis
03:00
created

StopwatchMiddleware   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __invoke() 0 19 2
1
<?php
2
3
namespace Sludio\HelperBundle\Guzzle\GuzzleHttp\Middleware;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Symfony\Component\Stopwatch\Stopwatch;
8
9
class StopwatchMiddleware
10
{
11
    private $stopwatch;
12
    private $increments = [];
13
14
    public function __construct(Stopwatch $stopwatch)
15
    {
16
        $this->stopwatch = $stopwatch;
17
    }
18
19
    public function __invoke(callable $handler)
20
    {
21
        return function(RequestInterface $request, array $options) use ($handler) {
22
            $key = sprintf('%s %s', $request->getMethod(), (string)$request->getUri());
23
24
            if (!isset($this->increments[$key])) {
25
                $this->increments[$key] = 1;
26
            } else {
27
                ++$this->increments[$key];
28
29
                $key .= ' ('.$this->increments[$key].')';
30
            }
31
32
            $this->stopwatch->start($key);
33
34
            return $handler($request, $options)->then(function(ResponseInterface $response) use ($key) {
35
                $this->stopwatch->stop($key);
36
37
                return $response;
38
            });
39
        };
40
    }
41
}