Skip to content

Commit

Permalink
Moving accepts() into CakeRequest.
Browse files Browse the repository at this point in the history
Adding test cases.
  • Loading branch information
markstory committed Jul 1, 2010
1 parent 8b847cf commit ea0f9cf
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions cake/libs/cake_request.php
Expand Up @@ -410,6 +410,7 @@ public function referer($local = false) {
* @param string $name The method called
* @param array $params Array of parameters for the method call
* @return mixed
* @throws BadMethodCallException when an invalid method is called.
*/
public function __call($name, $params) {
if (strpos($name, 'is') === 0) {
Expand Down Expand Up @@ -545,6 +546,29 @@ public function header($name) {
}
return false;
}

/**
* Find out which content types the client accepts or check if they accept a
* particular type of content.
*
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
* provided type.
*/
public function accepts($type = null) {
$acceptTypes = explode(',', $this->header('accept'));
foreach ($acceptTypes as $i => $accepted) {
if (strpos($accepted, ';') !== false) {
list($accepted, $prefValue) = explode(';', $accepted);
$acceptTypes[$i] = $accepted;
}
}
if ($type === null) {
return $acceptTypes;
}
return in_array($type, $acceptTypes);
}

/**
* Array access read implementation
*
Expand Down
22 changes: 22 additions & 0 deletions cake/tests/cases/libs/cake_request.test.php
Expand Up @@ -668,6 +668,28 @@ function testHeader() {
$this->assertEquals($_SERVER['HTTP_USER_AGENT'], $request->header('User-Agent'));
}

/**
* test accepts() with and without parameters
*
* @return void
*/
function testAccepts() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml;q=0.9,application/xhtml+xml,text/html,text/plain,image/png';
$request = new CakeRequest('/', false);

$result = $request->accepts();
$expected = array(
'text/xml', 'application/xml', 'application/xhtml+xml', 'text/html', 'text/plain', 'image/png'
);
$this->assertEquals($expected, $result, 'Content types differ.');

$result = $request->accepts('text/html');
$this->assertTrue($result);

$result = $request->accepts('image/gif');
$this->assertFalse($result);
}

/**
* testBaseUrlAndWebrootWithModRewrite method
*
Expand Down

0 comments on commit ea0f9cf

Please sign in to comment.