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
13 use Zend\Http\Header\SetCookie
;
14 use Zend\Http\Response
;
19 * A Zend\Http\Cookies object is designed to contain and maintain HTTP cookies, and should
20 * be used along with Zend\Http\Client in order to manage cookies across HTTP requests and
23 * The class contains an array of Zend\Http\Header\Cookie objects. Cookies can be added
24 * automatically from a request or manually. Then, the Cookies class can find and return the
25 * cookies needed for a specific HTTP request.
27 * A special parameter can be passed to all methods of this class that return cookies: Cookies
28 * can be returned either in their native form (as Zend\Http\Header\Cookie objects) or as strings -
29 * the later is suitable for sending as the value of the "Cookie" header in an HTTP request.
30 * You can also choose, when returning more than one cookie, whether to get an array of strings
31 * (by passing Zend\Http\Client\Cookies::COOKIE_STRING_ARRAY) or one unified string for all cookies
32 * (by passing Zend\Http\Client\Cookies::COOKIE_STRING_CONCAT).
34 * @link http://wp.netscape.com/newsref/std/cookie_spec.html for some specs.
36 class Cookies
extends Headers
39 * Return cookie(s) as a Zend\Http\Cookie object
42 const COOKIE_OBJECT
= 0;
45 * Return cookie(s) as a string (suitable for sending in an HTTP request)
48 const COOKIE_STRING_ARRAY
= 1;
51 * Return all cookies as one long string (suitable for sending in an HTTP request)
54 const COOKIE_STRING_CONCAT
= 2;
57 * Return all cookies as one long string (strict mode)
58 * - Single space after the semi-colon separating each cookie
59 * - Remove trailing semi-colon, if any
61 const COOKIE_STRING_CONCAT_STRICT
= 3;
64 * @var \Zend\Http\Cookies
66 protected $cookies = array();
69 * @var \Zend\Http\Headers
71 protected $headers = null;
76 protected $rawCookies;
80 * @throws Exception\RuntimeException
84 public static function fromString($string)
86 throw new Exception\
RuntimeException(
87 __CLASS__
. '::' . __FUNCTION__
. ' should not be used as a factory, use '
88 . __NAMESPACE__
. '\Headers::fromtString() instead.'
93 * Add a cookie to the class. Cookie should be passed either as a Zend\Http\Header\Cookie object
94 * or as a string - in which case an object is created from the string.
96 * @param SetCookie|string $cookie
97 * @param Uri\Uri|string $refUri Optional reference URI (for domain, path, secure)
98 * @throws Exception\InvalidArgumentException
100 public function addCookie($cookie, $refUri = null)
102 if (is_string($cookie)) {
103 $cookie = SetCookie
::fromString($cookie, $refUri);
106 if ($cookie instanceof SetCookie
) {
107 $domain = $cookie->getDomain();
108 $path = $cookie->getPath();
109 if (!isset($this->cookies
[$domain])) {
110 $this->cookies
[$domain] = array();
112 if (!isset($this->cookies
[$domain][$path])) {
113 $this->cookies
[$domain][$path] = array();
115 $this->cookies
[$domain][$path][$cookie->getName()] = $cookie;
116 $this->rawCookies
[] = $cookie;
118 throw new Exception\
InvalidArgumentException('Supplient argument is not a valid cookie string or object');
123 * Parse an HTTP response, adding all the cookies set in that response
125 * @param Response $response
126 * @param Uri\Uri|string $refUri Requested URI
128 public function addCookiesFromResponse(Response
$response, $refUri)
130 $cookieHdrs = $response->getHeaders()->get('Set-Cookie');
132 if (is_array($cookieHdrs) ||
$cookieHdrs instanceof ArrayIterator
) {
133 foreach ($cookieHdrs as $cookie) {
134 $this->addCookie($cookie, $refUri);
136 } elseif (is_string($cookieHdrs)) {
137 $this->addCookie($cookieHdrs, $refUri);
142 * Get all cookies in the cookie jar as an array
144 * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\SetCookie or as strings
145 * @return array|string
147 public function getAllCookies($retAs = self
::COOKIE_OBJECT
)
149 $cookies = $this->_flattenCookiesArray($this->cookies
, $retAs);
154 * Return an array of all cookies matching a specific request according to the request URI,
155 * whether session cookies should be sent or not, and the time to consider as "now" when
156 * checking cookie expiry time.
158 * @param string|Uri\Uri $uri URI to check against (secure, domain, path)
159 * @param bool $matchSessionCookies Whether to send session cookies
160 * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\Cookie or as strings
161 * @param int $now Override the current time when checking for expiry time
162 * @throws Exception\InvalidArgumentException if invalid URI specified
163 * @return array|string
165 public function getMatchingCookies($uri, $matchSessionCookies = true,
166 $retAs = self
::COOKIE_OBJECT
, $now = null)
168 if (is_string($uri)) {
169 $uri = Uri\UriFactory
::factory($uri, 'http');
170 } elseif (!$uri instanceof Uri\Uri
) {
171 throw new Exception\
InvalidArgumentException("Invalid URI string or object passed");
174 $host = $uri->getHost();
176 throw new Exception\
InvalidArgumentException('Invalid URI specified; does not contain a host');
179 // First, reduce the array of cookies to only those matching domain and path
180 $cookies = $this->_matchDomain($host);
181 $cookies = $this->_matchPath($cookies, $uri->getPath());
182 $cookies = $this->_flattenCookiesArray($cookies, self
::COOKIE_OBJECT
);
184 // Next, run Cookie->match on all cookies to check secure, time and session matching
186 foreach ($cookies as $cookie)
187 if ($cookie->match($uri, $matchSessionCookies, $now))
190 // Now, use self::_flattenCookiesArray again - only to convert to the return format ;)
191 $ret = $this->_flattenCookiesArray($ret, $retAs);
197 * Get a specific cookie according to a URI and name
199 * @param Uri\Uri|string $uri The uri (domain and path) to match
200 * @param string $cookieName The cookie's name
201 * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\SetCookie or as strings
202 * @throws Exception\InvalidArgumentException if invalid URI specified or invalid $retAs value
203 * @return SetCookie|string
205 public function getCookie($uri, $cookieName, $retAs = self
::COOKIE_OBJECT
)
207 if (is_string($uri)) {
208 $uri = Uri\UriFactory
::factory($uri, 'http');
209 } elseif (!$uri instanceof Uri\Uri
) {
210 throw new Exception\
InvalidArgumentException('Invalid URI specified');
213 $host = $uri->getHost();
215 throw new Exception\
InvalidArgumentException('Invalid URI specified; host missing');
218 // Get correct cookie path
219 $path = $uri->getPath();
220 $path = substr($path, 0, strrpos($path, '/'));
221 if (! $path) $path = '/';
223 if (isset($this->cookies
[$uri->getHost()][$path][$cookieName])) {
224 $cookie = $this->cookies
[$uri->getHost()][$path][$cookieName];
227 case self
::COOKIE_OBJECT
:
231 case self
::COOKIE_STRING_ARRAY
:
232 case self
::COOKIE_STRING_CONCAT
:
233 return $cookie->__toString();
237 throw new Exception\
InvalidArgumentException("Invalid value passed for \$retAs: {$retAs}");
246 * Helper function to recursively flatten an array. Should be used when exporting the
247 * cookies array (or parts of it)
249 * @param \Zend\Http\Header\SetCookie|array $ptr
250 * @param int $retAs What value to return
251 * @return array|string
253 protected function _flattenCookiesArray($ptr, $retAs = self
::COOKIE_OBJECT
)
255 if (is_array($ptr)) {
256 $ret = ($retAs == self
::COOKIE_STRING_CONCAT ?
'' : array());
257 foreach ($ptr as $item) {
258 if ($retAs == self
::COOKIE_STRING_CONCAT
) {
259 $ret .= $this->_flattenCookiesArray($item, $retAs);
261 $ret = array_merge($ret, $this->_flattenCookiesArray($item, $retAs));
265 } elseif ($ptr instanceof SetCookie
) {
267 case self
::COOKIE_STRING_ARRAY
:
268 return array($ptr->__toString());
271 case self
::COOKIE_STRING_CONCAT
:
272 return $ptr->__toString();
275 case self
::COOKIE_OBJECT
:
286 * Return a subset of the cookies array matching a specific domain
288 * @param string $domain
291 protected function _matchDomain($domain)
295 foreach (array_keys($this->cookies
) as $cdom) {
296 if (SetCookie
::matchCookieDomain($cdom, $domain)) {
297 $ret[$cdom] = $this->cookies
[$cdom];
305 * Return a subset of a domain-matching cookies that also match a specified path
307 * @param array $domains
308 * @param string $path
311 protected function _matchPath($domains, $path)
315 foreach ($domains as $dom => $pathsArray) {
316 foreach (array_keys($pathsArray) as $cpath) {
317 if (SetCookie
::matchCookiePath($cpath, $path)) {
318 if (! isset($ret[$dom])) {
319 $ret[$dom] = array();
322 $ret[$dom][$cpath] = $pathsArray[$cpath];
331 * Create a new Cookies object and automatically load into it all the
332 * cookies set in an Http_Response object. If $uri is set, it will be
333 * considered as the requested URI for setting default domain and path
336 * @param Response $response HTTP Response object
337 * @param Uri\Uri|string $refUri The requested URI
339 * @todo Add the $uri functionality.
341 public static function fromResponse(Response
$response, $refUri)
344 $jar->addCookiesFromResponse($response, $refUri);
349 * Tells if the array of cookies is empty
353 public function isEmpty()
355 return count($this) == 0;
359 * Empties the cookieJar of any cookie
363 public function reset()
365 $this->cookies
= $this->rawCookies
= array();