Completed
Push — master ( 119f88...a5ef59 )
by Márk
06:54
created

DebugPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Http\HttplugBundle\Collector;
4
5
use Http\Client\Common\Plugin;
6
use Http\Client\Exception;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * A plugin used for log requests and responses. This plugin is executed between each normal plugin.
12
 *
13
 * @author Tobias Nyholm <[email protected]>
14
 */
15
final class DebugPlugin implements Plugin
16
{
17
    /**
18
     * @var DebugPluginCollector
19
     */
20
    private $collector;
21
22
    /**
23
     * @var string
24
     */
25
    private $clientName;
26
27
    /**
28
     * @var int
29
     */
30
    private $depth = -1;
31
32
    /**
33
     * @param DebugPluginCollector $collector
34
     * @param string               $clientName
35
     */
36
    public function __construct(DebugPluginCollector $collector, $clientName)
37
    {
38
        $this->collector = $collector;
39
        $this->clientName = $clientName;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
46
    {
47
        $collector = $this->collector;
48
        $clientName = $this->clientName;
49
        $depth = &$this->depth;
50
51
        $collector->addRequest($request, $clientName, ++$depth);
52
53
        return $next($request)->then(function (ResponseInterface $response) use ($collector, $clientName, &$depth) {
54
            $collector->addResponse($response, $clientName, $depth--);
55
56
            return $response;
57
        }, function (Exception $exception) use ($collector, $clientName, &$depth) {
58
            $collector->addFailure($exception, $clientName, $depth--);
59
60
            throw $exception;
61
        });
62
    }
63
}
64