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

  • CookieCollection
  • FormData
  • Message
  • Request
  • Response

Interfaces

  • AdapterInterface
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
 10:  * @link          https://cakephp.org CakePHP(tm) Project
 11:  * @since         3.0.0
 12:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 13:  */
 14: namespace Cake\Http\Client;
 15: 
 16: // This alias is necessary to avoid class name conflicts
 17: // with the deprecated class in this namespace.
 18: use Cake\Http\Cookie\CookieCollection as CookiesCollection;
 19: use Cake\Http\Cookie\CookieInterface;
 20: use Psr\Http\Message\ResponseInterface;
 21: use RuntimeException;
 22: use Zend\Diactoros\MessageTrait;
 23: use Zend\Diactoros\Stream;
 24: 
 25: /**
 26:  * Implements methods for HTTP responses.
 27:  *
 28:  * All of the following examples assume that `$response` is an
 29:  * instance of this class.
 30:  *
 31:  * ### Get header values
 32:  *
 33:  * Header names are case-insensitive, but normalized to Title-Case
 34:  * when the response is parsed.
 35:  *
 36:  * ```
 37:  * $val = $response->getHeaderLine('content-type');
 38:  * ```
 39:  *
 40:  * Will read the Content-Type header. You can get all set
 41:  * headers using:
 42:  *
 43:  * ```
 44:  * $response->getHeaders();
 45:  * ```
 46:  *
 47:  * ### Get the response body
 48:  *
 49:  * You can access the response body stream using:
 50:  *
 51:  * ```
 52:  * $content = $response->getBody();
 53:  * ```
 54:  *
 55:  * You can get the body string using:
 56:  *
 57:  * ```
 58:  * $content = $response->getStringBody();
 59:  * ```
 60:  *
 61:  * If your response body is in XML or JSON you can use
 62:  * special content type specific accessors to read the decoded data.
 63:  * JSON data will be returned as arrays, while XML data will be returned
 64:  * as SimpleXML nodes:
 65:  *
 66:  * ```
 67:  * // Get as xml
 68:  * $content = $response->getXml()
 69:  * // Get as json
 70:  * $content = $response->getJson()
 71:  * ```
 72:  *
 73:  * If the response cannot be decoded, null will be returned.
 74:  *
 75:  * ### Check the status code
 76:  *
 77:  * You can access the response status code using:
 78:  *
 79:  * ```
 80:  * $content = $response->getStatusCode();
 81:  * ```
 82:  */
 83: class Response extends Message implements ResponseInterface
 84: {
 85:     use MessageTrait;
 86: 
 87:     /**
 88:      * The status code of the response.
 89:      *
 90:      * @var int
 91:      */
 92:     protected $code;
 93: 
 94:     /**
 95:      * Cookie Collection instance
 96:      *
 97:      * @var \Cake\Http\Cookie\CookieCollection
 98:      */
 99:     protected $cookies;
100: 
101:     /**
102:      * The reason phrase for the status code
103:      *
104:      * @var string
105:      */
106:     protected $reasonPhrase;
107: 
108:     /**
109:      * Cached decoded XML data.
110:      *
111:      * @var \SimpleXMLElement
112:      */
113:     protected $_xml;
114: 
115:     /**
116:      * Cached decoded JSON data.
117:      *
118:      * @var array
119:      */
120:     protected $_json;
121: 
122:     /**
123:      * Map of public => property names for __get()
124:      *
125:      * @var array
126:      */
127:     protected $_exposedProperties = [
128:         'cookies' => '_getCookies',
129:         'body' => '_getBody',
130:         'code' => 'code',
131:         'json' => '_getJson',
132:         'xml' => '_getXml',
133:         'headers' => '_getHeaders',
134:     ];
135: 
136:     /**
137:      * Map of deprecated magic properties.
138:      *
139:      * @var array
140:      * @internal
141:      */
142:     protected $_deprecatedMagicProperties = [
143:         'cookies' => 'getCookies()',
144:         'body' => 'getStringBody()',
145:         'json' => 'getJson()',
146:         'xml' => 'getXml()',
147:         'headers' => 'getHeaders()',
148:     ];
149: 
150:     /**
151:      * Constructor
152:      *
153:      * @param array $headers Unparsed headers.
154:      * @param string $body The response body.
155:      */
156:     public function __construct($headers = [], $body = '')
157:     {
158:         $this->_parseHeaders($headers);
159:         if ($this->getHeaderLine('Content-Encoding') === 'gzip') {
160:             $body = $this->_decodeGzipBody($body);
161:         }
162:         $stream = new Stream('php://memory', 'wb+');
163:         $stream->write($body);
164:         $stream->rewind();
165:         $this->stream = $stream;
166:     }
167: 
168:     /**
169:      * Uncompress a gzip response.
170:      *
171:      * Looks for gzip signatures, and if gzinflate() exists,
172:      * the body will be decompressed.
173:      *
174:      * @param string $body Gzip encoded body.
175:      * @return string
176:      * @throws \RuntimeException When attempting to decode gzip content without gzinflate.
177:      */
178:     protected function _decodeGzipBody($body)
179:     {
180:         if (!function_exists('gzinflate')) {
181:             throw new RuntimeException('Cannot decompress gzip response body without gzinflate()');
182:         }
183:         $offset = 0;
184:         // Look for gzip 'signature'
185:         if (substr($body, 0, 2) === "\x1f\x8b") {
186:             $offset = 2;
187:         }
188:         // Check the format byte
189:         if (substr($body, $offset, 1) === "\x08") {
190:             return gzinflate(substr($body, $offset + 8));
191:         }
192:     }
193: 
194:     /**
195:      * Parses headers if necessary.
196:      *
197:      * - Decodes the status code and reasonphrase.
198:      * - Parses and normalizes header names + values.
199:      *
200:      * @param array $headers Headers to parse.
201:      * @return void
202:      */
203:     protected function _parseHeaders($headers)
204:     {
205:         foreach ($headers as $key => $value) {
206:             if (substr($value, 0, 5) === 'HTTP/') {
207:                 preg_match('/HTTP\/([\d.]+) ([0-9]+)(.*)/i', $value, $matches);
208:                 $this->protocol = $matches[1];
209:                 $this->code = (int)$matches[2];
210:                 $this->reasonPhrase = trim($matches[3]);
211:                 continue;
212:             }
213:             if (strpos($value, ':') === false) {
214:                 continue;
215:             }
216:             list($name, $value) = explode(':', $value, 2);
217:             $value = trim($value);
218:             $name = trim($name);
219: 
220:             $normalized = strtolower($name);
221: 
222:             if (isset($this->headers[$name])) {
223:                 $this->headers[$name][] = $value;
224:             } else {
225:                 $this->headers[$name] = (array)$value;
226:                 $this->headerNames[$normalized] = $name;
227:             }
228:         }
229:     }
230: 
231:     /**
232:      * Check if the response was OK
233:      *
234:      * @return bool
235:      */
236:     public function isOk()
237:     {
238:         $codes = [
239:             static::STATUS_OK,
240:             static::STATUS_CREATED,
241:             static::STATUS_ACCEPTED,
242:             static::STATUS_NON_AUTHORITATIVE_INFORMATION,
243:             static::STATUS_NO_CONTENT
244:         ];
245: 
246:         return in_array($this->code, $codes);
247:     }
248: 
249:     /**
250:      * Check if the response had a redirect status code.
251:      *
252:      * @return bool
253:      */
254:     public function isRedirect()
255:     {
256:         $codes = [
257:             static::STATUS_MOVED_PERMANENTLY,
258:             static::STATUS_FOUND,
259:             static::STATUS_SEE_OTHER,
260:             static::STATUS_TEMPORARY_REDIRECT,
261:         ];
262: 
263:         return (
264:             in_array($this->code, $codes) &&
265:             $this->getHeaderLine('Location')
266:         );
267:     }
268: 
269:     /**
270:      * Get the status code from the response
271:      *
272:      * @return int
273:      * @deprecated 3.3.0 Use getStatusCode() instead.
274:      */
275:     public function statusCode()
276:     {
277:         deprecationWarning(
278:             'Response::statusCode() is deprecated. ' .
279:             'Use Response::getStatusCode() instead.'
280:         );
281: 
282:         return $this->code;
283:     }
284: 
285:     /**
286:      * {@inheritdoc}
287:      *
288:      * @return int The status code.
289:      */
290:     public function getStatusCode()
291:     {
292:         return $this->code;
293:     }
294: 
295:     /**
296:      * {@inheritdoc}
297:      *
298:      * @param int $code The status code to set.
299:      * @param string $reasonPhrase The status reason phrase.
300:      * @return $this A copy of the current object with an updated status code.
301:      */
302:     public function withStatus($code, $reasonPhrase = '')
303:     {
304:         $new = clone $this;
305:         $new->code = $code;
306:         $new->reasonPhrase = $reasonPhrase;
307: 
308:         return $new;
309:     }
310: 
311:     /**
312:      * {@inheritdoc}
313:      *
314:      * @return string The current reason phrase.
315:      */
316:     public function getReasonPhrase()
317:     {
318:         return $this->reasonPhrase;
319:     }
320: 
321:     /**
322:      * Get the encoding if it was set.
323:      *
324:      * @return string|null
325:      * @deprecated 3.3.0 Use getEncoding() instead.
326:      */
327:     public function encoding()
328:     {
329:         deprecationWarning(
330:             'Response::encoding() is deprecated. ' .
331:             'Use Response::getEncoding() instead.'
332:         );
333: 
334:         return $this->getEncoding();
335:     }
336: 
337:     /**
338:      * Get the encoding if it was set.
339:      *
340:      * @return string|null
341:      */
342:     public function getEncoding()
343:     {
344:         $content = $this->getHeaderLine('content-type');
345:         if (!$content) {
346:             return null;
347:         }
348:         preg_match('/charset\s?=\s?[\'"]?([a-z0-9-_]+)[\'"]?/i', $content, $matches);
349:         if (empty($matches[1])) {
350:             return null;
351:         }
352: 
353:         return $matches[1];
354:     }
355: 
356:     /**
357:      * Read single/multiple header value(s) out.
358:      *
359:      * @param string|null $name The name of the header you want. Leave
360:      *   null to get all headers.
361:      * @return mixed Null when the header doesn't exist. An array
362:      *   will be returned when getting all headers or when getting
363:      *   a header that had multiple values set. Otherwise a string
364:      *   will be returned.
365:      * @deprecated 3.3.0 Use getHeader() and getHeaderLine() instead.
366:      */
367:     public function header($name = null)
368:     {
369:         deprecationWarning(
370:             'Response::header() is deprecated. ' .
371:             'Use Response::getHeader() and getHeaderLine() instead.'
372:         );
373: 
374:         if ($name === null) {
375:             return $this->_getHeaders();
376:         }
377:         $header = $this->getHeader($name);
378:         if (count($header) === 1) {
379:             return $header[0];
380:         }
381: 
382:         return $header;
383:     }
384: 
385:     /**
386:      * Read single/multiple cookie values out.
387:      *
388:      * *Note* This method will only provide access to cookies that
389:      * were added as part of the constructor. If cookies are added post
390:      * construction they will not be accessible via this method.
391:      *
392:      * @param string|null $name The name of the cookie you want. Leave
393:      *   null to get all cookies.
394:      * @param bool $all Get all parts of the cookie. When false only
395:      *   the value will be returned.
396:      * @return mixed
397:      * @deprecated 3.3.0 Use getCookie(), getCookieData() or getCookies() instead.
398:      */
399:     public function cookie($name = null, $all = false)
400:     {
401:         deprecationWarning(
402:             'Response::cookie() is deprecated. ' .
403:             'Use Response::getCookie(), getCookieData() or getCookies() instead.'
404:         );
405: 
406:         if ($name === null) {
407:             return $this->getCookies();
408:         }
409:         if ($all) {
410:             return $this->getCookieData($name);
411:         }
412: 
413:         return $this->getCookie($name);
414:     }
415: 
416:     /**
417:      * Get the all cookie data.
418:      *
419:      * @return array The cookie data
420:      */
421:     public function getCookies()
422:     {
423:         return $this->_getCookies();
424:     }
425: 
426:     /**
427:      * Get the cookie collection from this response.
428:      *
429:      * This method exposes the response's CookieCollection
430:      * instance allowing you to interact with cookie objects directly.
431:      *
432:      * @return \Cake\Http\Cookie\CookieCollection
433:      */
434:     public function getCookieCollection()
435:     {
436:         $this->buildCookieCollection();
437: 
438:         return $this->cookies;
439:     }
440: 
441:     /**
442:      * Get the value of a single cookie.
443:      *
444:      * @param string $name The name of the cookie value.
445:      * @return string|array|null Either the cookie's value or null when the cookie is undefined.
446:      */
447:     public function getCookie($name)
448:     {
449:         $this->buildCookieCollection();
450:         if (!$this->cookies->has($name)) {
451:             return null;
452:         }
453: 
454:         return $this->cookies->get($name)->getValue();
455:     }
456: 
457:     /**
458:      * Get the full data for a single cookie.
459:      *
460:      * @param string $name The name of the cookie value.
461:      * @return array|null Either the cookie's data or null when the cookie is undefined.
462:      */
463:     public function getCookieData($name)
464:     {
465:         $this->buildCookieCollection();
466: 
467:         if (!$this->cookies->has($name)) {
468:             return null;
469:         }
470: 
471:         $cookie = $this->cookies->get($name);
472: 
473:         return $this->convertCookieToArray($cookie);
474:     }
475: 
476:     /**
477:      * Convert the cookie into an array of its properties.
478:      *
479:      * This method is compatible with older client code that
480:      * expects date strings instead of timestamps.
481:      *
482:      * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
483:      * @return array
484:      */
485:     protected function convertCookieToArray(CookieInterface $cookie)
486:     {
487:         return [
488:             'name' => $cookie->getName(),
489:             'value' => $cookie->getValue(),
490:             'path' => $cookie->getPath(),
491:             'domain' => $cookie->getDomain(),
492:             'secure' => $cookie->isSecure(),
493:             'httponly' => $cookie->isHttpOnly(),
494:             'expires' => $cookie->getFormattedExpires()
495:         ];
496:     }
497: 
498:     /**
499:      * Lazily build the CookieCollection and cookie objects from the response header
500:      *
501:      * @return void
502:      */
503:     protected function buildCookieCollection()
504:     {
505:         if ($this->cookies) {
506:             return;
507:         }
508:         $this->cookies = CookiesCollection::createFromHeader($this->getHeader('Set-Cookie'));
509:     }
510: 
511:     /**
512:      * Property accessor for `$this->cookies`
513:      *
514:      * @return array Array of Cookie data.
515:      */
516:     protected function _getCookies()
517:     {
518:         $this->buildCookieCollection();
519: 
520:         $cookies = [];
521:         foreach ($this->cookies as $cookie) {
522:             $cookies[$cookie->getName()] = $this->convertCookieToArray($cookie);
523:         }
524: 
525:         return $cookies;
526:     }
527: 
528:     /**
529:      * Get the HTTP version used.
530:      *
531:      * @return string
532:      * @deprecated 3.3.0 Use getProtocolVersion()
533:      */
534:     public function version()
535:     {
536:         deprecationWarning(
537:             'Response::version() is deprecated. ' .
538:             'Use Response::getProtocolVersion() instead.'
539:         );
540: 
541:         return $this->protocol;
542:     }
543: 
544:     /**
545:      * Get the response body.
546:      *
547:      * By passing in a $parser callable, you can get the decoded
548:      * response content back.
549:      *
550:      * For example to get the json data as an object:
551:      *
552:      * ```
553:      * $body = $response->body('json_decode');
554:      * ```
555:      *
556:      * @param callable|null $parser The callback to use to decode
557:      *   the response body.
558:      * @return mixed The response body.
559:      * @deprecated 3.7.0 Use getStringBody()/getJson()/getXml() instead.
560:      */
561:     public function body($parser = null)
562:     {
563:         deprecationWarning(
564:             'Response::body() is deprecated. Use getStringBody()/getJson()/getXml() instead.'
565:         );
566: 
567:         $stream = $this->stream;
568:         $stream->rewind();
569:         if ($parser) {
570:             return $parser($stream->getContents());
571:         }
572: 
573:         return $stream->getContents();
574:     }
575: 
576:     /**
577:      * Get the response body as string.
578:      *
579:      * @return string
580:      */
581:     public function getStringBody()
582:     {
583:         return $this->_getBody();
584:     }
585: 
586:     /**
587:      * Get the response body as JSON decoded data.
588:      *
589:      * @return array|null
590:      */
591:     public function getJson()
592:     {
593:         return $this->_getJson();
594:     }
595: 
596:     /**
597:      * Get the response body as JSON decoded data.
598:      *
599:      * @return array|null
600:      */
601:     protected function _getJson()
602:     {
603:         if ($this->_json) {
604:             return $this->_json;
605:         }
606: 
607:         return $this->_json = json_decode($this->_getBody(), true);
608:     }
609: 
610:     /**
611:      * Get the response body as XML decoded data.
612:      *
613:      * @return \SimpleXMLElement|null
614:      */
615:     public function getXml()
616:     {
617:         return $this->_getXml();
618:     }
619: 
620:     /**
621:      * Get the response body as XML decoded data.
622:      *
623:      * @return \SimpleXMLElement|null
624:      */
625:     protected function _getXml()
626:     {
627:         if ($this->_xml) {
628:             return $this->_xml;
629:         }
630:         libxml_use_internal_errors();
631:         $data = simplexml_load_string($this->_getBody());
632:         if ($data) {
633:             $this->_xml = $data;
634: 
635:             return $this->_xml;
636:         }
637: 
638:         return null;
639:     }
640: 
641:     /**
642:      * Provides magic __get() support.
643:      *
644:      * @return array
645:      */
646:     protected function _getHeaders()
647:     {
648:         $out = [];
649:         foreach ($this->headers as $key => $values) {
650:             $out[$key] = implode(',', $values);
651:         }
652: 
653:         return $out;
654:     }
655: 
656:     /**
657:      * Provides magic __get() support.
658:      *
659:      * @return string
660:      */
661:     protected function _getBody()
662:     {
663:         $this->stream->rewind();
664: 
665:         return $this->stream->getContents();
666:     }
667: 
668:     /**
669:      * Read values as properties.
670:      *
671:      * @param string $name Property name.
672:      * @return mixed
673:      */
674:     public function __get($name)
675:     {
676:         if (!isset($this->_exposedProperties[$name])) {
677:             return false;
678:         }
679:         $key = $this->_exposedProperties[$name];
680:         if (substr($key, 0, 4) === '_get') {
681:             deprecationWarning(sprintf(
682:                 'Response::%s is deprecated. Use Response::%s instead.',
683:                 $name,
684:                 $this->_deprecatedMagicProperties[$name]
685:             ));
686: 
687:             return $this->{$key}();
688:         }
689: 
690:         if ($key === 'code') {
691:             deprecationWarning(
692:                 'Response::code() is deprecated. ' .
693:                 'Use Response::getStatusCode() instead.'
694:             );
695:         }
696: 
697:         return $this->{$key};
698:     }
699: 
700:     /**
701:      * isset/empty test with -> syntax.
702:      *
703:      * @param string $name Property name.
704:      * @return bool
705:      */
706:     public function __isset($name)
707:     {
708:         if (!isset($this->_exposedProperties[$name])) {
709:             return false;
710:         }
711:         $key = $this->_exposedProperties[$name];
712:         if (substr($key, 0, 4) === '_get') {
713:             deprecationWarning(sprintf(
714:                 'Response::%s is deprecated. Use Response::%s instead.',
715:                 $name,
716:                 $this->_deprecatedMagicProperties[$name]
717:             ));
718: 
719:             $val = $this->{$key}();
720: 
721:             return $val !== null;
722:         }
723: 
724:         if ($key === 'code') {
725:             deprecationWarning(
726:                 'Response::code() is deprecated. ' .
727:                 'Use Response::getStatusCode() instead.'
728:             );
729:         }
730: 
731:         return isset($this->{$key});
732:     }
733: }
734: 
735: // @deprecated 3.4.0 Add backwards compat alias.
736: class_alias('Cake\Http\Client\Response', 'Cake\Network\Http\Response');
737: 
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