Skip to content

Commit

Permalink
Add getCookie() and replace cookie()
Browse files Browse the repository at this point in the history
This method is more consistent with getData() and getQuery() in that it
supports dotted paths and default values.
  • Loading branch information
markstory committed Nov 11, 2016
1 parent e7c2469 commit 3e6954c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
15 changes: 14 additions & 1 deletion src/Http/ServerRequest.php
Expand Up @@ -1389,7 +1389,7 @@ protected function _parseAcceptWithQualifier($header)
*
* @param string|null $name Query string variable name or null to read all.
* @return string|array|null The value being read
* @deprecated 3.4.0 Use getQuery() instead.
* @deprecated 3.4.0 Use getQuery() and withQueryParams() instead.
*/
public function query($name = null)
{
Expand Down Expand Up @@ -1542,6 +1542,7 @@ public function input($callback = null, ...$args)
*
* @param string $key The key you want to read.
* @return null|string Either the cookie value, or null if the value doesn't exist.
* @deprecated 3.4.0 Use getCookie() instead.
*/
public function cookie($key)
{
Expand All @@ -1552,6 +1553,18 @@ public function cookie($key)
return null;
}

/**
* Read cookie data from the request's cookie data.
*
* @param string $key The key you want to read.
* @param string $default The default value if the cookie is not set.
* @return null|string Either the cookie value, or null if the value doesn't exist.
*/
public function getCookie($key, $default = null)
{
return Hash::get($this->cookies, $key, $default);
}

/**
* Get all the cookie data from the request.
*
Expand Down
20 changes: 14 additions & 6 deletions tests/TestCase/Network/RequestTest.php
Expand Up @@ -3009,18 +3009,26 @@ public function testIsRequested()
*
* @return void
*/
public function testCookie()
public function testGetCookie()
{
$request = new Request([
'cookies' => [
'testing' => 'A value in the cookie'
'testing' => 'A value in the cookie',
'user' => [
'remember' => '1'
]
]
]);
$result = $request->cookie('testing');
$this->assertEquals('A value in the cookie', $result);
$this->assertEquals('A value in the cookie', $request->cookie('testing'));
$this->assertEquals('A value in the cookie', $request->getCookie('testing'));

$this->assertNull($request->cookie('not there'));
$this->assertNull($request->getCookie('not there'));
$this->assertSame('default', $request->getCookie('not there', 'default'));

$result = $request->cookie('not there');
$this->assertNull($result);
$this->assertSame('1', $request->getCookie('user.remember'));
$this->assertSame('1', $request->getCookie('user.remember', 'default'));
$this->assertSame('default', $request->getCookie('user.not there', 'default'));
}

/**
Expand Down

0 comments on commit 3e6954c

Please sign in to comment.