Browse Source

Allow extra cookies when building the cookie header

Allowing extra cookies to be added will make the client and stream
adapters much simpler, and co-locates all the cookie handling code.
Mark Story 9 years ago
parent
commit
5052abb890

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

@@ -177,9 +177,11 @@ class CookieCollection implements IteratorAggregate, Countable
      * when this method is called will be applied to the request.
      *
      * @param \Psr\Http\Message\RequestInterface $request The request to update.
+     * @param array $extraCookies Associative array of additional cookies to add into the request. This
+     *   is useful when you have cookie data from outside the collection you want to send.
      * @return \Psr\Http\Message\RequestInterface An updated request.
      */
-    public function addToRequest(RequestInterface $request)
+    public function addToRequest(RequestInterface $request, array $extraCookies = [])
     {
         $uri = $request->getUri();
         $cookies = $this->findMatchingCookies(
@@ -187,12 +189,13 @@ class CookieCollection implements IteratorAggregate, Countable
             $uri->getHost(),
             $uri->getPath()
         );
+        $cookies = array_merge($cookies, $extraCookies);
         $cookiePairs = [];
         foreach ($cookies as $key => $value) {
-            $cookiePairs[] = sprintf("%s=%s", urlencode($key), urlencode($value));
+            $cookiePairs[] = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
         }
 
-        return $request->withAddedHeader('Cookie', implode('; ', $cookiePairs));
+        return $request->withHeader('Cookie', implode('; ', $cookiePairs));
     }
 
     /**

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

@@ -348,6 +348,27 @@ class CookieCollectionTest extends TestCase
     }
 
     /**
+     * Test adding cookies from the collection to request.
+     *
+     * @return void
+     */
+    public function testAddToRequestExtraCookies()
+    {
+        $collection = new CookieCollection();
+        $collection = $collection
+            ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
+            ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
+            ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
+        $request = new ClientRequest('http://example.com/api');
+        $request = $collection->addToRequest($request, ['b' => 'B']);
+        $this->assertSame('api=A; b=B', $request->getHeaderLine('Cookie'));
+
+        $request = new ClientRequest('http://example.com/api');
+        $request = $collection->addToRequest($request, ['api' => 'custom']);
+        $this->assertSame('api=custom', $request->getHeaderLine('Cookie'), 'Extra cookies overwrite values in jar');
+    }
+
+    /**
      * Test adding cookies ignores leading dot
      *
      * @return void