Completed
Pull Request — master (#128)
by Fabien
10:06
created

StackPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
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
class StackPlugin implements Plugin
11
{
12
    /**
13
     * @var Collector
14
     */
15
    private $collector;
16
17
    /**
18
     * @var string
19
     */
20
    private $client;
21
22
    /**
23
     * @var Formatter
24
     */
25
    private $formatter;
26
27
    /**
28
     * @param Collector $collector
29
     * @param Formatter $formatter
30
     * @param string $client
31
     */
32
    public function __construct(Collector $collector, Formatter $formatter, $client)
33
    {
34
        $this->collector = $collector;
35
        $this->formatter = $formatter;
36
        $this->client = $client;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
43
    {
44
        $stack = new Stack();
45
        $stack->setClient($this->client);
46
        $stack->setRequest($this->formatter->formatRequest($request));
47
48
        $this->collector->addStack($stack);
49
        return $next($request)->then(function (ResponseInterface $response) use ($stack) {
50
            $stack->setResponse($this->formatter->formatResponse($response));
51
52
            return $response;
53
        }, function (Exception $exception) use ($stack) {
54
            $stack->setResponse($this->formatter->formatException($exception));
55
            $stack->setFailed(true);
56
57
            throw $exception;
58
        });
59
    }
60
}
61