Skip to content

Commit

Permalink
Fixing RequesHandler::prefers(). It was previously entirely wrong.
Browse files Browse the repository at this point in the history
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
markstory committed Aug 31, 2011
1 parent e2f48b4 commit bb3a1d5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
19 changes: 11 additions & 8 deletions lib/Cake/Controller/Component/RequestHandlerComponent.php
Expand Up @@ -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;
}
Expand All @@ -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));
Expand Down
Expand Up @@ -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))
Expand Down Expand Up @@ -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');
Expand Down

0 comments on commit bb3a1d5

Please sign in to comment.