From c097e03d8880fe20b56622a0db24686cb02c1aa6 Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Wed, 25 May 2016 09:22:36 +0100 Subject: [PATCH] Ensure determineContentType() returns a valid result If the acceptable media type in the Accept header is not first in the list, we need to ensure that we return it correctly. Fixes #1892 --- Slim/Handlers/AbstractHandler.php | 2 +- tests/Handlers/AbstractHandlerTest.php | 28 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Slim/Handlers/AbstractHandler.php b/Slim/Handlers/AbstractHandler.php index e3be0ce0b..decdf725c 100644 --- a/Slim/Handlers/AbstractHandler.php +++ b/Slim/Handlers/AbstractHandler.php @@ -43,7 +43,7 @@ protected function determineContentType(ServerRequestInterface $request) $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); if (count($selectedContentTypes)) { - return $selectedContentTypes[0]; + return current($selectedContentTypes); } // handle +json and +xml specially diff --git a/tests/Handlers/AbstractHandlerTest.php b/tests/Handlers/AbstractHandlerTest.php index e68728f52..d19ec4582 100644 --- a/tests/Handlers/AbstractHandlerTest.php +++ b/tests/Handlers/AbstractHandlerTest.php @@ -39,4 +39,32 @@ public function testHalfValidContentType() $this->assertEquals('text/html', $return); } + + /** + * Ensure that an acceptable media-type is found in the Accept header even + * if it's not the first in the list. + */ + public function testAcceptableMediaTypeIsNotFirstInList() + { + $request = $this->getMockBuilder('Slim\Http\Request') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->any()) + ->method('getHeaderLine') + ->willReturn('text/plain,text/html'); + + // provide access to the determineContentType() as it's a protected method + $class = new \ReflectionClass(AbstractHandler::class); + $method = $class->getMethod('determineContentType'); + $method->setAccessible(true); + + // use a mock object here as AbstractHandler cannot be directly instantiated + $abstractHandler = $this->getMockForAbstractClass(AbstractHandler::class); + + // call determineContentType() + $return = $method->invoke($abstractHandler, $request); + + $this->assertEquals('text/html', $return); + } }