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

ProfilePlugin::handleRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
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 ProfilePlugin implements Plugin
11
{
12
    /**
13
     * @var Plugin
14
     */
15
    private $plugin;
16
17
    /**
18
     * @var Collector
19
     */
20
    private $collector;
21
22
    /**
23
     * @var Formatter
24
     */
25
    private $formatter;
26
27
    /**
28
     * @var ProfileFactory
29
     */
30
    private $factory;
31
32
    /**
33
     * @var string
34
     */
35
    private $pluginName;
36
37
    /**
38
     * @param Plugin         $plugin
39
     * @param Collector      $collector
40
     * @param Formatter      $formatter
41
     * @param ProfileFactory $factory
42
     * @param string         $pluginName
43
     */
44
    public function __construct(Plugin $plugin, Collector $collector, Formatter $formatter, ProfileFactory $factory, $pluginName)
45
    {
46
        $this->plugin = $plugin;
47
        $this->collector = $collector;
48
        $this->formatter = $formatter;
49
        $this->factory = $factory;
50
        $this->pluginName = $pluginName;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
57
    {
58
        $profile = $this->factory->createProfile();
59
        $profile->setPlugin($this->pluginName);
60
        $profile->setRequest($this->formatter->formatRequest($request));
61
62
        $this->collector->getCurrentStack()->addProfile($profile);
63
64
        return $this->plugin->handleRequest($request, $next, $first)->then(function (ResponseInterface $response) use ($profile) {
65
            $profile->setResponse($this->formatter->formatResponse($response));
66
67
            return $response;
68
        }, function (Exception $exception) use ($profile) {
69
            $profile->setFailed(true);
70
            $profile->setResponse($this->formatter->formatException($exception));
71
72
            throw $exception;
73
        });
74
    }
75
}
76