diff --git a/src/Response.php b/src/Response.php index 7edab23587..178639ddb5 100644 --- a/src/Response.php +++ b/src/Response.php @@ -88,6 +88,16 @@ class Response extends AbstractMessage implements ResponseInterface const STATUS_CODE_599 = 599; /**#@-*/ + /** + * @internal + */ + const MIN_STATUS_CODE_VALUE = 100; + + /** + * @internal + */ + const MAX_STATUS_CODE_VALUE = 599; + /** * @var array Recommended Reason Phrases */ @@ -279,12 +289,16 @@ public function getCookie() */ public function setStatusCode($code) { - $const = get_class($this) . '::STATUS_CODE_' . $code; - if (! is_numeric($code) || ! defined($const)) { - $code = is_scalar($code) ? $code : gettype($code); + if (! is_numeric($code) + || is_float($code) + || $code < static::MIN_STATUS_CODE_VALUE + || $code > static::MAX_STATUS_CODE_VALUE + ) { throw new Exception\InvalidArgumentException(sprintf( - 'Invalid status code provided: "%s"', - $code + 'Invalid status code "%s"; must be an integer between %d and %d, inclusive', + is_scalar($code) ? $code : gettype($code), + static::MIN_STATUS_CODE_VALUE, + static::MAX_STATUS_CODE_VALUE )); } diff --git a/test/ResponseTest.php b/test/ResponseTest.php index 6d1f48abef..b62aaa15e4 100644 --- a/test/ResponseTest.php +++ b/test/ResponseTest.php @@ -107,12 +107,24 @@ public function testRequestCanSetHeaders() $this->assertSame($headers, $response->getHeaders()); } - public function testResponseCanSetStatusCode() + public function validStatusCode() + { + for ($i = 100; $i <= 599; ++$i) { + yield $i => [$i]; + } + } + + /** + * @dataProvider validStatusCode + * + * @param int $statusCode + */ + public function testResponseCanSetStatusCode($statusCode) { $response = new Response(); - $this->assertEquals(200, $response->getStatusCode()); - $response->setStatusCode('303'); - $this->assertEquals(303, $response->getStatusCode()); + $this->assertSame(200, $response->getStatusCode()); + $response->setStatusCode($statusCode); + $this->assertSame($statusCode, $response->getStatusCode()); } public function testResponseSetStatusCodeThrowsExceptionOnInvalidCode() @@ -142,7 +154,7 @@ public function testResponseSetCustomStatusCodeThrowsExceptionOnInvalidCode() { $response = new Response(); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid status code provided: "foo"'); + $this->expectExceptionMessage('Invalid status code "foo"; must be an integer between 100 and 599, inclusive'); $response->setStatusCode('foo'); } @@ -540,8 +552,6 @@ public function testGetVersion() public function testUnknownCode() { $responseStr = $this->readResponse('response_unknown'); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid status code provided: "550"'); $response = Response::fromString($responseStr); $this->assertEquals(550, $response->getStatusCode()); }