3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Http\Header
;
15 * @see http://www.ietf.org/rfc/rfc2109.txt
16 * @see http://www.w3.org/Protocols/rfc2109/rfc2109
18 class Cookie
extends ArrayObject
implements HeaderInterface
21 protected $encodeValue = true;
23 public static function fromSetCookieArray(array $setCookies)
26 /* @var $setCookie SetCookie */
27 foreach ($setCookies as $setCookie) {
28 if (!$setCookie instanceof SetCookie
) {
29 throw new Exception\
InvalidArgumentException(__CLASS__
. '::' . __METHOD__
. ' requires an array of SetCookie objects');
31 if (array_key_exists($setCookie->getName(), $nvPairs)) {
32 throw new Exception\
InvalidArgumentException('Two cookies with the same name were provided to ' . __CLASS__
. '::' . __METHOD__
);
35 $nvPairs[$setCookie->getName()] = $setCookie->getValue();
37 return new static($nvPairs);
40 public static function fromString($headerLine)
42 $header = new static();
44 list($name, $value) = GenericHeader
::splitHeaderLine($headerLine);
46 // check to ensure proper header type for this factory
47 if (strtolower($name) !== 'cookie') {
48 throw new Exception\
InvalidArgumentException('Invalid header line for Server string: "' . $name . '"');
51 $nvPairs = preg_split('#;\s*#', $value);
54 foreach ($nvPairs as $nvPair) {
55 $parts = explode('=', $nvPair, 2);
56 if (count($parts) != 2) {
57 throw new Exception\
RuntimeException('Malformed Cookie header found');
59 list($name, $value) = $parts;
60 $arrayInfo[$name] = urldecode($value);
63 $header->exchangeArray($arrayInfo);
68 public function __construct(array $array = array())
70 parent
::__construct($array, ArrayObject
::ARRAY_AS_PROPS
);
73 public function setEncodeValue($encodeValue)
75 $this->encodeValue
= (bool) $encodeValue;
79 public function getEncodeValue()
81 return $this->encodeValue
;
84 public function getFieldName()
89 public function getFieldValue()
93 foreach ($this as $name => $value) {
94 $nvPairs[] = $name . '=' . (($this->encodeValue
) ?
urlencode($value) : $value);
97 return implode('; ', $nvPairs);
100 public function toString()
102 return 'Cookie: ' . $this->getFieldValue();
106 * Get the cookie as a string, suitable for sending as a "Cookie" header in an
111 public function __toString()
113 return $this->toString();