From ea0f9cffea2b778fdec939fd842cfa97f413ec1c Mon Sep 17 00:00:00 2001 From: mark_story Date: Wed, 30 Jun 2010 23:25:45 -0400 Subject: [PATCH] Moving accepts() into CakeRequest. Adding test cases. --- cake/libs/cake_request.php | 24 +++++++++++++++++++++ cake/tests/cases/libs/cake_request.test.php | 22 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/cake/libs/cake_request.php b/cake/libs/cake_request.php index 7b075e784..f39431a5a 100644 --- a/cake/libs/cake_request.php +++ b/cake/libs/cake_request.php @@ -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 * diff --git a/cake/tests/cases/libs/cake_request.test.php b/cake/tests/cases/libs/cake_request.test.php index d221a6f50..d4ce32a26 100644 --- a/cake/tests/cases/libs/cake_request.test.php +++ b/cake/tests/cases/libs/cake_request.test.php @@ -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 *