Moving accepts() into CakeRequest.

Adding test cases.
This commit is contained in:
mark_story 2010-06-30 23:25:45 -04:00
parent 8b847cffef
commit ea0f9cffea
2 changed files with 46 additions and 0 deletions

View file

@ -410,6 +410,7 @@ class CakeRequest implements ArrayAccess {
* @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) {
@ -545,6 +546,29 @@ class CakeRequest implements ArrayAccess {
}
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
*

View file

@ -668,6 +668,28 @@ class CakeRequestTestCase extends CakeTestCase {
$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
*