diff --git a/spec/StopwatchPluginSpec.php b/spec/StopwatchPluginSpec.php index ba80ba6..755bcf8 100644 --- a/spec/StopwatchPluginSpec.php +++ b/spec/StopwatchPluginSpec.php @@ -7,10 +7,10 @@ use Http\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; use Psr\Http\Message\UriInterface; use Symfony\Component\Stopwatch\Stopwatch; use PhpSpec\ObjectBehavior; +use Symfony\Component\Stopwatch\StopwatchEvent; class StopwatchPluginSpec extends ObjectBehavior { @@ -29,14 +29,21 @@ function it_is_a_plugin() $this->shouldImplement('Http\Client\Common\Plugin'); } - function it_records_event(Stopwatch $stopwatch, RequestInterface $request, ResponseInterface $response, UriInterface $uri) - { + function it_records_event( + Stopwatch $stopwatch, + RequestInterface $request, + ResponseInterface $response, + UriInterface $uri, + StopwatchEvent $event + ) { $request->getMethod()->willReturn('GET'); $request->getUri()->willReturn($uri); $uri->__toString()->willReturn('http://foo.com/bar'); + $event->getDuration()->willReturn(123); $stopwatch->start('GET http://foo.com/bar', 'php_http.request')->shouldBeCalled(); - $stopwatch->stop('GET http://foo.com/bar', 'php_http.request')->shouldBeCalled(); + $stopwatch->stop('GET http://foo.com/bar')->shouldBeCalled()->willReturn($event); + $response->withHeader('X-Duration', 123)->shouldBeCalled(); $next = function (RequestInterface $request) use ($response) { return new FulfilledPromise($response->getWrappedObject()); @@ -52,7 +59,7 @@ function it_records_event_on_error(Stopwatch $stopwatch, RequestInterface $reque $uri->__toString()->willReturn('http://foo.com/bar'); $stopwatch->start('GET http://foo.com/bar', 'php_http.request')->shouldBeCalled(); - $stopwatch->stop('GET http://foo.com/bar', 'php_http.request')->shouldBeCalled(); + $stopwatch->stop('GET http://foo.com/bar')->shouldBeCalled(); $next = function (RequestInterface $request) { return new RejectedPromise(new NetworkException('', $request)); diff --git a/src/StopwatchPlugin.php b/src/StopwatchPlugin.php index 8e3054a..f7e37c6 100644 --- a/src/StopwatchPlugin.php +++ b/src/StopwatchPlugin.php @@ -16,6 +16,7 @@ final class StopwatchPlugin implements Plugin { const CATEGORY = 'php_http.request'; + const HEADER = 'X-Duration'; /** * @var Stopwatch @@ -39,11 +40,11 @@ public function handleRequest(RequestInterface $request, callable $next, callabl $this->stopwatch->start($eventName, self::CATEGORY); return $next($request)->then(function (ResponseInterface $response) use ($eventName) { - $this->stopwatch->stop($eventName, self::CATEGORY); + $event = $this->stopwatch->stop($eventName); - return $response; + return $response->withHeader(self::HEADER, $event->getDuration()); }, function (Exception $exception) use ($eventName) { - $this->stopwatch->stop($eventName, self::CATEGORY); + $this->stopwatch->stop($eventName); throw $exception; });