Browse Source

[HttpFoundation] added __toString() method

jsor 14 năm trước cách đây
mục cha
commit
e6d929aa71

+ 33 - 0
src/Symfony/Component/HttpFoundation/Cookie.php

@@ -60,6 +60,39 @@ class Cookie
         $this->secure = (Boolean) $secure;
         $this->httpOnly = (Boolean) $httpOnly;
     }
+    
+    public function __toString()
+    {
+        $str = urlencode($this->getName()).'=';
+
+        if (null === $this->getValue()) {
+                $str .= 'deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT';
+        } else {
+            $str .= urlencode($this->getValue());
+
+            if ($this->getExpiresTime() > 0) {
+                $str .= '; expires='.gmdate("D, d-M-Y H:i:s T", $this->getExpiresTime());
+            }
+        }
+
+        if (null !== $this->getPath()) {
+            $str .= '; path='.$this->getPath();
+        }
+
+        if (null !== $this->getDomain()) {
+            $str .= '; domain='.$this->getDomain();
+        }
+
+        if (true === $this->isSecure()) {
+            $str .= '; secure';
+        }
+
+        if (true === $this->isHttpOnly()) {
+            $str .= '; httponly';
+        }
+
+        return $str;
+    }
 
     public function getName()
     {

+ 11 - 0
tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php

@@ -137,4 +137,15 @@ class CookieTest extends \PHPUnit_Framework_TestCase
 
         $this->assertTrue($cookie->isCleared(), '->isCleared() returns true if the cookie has expired');
     }
+    
+    public function testToString()
+    {
+        $cookie = new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
+
+        $this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly', $cookie->__toString(), '->__toString() returns string representation of the cookie');
+        
+        $cookie = new Cookie('foo', null, 1, '/', '.myfoodomain.com');
+
+        $this->assertEquals('foo=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.myfoodomain.com; httponly', $cookie->__toString(), '->__toString() returns string representation of a cleared cookie if value is NULL');
+    }
 }