From b517bd912afa5aa1033ce434d7138641fd6c31ab Mon Sep 17 00:00:00 2001 From: Dylan McDonald Date: Fri, 7 Apr 2017 14:03:48 -0600 Subject: [PATCH] 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 :+1: to @Nyholm * added null test to Cookie Jar Test * added better null protection * disallowed null names in getCookieByName * changed null to empty string --- src/Cookie/CookieJar.php | 19 +++++++++++++++++++ tests/Cookie/CookieJarTest.php | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/Cookie/CookieJar.php b/src/Cookie/CookieJar.php index 7fffd30e..e510d7e0 100644 --- a/src/Cookie/CookieJar.php +++ b/src/Cookie/CookieJar.php @@ -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) { diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index 5c25a9a6..3526f950 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -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 */