From fbbf5a152dc58d8574fe72b3d73097c59b50f335 Mon Sep 17 00:00:00 2001 From: Moritz Fain Date: Fri, 16 Mar 2018 15:52:18 +0100 Subject: [PATCH] Added error listeners to RequestHandlerRunner --- src/RequestHandlerRunner.php | 41 +++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/RequestHandlerRunner.php b/src/RequestHandlerRunner.php index b22253e..7b5e67a 100644 --- a/src/RequestHandlerRunner.php +++ b/src/RequestHandlerRunner.php @@ -59,6 +59,11 @@ class RequestHandlerRunner */ private $serverRequestFactory; + /** + * @var callable[] + */ + protected $listeners = []; + public function __construct( RequestHandlerInterface $handler, Emitter\EmitterInterface $emitter, @@ -97,9 +102,43 @@ public function run() : void $this->emitter->emit($response); } - private function emitMarshalServerRequestException(Throwable $exception) : void + /** + * Attach an error listener. + * + * Each listener receives the following two arguments: + * + * - Throwable $error + * - ResponseInterface $response + * + * These instances are all immutable, and the return values of + * listeners are ignored; use listeners for reporting purposes + * only. + */ + public function attachListener(callable $listener) : void + { + if (in_array($listener, $this->listeners, true)) { + return; + } + + $this->listeners[] = $listener; + } + + /** + * Trigger all error listeners. + */ + private function triggerListeners( + \Throwable $error, + ResponseInterface $response + ) : void { + foreach ($this->listeners as $listener) { + $listener($error, $response); + } + } + + public function emitMarshalServerRequestException(Throwable $exception) : void { $response = ($this->serverRequestErrorResponseGenerator)($exception); + $this->triggerListeners($exception, $response); $this->emitter->emit($response); } }