浏览代码

Add Cookie::toArray()

This method belongs here as all the data is here.
Mark Story 9 年之前
父节点
当前提交
f4d5c01b43
共有 3 个文件被更改,包括 47 次插入9 次删除
  1. 1 9
      src/Http/Client/CookieCollection.php
  2. 20 0
      src/Http/Cookie/Cookie.php
  3. 26 0
      tests/TestCase/Http/Cookie/CookieTest.php

+ 1 - 9
src/Http/Client/CookieCollection.php

@@ -78,15 +78,7 @@ class CookieCollection extends BaseCollection
     {
         $out = [];
         foreach ($this->cookies as $cookie) {
-            $out[] = [
-                'name' => $cookie->getName(),
-                'value' => $cookie->getValue(),
-                'path' => $cookie->getPath(),
-                'domain' => $cookie->getDomain(),
-                'secure' => $cookie->isSecure(),
-                'httponly' => $cookie->isHttpOnly(),
-                'expires' => $cookie->getExpiry()
-            ];
+            $out[] = $cookie->toArray();
         }
 
         return $out;

+ 20 - 0
src/Http/Cookie/Cookie.php

@@ -597,6 +597,26 @@ class Cookie implements CookieInterface
     }
 
     /**
+     * Convert the cookie into an array of its properties.
+     *
+     * Primarily useful where backwards compatibility is needed.
+     *
+     * @return array
+     */
+    public function toArray()
+    {
+        return [
+            'name' => $this->getName(),
+            'value' => $this->getValue(),
+            'path' => $this->getPath(),
+            'domain' => $this->getDomain(),
+            'secure' => $this->isSecure(),
+            'httponly' => $this->isHttpOnly(),
+            'expires' => $this->getExpiry()
+        ];
+    }
+
+    /**
      * Implode method to keep keys are multidimensional arrays
      *
      * @param array $array Map of key and values

+ 26 - 0
tests/TestCase/Http/Cookie/CookieTest.php

@@ -521,4 +521,30 @@ class CookieTest extends TestCase
         $cookie = new Cookie('test', 'val', null, '/path', 'example.com');
         $this->assertEquals('test;example.com;/path', $cookie->getId());
     }
+
+    /**
+     * Test toArray
+     *
+     * @return void
+     */
+    public function testToArray()
+    {
+        $date = Chronos::parse('2017-03-31 12:34:56');
+        $cookie = new Cookie('cakephp', 'cakephp-rocks');
+        $cookie = $cookie->withDomain('cakephp.org')
+            ->withPath('/api')
+            ->withExpiry($date)
+            ->withHttpOnly(true)
+            ->withSecure(true);
+        $expected = [
+            'name' => 'cakephp',
+            'value' => 'cakephp-rocks',
+            'path' => '/api',
+            'domain' => 'cakephp.org',
+            'expires' => (int)$date->format('U'),
+            'secure' => true,
+            'httponly' => true
+        ];
+        $this->assertEquals($expected, $cookie->toArray());
+    }
 }