diff --git a/src/ApiProblem.php b/src/ApiProblem.php index e97a43d..d85be77 100644 --- a/src/ApiProblem.php +++ b/src/ApiProblem.php @@ -140,6 +140,14 @@ public function __construct($status, $detail, $type = null, $title = null, array } } + // Ensure a valid HTTP status + if (! is_numeric($status) + || ($status < 100) + || ($status > 599) + ) { + $status = 500; + } + $this->status = $status; $this->detail = $detail; $this->title = $title; diff --git a/src/Listener/ApiProblemListener.php b/src/Listener/ApiProblemListener.php index 06009fb..c7f6e66 100644 --- a/src/Listener/ApiProblemListener.php +++ b/src/Listener/ApiProblemListener.php @@ -157,21 +157,13 @@ public function onDispatchError(MvcEvent $e) // Marshall an ApiProblem and view model based on the exception $exception = $e->getParam('exception'); - if ($exception instanceof ProblemExceptionInterface) { - $problem = new ApiProblem($exception->getCode(), $exception); - } elseif ($exception instanceof \Exception) { - $status = $exception->getCode(); - if (0 === $status) { - $status = 500; - } - $problem = new ApiProblem($status, $exception); - } else { + if (! $exception instanceof \Exception) { // If it's not an exception, do not know what to do. return; } $e->stopPropagation(); - $response = new ApiProblemResponse($problem); + $response = new ApiProblemResponse(new ApiProblem($exception->getCode(), $exception)); $e->setResponse($response); return $response; } diff --git a/test/ApiProblemResponseTest.php b/test/ApiProblemResponseTest.php index 847941f..b587fb3 100644 --- a/test/ApiProblemResponseTest.php +++ b/test/ApiProblemResponseTest.php @@ -63,6 +63,6 @@ public function testComposeApiProblemIsAccessible() public function testOverridesReasonPhraseIfStatusCodeIsUnknown() { $response = new ApiProblemResponse(new ApiProblem(7, 'Random error')); - $this->assertContains('Unknown', $response->getReasonPhrase()); + $this->assertContains('Internal Server Error', $response->getReasonPhrase()); } } diff --git a/test/ApiProblemTest.php b/test/ApiProblemTest.php index c0e13ec..515dc05 100644 --- a/test/ApiProblemTest.php +++ b/test/ApiProblemTest.php @@ -215,4 +215,26 @@ public function testUsesAdditionalDetailsFromExceptionWhenProvided() $this->assertArrayHasKey('foo', $payload); $this->assertEquals('bar', $payload['foo']); } + + public function invalidStatusCodes() + { + return array( + '-1' => array(-1), + '0' => array(0), + '7' => array(7), // reported + '14' => array(14), // observed + '600' => array(600), + ); + } + + /** + * @dataProvider invalidStatusCodes + * @group zf-apigility-118 + */ + public function testInvalidHttpStatusCodesAreCastTo500($code) + { + $e = new \Exception('Testing', $code); + $problem = new ApiProblem($code, $e); + $this->assertEquals(500, $problem->status); + } }