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.8 Red Velvet API

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