From 4f3cbea82416c05cf8569970acff3f612bad1d14 Mon Sep 17 00:00:00 2001 From: NGUEREZA Tony Date: Mon, 20 Nov 2023 09:09:36 +0100 Subject: [PATCH] Add headers support in HTTP Exception --- src/Http/Exception/HttpException.php | 31 ++++++++++++++++++- .../Command/VendorPublishCommandTest.php | 2 +- tests/Http/Exception/HttpExceptionTest.php | 13 ++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/Http/Exception/HttpException.php b/src/Http/Exception/HttpException.php index c112f60..b24bb72 100644 --- a/src/Http/Exception/HttpException.php +++ b/src/Http/Exception/HttpException.php @@ -61,21 +61,30 @@ class HttpException extends Exception */ protected string $description = ''; + /** + * Additional headers to add into error response + * @var array + */ + protected array $headers = []; + /** * Create new instance * @param ServerRequestInterface $request * @param string $message * @param int $code * @param Throwable|null $previous + * @param array $headers */ public function __construct( ServerRequestInterface $request, string $message = '', int $code = 0, - ?Throwable $previous = null + ?Throwable $previous = null, + array $headers = [] ) { parent::__construct($message, $code, $previous); $this->request = $request; + $this->headers = $headers; } /** @@ -128,4 +137,24 @@ public function setDescription(string $description): self return $this; } + + /** + * Return headers + * @return array + */ + public function getHeaders(): array + { + return $this->headers; + } + + /** + * Set the headers + * @param array $headers + * @return $this + */ + public function setHeaders(array $headers): self + { + $this->headers = $headers; + return $this; + } } diff --git a/tests/Console/Command/VendorPublishCommandTest.php b/tests/Console/Command/VendorPublishCommandTest.php index 0639057..8339cc4 100644 --- a/tests/Console/Command/VendorPublishCommandTest.php +++ b/tests/Console/Command/VendorPublishCommandTest.php @@ -118,7 +118,7 @@ public function testExecutePublishOnlySomeFiles(): void 'templates', $rootDir->url() ] - + ] ]); $writer = $this->getWriterInstance(); diff --git a/tests/Http/Exception/HttpExceptionTest.php b/tests/Http/Exception/HttpExceptionTest.php index dae3099..b36eac1 100644 --- a/tests/Http/Exception/HttpExceptionTest.php +++ b/tests/Http/Exception/HttpExceptionTest.php @@ -28,4 +28,17 @@ public function testTitleAndDescription(): void $this->assertEquals('exception description', $o->getDescription()); $this->assertEquals('exception title', $o->getTitle()); } + + public function testHeaders(): void + { + $request = $this->getMockInstance(ServerRequest::class); + $o = new HttpException($request); + $o->setHeaders(['foo' => 'bar']); + + $headers = $o->getHeaders(); + + $this->assertCount(1, $headers); + $this->assertArrayHasKey('foo', $headers); + $this->assertEquals('bar', $headers['foo']); + } }