Permalink
Browse files

Fixing RequesHandler::prefers(). It was previously entirely wrong.

It took the ordered list of accept types, and blindly assumed
the first in the list was the most preferred.  This is an incorrect
assumption to make, as all types with the same q value are equal.

- Using CakeRequest::parseAccept() to access only the most preferred
content types.
- Using in_array() to check for the desired type.
- Updating tests for RequestHandler.
  • Loading branch information...
1 parent e2f48b4 commit bb3a1d546b0ca573be9c46976623686782fb7042 @markstory markstory committed Aug 31, 2011
View
19 lib/Cake/Controller/Component/RequestHandlerComponent.php
@@ -468,14 +468,17 @@ public function requestedWith($type = null) {
* @see RequestHandlerComponent::setContent()
*/
public function prefers($type = null) {
- $accepts = $this->accepts();
+ $acceptRaw = $this->request->parseAccept();
+
+ if (empty($acceptRaw)) {
+ return $this->ext;
+ }
+ $accepts = array_shift($acceptRaw);
+ $accepts = $this->mapType($accepts);
if ($type == null) {
- if (empty($this->ext)) {
- if (is_array($accepts)) {
- return $accepts[0];
- }
- return $accepts;
+ if (empty($this->ext) && !empty($accepts)) {
+ return $accepts[0];
}
return $this->ext;
}
@@ -484,9 +487,9 @@ public function prefers($type = null) {
if (count($types) === 1) {
if (!empty($this->ext)) {
- return ($types[0] == $this->ext);
+ return in_array($this->ext, $types);
}
- return ($types[0] == $accepts[0]);
+ return in_array($types[0], $accepts);
}
$intersect = array_values(array_intersect($accepts, $types));
View
8 lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php
@@ -333,8 +333,8 @@ public function testRenderAs() {
public function testRenderAsWithAttachment() {
$this->RequestHandler->request = $this->getMock('CakeRequest');
$this->RequestHandler->request->expects($this->any())
- ->method('accepts')
- ->will($this->returnValue(array('application/xml')));
+ ->method('parseAccept')
+ ->will($this->returnValue(array('1.0' => array('application/xml'))));
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download', 'charset'));
$this->RequestHandler->response->expects($this->at(0))
@@ -387,8 +387,8 @@ public function testRespondAsWithAttachment() {
$this->RequestHandler->request = $this->getMock('CakeRequest');
$this->RequestHandler->request->expects($this->once())
- ->method('accepts')
- ->will($this->returnValue(array('application/xml')));
+ ->method('parseAccept')
+ ->will($this->returnValue(array('1.0' => array('application/xml'))));
$this->RequestHandler->response->expects($this->once())->method('download')
->with('myfile.xml');

0 comments on commit bb3a1d5

Please sign in to comment.