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
|
4 |
|
public function __construct(Collector $collector, Formatter $formatter, $client) |
41
|
|
|
{ |
42
|
4 |
|
$this->collector = $collector; |
43
|
4 |
|
$this->formatter = $formatter; |
44
|
4 |
|
$this->client = $client; |
45
|
4 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
3 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
51
|
|
|
{ |
52
|
3 |
|
$stack = new Stack( |
53
|
3 |
|
$this->client, |
54
|
3 |
|
$request->getMethod(), |
55
|
3 |
|
$request->getRequestTarget(), |
56
|
3 |
|
$this->formatter->formatRequest($request) |
57
|
3 |
|
); |
58
|
|
|
|
59
|
3 |
|
$this->collector->addStack($stack); |
60
|
|
|
|
61
|
|
|
return $next($request)->then(function (ResponseInterface $response) use ($stack) { |
62
|
1 |
|
$stack->setResponse($this->formatter->formatResponse($response)); |
63
|
1 |
|
$stack->setResponseCode($response->getStatusCode()); |
64
|
|
|
|
65
|
1 |
|
if ($response->hasHeader('X-Duration')) { |
66
|
|
|
$stack->setDuration(array_sum($response->getHeader('X-Duration'))); |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
return $response; |
70
|
3 |
|
}, function (Exception $exception) use ($stack) { |
71
|
1 |
|
$stack->setResponse($this->formatter->formatException($exception)); |
72
|
1 |
|
$stack->setFailed(true); |
73
|
|
|
|
74
|
1 |
|
throw $exception; |
75
|
3 |
|
}); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|