Completed
Push — master ( 33ed6a...1627ff )
by Tobias
06:48
created

StackPlugin::handleRequest()   B

Complexity

Conditions 1
Paths 2

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 15
cts 15
cp 1
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 15
nc 2
nop 3
crap 1
1
<?php
2
3
namespace Http\HttplugBundle\Collector;
4
5
use Exception;
6
use Http\Client\Common\Plugin;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * The StackPlugin must be used as first Plugin in a client stack. It's used to detect when a new request start by
12
 * creating a new Stack and pushing it to the Collector.
13
 *
14
 * @author Fabien Bourigault <[email protected]>
15
 *
16
 * @internal
17
 */
18
class StackPlugin implements Plugin
19
{
20
    /**
21
     * @var Collector
22
     */
23
    private $collector;
24
25
    /**
26
     * @var string
27
     */
28
    private $client;
29
30
    /**
31
     * @var Formatter
32
     */
33
    private $formatter;
34
35
    /**
36
     * @param Collector $collector
37
     * @param Formatter $formatter
38
     * @param string    $client
39
     */
40 10
    public function __construct(Collector $collector, Formatter $formatter, $client)
41
    {
42 10
        $this->collector = $collector;
43 10
        $this->formatter = $formatter;
44 10
        $this->client = $client;
45 10
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 7
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
51
    {
52 7
        $stack = new Stack($this->client, $this->formatter->formatRequest($request));
53
54 7
        $this->collector->addStack($stack);
55 7
        $this->collector->activateStack($stack);
56
57
        $onFulfilled = function (ResponseInterface $response) use ($stack) {
58 4
            $stack->setResponse($this->formatter->formatResponse($response));
59
60 4
            return $response;
61 7
        };
62
63 7
        $onRejected = function (Exception $exception) use ($stack) {
64 1
            $stack->setResponse($this->formatter->formatException($exception));
65 1
            $stack->setFailed(true);
66
67 1
            throw $exception;
68 7
        };
69
70
        try {
71 7
            return $next($request)->then($onFulfilled, $onRejected);
72
        } finally {
73 7
            $this->collector->deactivateStack($stack);
74 7
        }
75
    }
76
}
77