Browse Source

Add a factory method for building a CookieCollection from a header.

Mark Story 9 years ago
parent
commit
f319be4eac

+ 15 - 3
src/Http/Cookie/CookieCollection.php

@@ -52,6 +52,19 @@ class CookieCollection implements IteratorAggregate, Countable
     }
 
     /**
+     * Create a Cookie Collection from an array of Set-Cookie Headers
+     *
+     * @param array $header The array of set-cookie header values.
+     * @return static
+     */
+    public static function createFromHeader(array $header)
+    {
+        $cookies = static::parseSetCookieHeader($header);
+
+        return new CookieCollection($cookies);
+    }
+
+    /**
      * Get the number of cookies in the collection.
      *
      * @return int
@@ -251,8 +264,7 @@ class CookieCollection implements IteratorAggregate, Countable
         $host = $uri->getHost();
         $path = $uri->getPath() ?: '/';
 
-        $header = $response->getHeader('Set-Cookie');
-        $cookies = $this->parseSetCookieHeader($header);
+        $cookies = static::parseSetCookieHeader($response->getHeader('Set-Cookie'));
         $cookies = $this->setRequestDefaults($cookies, $host, $path);
         $new = clone $this;
         foreach ($cookies as $cookie) {
@@ -293,7 +305,7 @@ class CookieCollection implements IteratorAggregate, Countable
      * @param array $values List of Set-Cookie Header values.
      * @return \Cake\Http\Cookie\Cookie[] An array of cookie objects
      */
-    protected function parseSetCookieHeader($values)
+    protected static function parseSetCookieHeader($values)
     {
         $cookies = [];
         foreach ($values as $value) {

+ 19 - 0
tests/TestCase/Http/Cookie/CookieCollectionTest.php

@@ -403,4 +403,23 @@ class CookieCollectionTest extends TestCase
         $request = $collection->addToRequest($request);
         $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
     }
+
+    /**
+     * test createFromHeader() building cookies from a header string.
+     *
+     * @return void
+     */
+    public function testCreateFromHeader()
+    {
+        $header = [
+            'http=name; HttpOnly; Secure;',
+            'expires=expiring; Expires=Wed, 15-Jun-2022 10:22:22; Path=/api; HttpOnly; Secure;',
+            'expired=expired; Expires=Wed, 15-Jun-2015 10:22:22;',
+        ];
+        $cookies = CookieCollection::createFromHeader($header);
+        $this->assertCount(3, $cookies);
+        $this->assertTrue($cookies->has('http'));
+        $this->assertTrue($cookies->has('expires'));
+        $this->assertTrue($cookies->has('expired'), 'Expired cookies should be present');
+    }
 }