1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-24 01:53:58 +01:00

Added convenience method to access a cookie by name (#1318)

* Added convenience method to access a cookie by name

* updated pull request against newest version

* added default null edge case 👍 to @Nyholm

* added null test to Cookie Jar Test

* added better null protection

* disallowed null names in getCookieByName

* changed null to empty string
This commit is contained in:
Dylan McDonald 2017-04-07 14:03:48 -06:00 committed by Tobias Nyholm
parent a1c4a74bf3
commit b517bd912a
2 changed files with 32 additions and 0 deletions

View File

@ -86,6 +86,25 @@ class CookieJar implements CookieJarInterface
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName($name)
{
// don't allow a null name
if($name === null) {
return null;
}
foreach($this->cookies as $cookie) {
if($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) {
return $cookie;
}
}
}
public function toArray()
{
return array_map(function (SetCookie $cookie) {

View File

@ -37,6 +37,19 @@ class CookieJarTest extends \PHPUnit_Framework_TestCase
$this->assertCount(2, $jar);
}
public function testGetsCookiesByName()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$testCookie = $cookies[0];
$this->assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName()));
$this->assertNull($this->jar->getCookieByName("doesnotexist"));
$this->assertNull($this->jar->getCookieByName(""));
}
/**
* Provides test data for cookie cookieJar retrieval
*/