Browse Source

Require that cookies added to the Client have a path and a domain.

Robert Pustułka 8 years ago
parent
commit
ce75980299
2 changed files with 41 additions and 1 deletions
  1. 4 0
      src/Http/Client.php
  2. 37 1
      tests/TestCase/Http/ClientTest.php

+ 4 - 0
src/Http/Client.php

@@ -20,6 +20,7 @@ use Cake\Http\Client\CookieCollection;
 use Cake\Http\Client\Request;
 use Cake\Http\Cookie\CookieInterface;
 use Cake\Utility\Hash;
+use InvalidArgumentException;
 use Zend\Diactoros\Uri;
 
 /**
@@ -192,6 +193,9 @@ class Client
      */
     public function addCookie(CookieInterface $cookie)
     {
+        if (!$cookie->getDomain() || !$cookie->getPath()) {
+            throw new InvalidArgumentException('Cookie must have a domain and a path set.');
+        }
         $this->_cookies = $this->_cookies->add($cookie);
 
         return $this;

+ 37 - 1
tests/TestCase/Http/ClientTest.php

@@ -644,7 +644,43 @@ class ClientTest extends TestCase
     public function testAddCookie()
     {
         $client = new Client();
-        $cookie = new Cookie('foo');
+        $cookie = new Cookie('foo', '', null, '/', 'example.com');
+
+        $this->assertFalse($client->cookies()->has('foo'));
+
+        $client->addCookie($cookie);
+        $this->assertTrue($client->cookies()->has('foo'));
+    }
+
+    /**
+     * Test addCookie() method without a domain.
+     *
+     * @return void
+     * @expectedException InvalidArgumentException
+     * @expectedExceptionMessage Cookie must have a domain and a path set.
+     */
+    public function testAddCookieWithoutDomain()
+    {
+        $client = new Client();
+        $cookie = new Cookie('foo', '', null, '/', '');
+
+        $this->assertFalse($client->cookies()->has('foo'));
+
+        $client->addCookie($cookie);
+        $this->assertTrue($client->cookies()->has('foo'));
+    }
+
+    /**
+     * Test addCookie() method without a path.
+     *
+     * @return void
+     * @expectedException InvalidArgumentException
+     * @expectedExceptionMessage Cookie must have a domain and a path set.
+     */
+    public function testAddCookieWithoutPath()
+    {
+        $client = new Client();
+        $cookie = new Cookie('foo', '', null, '', 'example.com');
 
         $this->assertFalse($client->cookies()->has('foo'));