CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.7 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.7
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • Cookie
  • CookieCollection

Interfaces

  • CookieInterface
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * Redistributions of files must retain the above copyright notice.
  8:  *
  9:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 10:  * @link          http://cakephp.org CakePHP(tm) Project
 11:  * @since         3.5.0
 12:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 13:  */
 14: namespace Cake\Http\Cookie;
 15: 
 16: use ArrayIterator;
 17: use Countable;
 18: use DateTimeImmutable;
 19: use DateTimeZone;
 20: use Exception;
 21: use InvalidArgumentException;
 22: use IteratorAggregate;
 23: use Psr\Http\Message\RequestInterface;
 24: use Psr\Http\Message\ResponseInterface;
 25: use Psr\Http\Message\ServerRequestInterface;
 26: 
 27: /**
 28:  * Cookie Collection
 29:  *
 30:  * Provides an immutable collection of cookies objects. Adding or removing
 31:  * to a collection returns a *new* collection that you must retain.
 32:  */
 33: class CookieCollection implements IteratorAggregate, Countable
 34: {
 35: 
 36:     /**
 37:      * Cookie objects
 38:      *
 39:      * @var \Cake\Http\Cookie\CookieInterface[]
 40:      */
 41:     protected $cookies = [];
 42: 
 43:     /**
 44:      * Constructor
 45:      *
 46:      * @param array $cookies Array of cookie objects
 47:      */
 48:     public function __construct(array $cookies = [])
 49:     {
 50:         $this->checkCookies($cookies);
 51:         foreach ($cookies as $cookie) {
 52:             $this->cookies[$cookie->getId()] = $cookie;
 53:         }
 54:     }
 55: 
 56:     /**
 57:      * Create a Cookie Collection from an array of Set-Cookie Headers
 58:      *
 59:      * @param array $header The array of set-cookie header values.
 60:      * @return static
 61:      */
 62:     public static function createFromHeader(array $header)
 63:     {
 64:         $cookies = static::parseSetCookieHeader($header);
 65: 
 66:         return new static($cookies);
 67:     }
 68: 
 69:     /**
 70:      * Create a new collection from the cookies in a ServerRequest
 71:      *
 72:      * @param \Psr\Http\Message\ServerRequestInterface $request The request to extract cookie data from
 73:      * @return static
 74:      */
 75:     public static function createFromServerRequest(ServerRequestInterface $request)
 76:     {
 77:         $data = $request->getCookieParams();
 78:         $cookies = [];
 79:         foreach ($data as $name => $value) {
 80:             $cookies[] = new Cookie($name, $value);
 81:         }
 82: 
 83:         return new static($cookies);
 84:     }
 85: 
 86:     /**
 87:      * Get the number of cookies in the collection.
 88:      *
 89:      * @return int
 90:      */
 91:     public function count()
 92:     {
 93:         return count($this->cookies);
 94:     }
 95: 
 96:     /**
 97:      * Add a cookie and get an updated collection.
 98:      *
 99:      * Cookies are stored by id. This means that there can be duplicate
100:      * cookies if a cookie collection is used for cookies across multiple
101:      * domains. This can impact how get(), has() and remove() behave.
102:      *
103:      * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie instance to add.
104:      * @return static
105:      */
106:     public function add(CookieInterface $cookie)
107:     {
108:         $new = clone $this;
109:         $new->cookies[$cookie->getId()] = $cookie;
110: 
111:         return $new;
112:     }
113: 
114:     /**
115:      * Get the first cookie by name.
116:      *
117:      * @param string $name The name of the cookie.
118:      * @return \Cake\Http\Cookie\CookieInterface|null
119:      */
120:     public function get($name)
121:     {
122:         $key = mb_strtolower($name);
123:         foreach ($this->cookies as $cookie) {
124:             if (mb_strtolower($cookie->getName()) === $key) {
125:                 return $cookie;
126:             }
127:         }
128: 
129:         return null;
130:     }
131: 
132:     /**
133:      * Check if a cookie with the given name exists
134:      *
135:      * @param string $name The cookie name to check.
136:      * @return bool True if the cookie exists, otherwise false.
137:      */
138:     public function has($name)
139:     {
140:         $key = mb_strtolower($name);
141:         foreach ($this->cookies as $cookie) {
142:             if (mb_strtolower($cookie->getName()) === $key) {
143:                 return true;
144:             }
145:         }
146: 
147:         return false;
148:     }
149: 
150:     /**
151:      * Create a new collection with all cookies matching $name removed.
152:      *
153:      * If the cookie is not in the collection, this method will do nothing.
154:      *
155:      * @param string $name The name of the cookie to remove.
156:      * @return static
157:      */
158:     public function remove($name)
159:     {
160:         $new = clone $this;
161:         $key = mb_strtolower($name);
162:         foreach ($new->cookies as $i => $cookie) {
163:             if (mb_strtolower($cookie->getName()) === $key) {
164:                 unset($new->cookies[$i]);
165:             }
166:         }
167: 
168:         return $new;
169:     }
170: 
171:     /**
172:      * Checks if only valid cookie objects are in the array
173:      *
174:      * @param array $cookies Array of cookie objects
175:      * @return void
176:      * @throws \InvalidArgumentException
177:      */
178:     protected function checkCookies(array $cookies)
179:     {
180:         foreach ($cookies as $index => $cookie) {
181:             if (!$cookie instanceof CookieInterface) {
182:                 throw new InvalidArgumentException(
183:                     sprintf(
184:                         'Expected `%s[]` as $cookies but instead got `%s` at index %d',
185:                         static::class,
186:                         getTypeName($cookie),
187:                         $index
188:                     )
189:                 );
190:             }
191:         }
192:     }
193: 
194:     /**
195:      * Gets the iterator
196:      *
197:      * @return \ArrayIterator
198:      */
199:     public function getIterator()
200:     {
201:         return new ArrayIterator($this->cookies);
202:     }
203: 
204:     /**
205:      * Add cookies that match the path/domain/expiration to the request.
206:      *
207:      * This allows CookieCollections to be used as a 'cookie jar' in an HTTP client
208:      * situation. Cookies that match the request's domain + path that are not expired
209:      * when this method is called will be applied to the request.
210:      *
211:      * @param \Psr\Http\Message\RequestInterface $request The request to update.
212:      * @param array $extraCookies Associative array of additional cookies to add into the request. This
213:      *   is useful when you have cookie data from outside the collection you want to send.
214:      * @return \Psr\Http\Message\RequestInterface An updated request.
215:      */
216:     public function addToRequest(RequestInterface $request, array $extraCookies = [])
217:     {
218:         $uri = $request->getUri();
219:         $cookies = $this->findMatchingCookies(
220:             $uri->getScheme(),
221:             $uri->getHost(),
222:             $uri->getPath() ?: '/'
223:         );
224:         $cookies = array_merge($cookies, $extraCookies);
225:         $cookiePairs = [];
226:         foreach ($cookies as $key => $value) {
227:             $cookie = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
228:             $size = strlen($cookie);
229:             if ($size > 4096) {
230:                 triggerWarning(sprintf(
231:                     'The cookie `%s` exceeds the recommended maximum cookie length of 4096 bytes.',
232:                     $key
233:                 ));
234:             }
235:             $cookiePairs[] = $cookie;
236:         }
237: 
238:         if (empty($cookiePairs)) {
239:             return $request;
240:         }
241: 
242:         return $request->withHeader('Cookie', implode('; ', $cookiePairs));
243:     }
244: 
245:     /**
246:      * Find cookies matching the scheme, host, and path
247:      *
248:      * @param string $scheme The http scheme to match
249:      * @param string $host The host to match.
250:      * @param string $path The path to match
251:      * @return array An array of cookie name/value pairs
252:      */
253:     protected function findMatchingCookies($scheme, $host, $path)
254:     {
255:         $out = [];
256:         $now = new DateTimeImmutable('now', new DateTimeZone('UTC'));
257:         foreach ($this->cookies as $cookie) {
258:             if ($scheme === 'http' && $cookie->isSecure()) {
259:                 continue;
260:             }
261:             if (strpos($path, $cookie->getPath()) !== 0) {
262:                 continue;
263:             }
264:             $domain = $cookie->getDomain();
265:             $leadingDot = substr($domain, 0, 1) === '.';
266:             if ($leadingDot) {
267:                 $domain = ltrim($domain, '.');
268:             }
269: 
270:             if ($cookie->isExpired($now)) {
271:                 continue;
272:             }
273: 
274:             $pattern = '/' . preg_quote($domain, '/') . '$/';
275:             if (!preg_match($pattern, $host)) {
276:                 continue;
277:             }
278: 
279:             $out[$cookie->getName()] = $cookie->getValue();
280:         }
281: 
282:         return $out;
283:     }
284: 
285:     /**
286:      * Create a new collection that includes cookies from the response.
287:      *
288:      * @param \Psr\Http\Message\ResponseInterface $response Response to extract cookies from.
289:      * @param \Psr\Http\Message\RequestInterface $request Request to get cookie context from.
290:      * @return static
291:      */
292:     public function addFromResponse(ResponseInterface $response, RequestInterface $request)
293:     {
294:         $uri = $request->getUri();
295:         $host = $uri->getHost();
296:         $path = $uri->getPath() ?: '/';
297: 
298:         $cookies = static::parseSetCookieHeader($response->getHeader('Set-Cookie'));
299:         $cookies = $this->setRequestDefaults($cookies, $host, $path);
300:         $new = clone $this;
301:         foreach ($cookies as $cookie) {
302:             $new->cookies[$cookie->getId()] = $cookie;
303:         }
304:         $new->removeExpiredCookies($host, $path);
305: 
306:         return $new;
307:     }
308: 
309:     /**
310:      * Apply path and host to the set of cookies if they are not set.
311:      *
312:      * @param array $cookies An array of cookies to update.
313:      * @param string $host The host to set.
314:      * @param string $path The path to set.
315:      * @return array An array of updated cookies.
316:      */
317:     protected function setRequestDefaults(array $cookies, $host, $path)
318:     {
319:         $out = [];
320:         foreach ($cookies as $name => $cookie) {
321:             if (!$cookie->getDomain()) {
322:                 $cookie = $cookie->withDomain($host);
323:             }
324:             if (!$cookie->getPath()) {
325:                 $cookie = $cookie->withPath($path);
326:             }
327:             $out[] = $cookie;
328:         }
329: 
330:         return $out;
331:     }
332: 
333:     /**
334:      * Parse Set-Cookie headers into array
335:      *
336:      * @param array $values List of Set-Cookie Header values.
337:      * @return \Cake\Http\Cookie\Cookie[] An array of cookie objects
338:      */
339:     protected static function parseSetCookieHeader($values)
340:     {
341:         $cookies = [];
342:         foreach ($values as $value) {
343:             $value = rtrim($value, ';');
344:             $parts = preg_split('/\;[ \t]*/', $value);
345: 
346:             $name = false;
347:             $cookie = [
348:                 'value' => '',
349:                 'path' => '',
350:                 'domain' => '',
351:                 'secure' => false,
352:                 'httponly' => false,
353:                 'expires' => null,
354:                 'max-age' => null
355:             ];
356:             foreach ($parts as $i => $part) {
357:                 if (strpos($part, '=') !== false) {
358:                     list($key, $value) = explode('=', $part, 2);
359:                 } else {
360:                     $key = $part;
361:                     $value = true;
362:                 }
363:                 if ($i === 0) {
364:                     $name = $key;
365:                     $cookie['value'] = urldecode($value);
366:                     continue;
367:                 }
368:                 $key = strtolower($key);
369:                 if (array_key_exists($key, $cookie) && !strlen($cookie[$key])) {
370:                     $cookie[$key] = $value;
371:                 }
372:             }
373:             try {
374:                 $expires = null;
375:                 if ($cookie['max-age'] !== null) {
376:                     $expires = new DateTimeImmutable('@' . (time() + $cookie['max-age']));
377:                 } elseif ($cookie['expires']) {
378:                     $expires = new DateTimeImmutable('@' . strtotime($cookie['expires']));
379:                 }
380:             } catch (Exception $e) {
381:                 $expires = null;
382:             }
383: 
384:             try {
385:                 $cookies[] = new Cookie(
386:                     $name,
387:                     $cookie['value'],
388:                     $expires,
389:                     $cookie['path'],
390:                     $cookie['domain'],
391:                     $cookie['secure'],
392:                     $cookie['httponly']
393:                 );
394:             } catch (Exception $e) {
395:                 // Don't blow up on invalid cookies
396:             }
397:         }
398: 
399:         return $cookies;
400:     }
401: 
402:     /**
403:      * Remove expired cookies from the collection.
404:      *
405:      * @param string $host The host to check for expired cookies on.
406:      * @param string $path The path to check for expired cookies on.
407:      * @return void
408:      */
409:     protected function removeExpiredCookies($host, $path)
410:     {
411:         $time = new DateTimeImmutable('now', new DateTimeZone('UTC'));
412:         $hostPattern = '/' . preg_quote($host, '/') . '$/';
413: 
414:         foreach ($this->cookies as $i => $cookie) {
415:             $expired = $cookie->isExpired($time);
416:             $pathMatches = strpos($path, $cookie->getPath()) === 0;
417:             $hostMatches = preg_match($hostPattern, $cookie->getDomain());
418:             if ($pathMatches && $hostMatches && $expired) {
419:                 unset($this->cookies[$i]);
420:             }
421:         }
422:     }
423: }
424: 
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs