Browse Source

Add toArrayCompat()

This method is necessary as the existing Http\Client code expects the
original date format to be returned. Having this method allows us to
have less duplication across the framework.
Mark Story 9 years ago
parent
commit
e4897781fa
2 changed files with 55 additions and 1 deletions
  1. 29 1
      src/Http/Cookie/Cookie.php
  2. 26 0
      tests/TestCase/Http/Cookie/CookieTest.php

+ 29 - 1
src/Http/Cookie/Cookie.php

@@ -49,6 +49,13 @@ class Cookie implements CookieInterface
     use CookieCryptTrait;
 
     /**
+     * Expires attribute format.
+     *
+     * @var string
+     */
+    const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T';
+
+    /**
      * Cookie name
      *
      * @var string
@@ -160,7 +167,7 @@ class Cookie implements CookieInterface
     {
         return sprintf(
             'expires=%s',
-            gmdate('D, d-M-Y H:i:s T', $this->expiresAt)
+            gmdate(static::EXPIRES_FORMAT, $this->expiresAt)
         );
     }
 
@@ -617,6 +624,27 @@ class Cookie implements CookieInterface
     }
 
     /**
+     * Convert the cookie into an array of its properties.
+     *
+     * This method is compatible with older client code that
+     * expects date strings instead of timestamps.
+     *
+     * @return array
+     */
+    public function toArrayCompat()
+    {
+        return [
+            'name' => $this->getName(),
+            'value' => $this->getValue(),
+            'path' => $this->getPath(),
+            'domain' => $this->getDomain(),
+            'secure' => $this->isSecure(),
+            'httponly' => $this->isHttpOnly(),
+            'expires' => gmdate(static::EXPIRES_FORMAT, $this->expiresAt)
+        ];
+    }
+
+    /**
      * Implode method to keep keys are multidimensional arrays
      *
      * @param array $array Map of key and values

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

@@ -547,4 +547,30 @@ class CookieTest extends TestCase
         ];
         $this->assertEquals($expected, $cookie->toArray());
     }
+
+    /**
+     * Test toArrayCompat
+     *
+     * @return void
+     */
+    public function testToArrayCompat()
+    {
+        $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' => $date->format(DATE_COOKIE),
+            'secure' => true,
+            'httponly' => true
+        ];
+        $this->assertEquals($expected, $cookie->toArrayCompat());
+    }
 }