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

  • AuthComponent
  • CookieComponent
  • CsrfComponent
  • FlashComponent
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  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:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 11:  * @link          https://cakephp.org CakePHP(tm) Project
 12:  * @since         0.10.4
 13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: namespace Cake\Controller\Component;
 16: 
 17: use Cake\Controller\Component;
 18: use Cake\Controller\ComponentRegistry;
 19: use Cake\Controller\Controller;
 20: use Cake\Core\App;
 21: use Cake\Core\Configure;
 22: use Cake\Core\Exception\Exception;
 23: use Cake\Event\Event;
 24: use Cake\Http\Exception\NotFoundException;
 25: use Cake\Http\Response;
 26: use Cake\Routing\Router;
 27: use Cake\Utility\Exception\XmlException;
 28: use Cake\Utility\Inflector;
 29: use Cake\Utility\Xml;
 30: use RuntimeException;
 31: 
 32: /**
 33:  * Request object for handling alternative HTTP requests
 34:  *
 35:  * Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
 36:  * and the like. These units have no use for AJAX requests, and this Component can tell how Cake
 37:  * should respond to the different needs of a handheld computer and a desktop machine.
 38:  *
 39:  * @link https://book.cakephp.org/3.0/en/controllers/components/request-handling.html
 40:  */
 41: class RequestHandlerComponent extends Component
 42: {
 43: 
 44:     /**
 45:      * @var bool
 46:      * @deprecated 3.4.0 Unused. Will be removed in 4.0.0
 47:      */
 48:     public $enabled = true;
 49: 
 50:     /**
 51:      * Contains the file extension parsed out by the Router
 52:      *
 53:      * Deprecated as of 3.7.0. This property will be made protected in 4.0.0.
 54:      *
 55:      * @var string|null
 56:      * @see \Cake\Routing\Router::extensions()
 57:      */
 58:     public $ext;
 59: 
 60:     /**
 61:      * The template to use when rendering the given content type.
 62:      *
 63:      * @var string|null
 64:      */
 65:     protected $_renderType;
 66: 
 67:     /**
 68:      * Default config
 69:      *
 70:      * These are merged with user-provided config when the component is used.
 71:      *
 72:      * - `checkHttpCache` - Whether to check for HTTP cache.
 73:      * - `viewClassMap` - Mapping between type and view classes. If undefined
 74:      *   json, xml, and ajax will be mapped. Defining any types will omit the defaults.
 75:      * - `inputTypeMap` - A mapping between types and deserializers for request bodies.
 76:      *   If undefined json & xml will be mapped. Defining any types will omit the defaults.
 77:      * - `enableBeforeRedirect` - Set to false to disable the `beforeRedirect` callback. The
 78:      *   `beforeRedirect` functionality has been deprecated.
 79:      *
 80:      * @var array
 81:      */
 82:     protected $_defaultConfig = [
 83:         'checkHttpCache' => true,
 84:         'viewClassMap' => [],
 85:         'inputTypeMap' => [],
 86:         'enableBeforeRedirect' => true
 87:     ];
 88: 
 89:     /**
 90:      * Set the layout to be used when rendering the AuthComponent's ajaxLogin element.
 91:      *
 92:      * @var string
 93:      * @deprecated 3.3.11 This feature property is not supported and will
 94:      *   be removed in 4.0.0
 95:      */
 96:     public $ajaxLayout;
 97: 
 98:     /**
 99:      * Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
100:      *
101:      * @param \Cake\Controller\ComponentRegistry $registry ComponentRegistry object.
102:      * @param array $config Array of config.
103:      */
104:     public function __construct(ComponentRegistry $registry, array $config = [])
105:     {
106:         $config += [
107:             'viewClassMap' => [
108:                 'json' => 'Json',
109:                 'xml' => 'Xml',
110:                 'ajax' => 'Ajax'
111:             ],
112:             'inputTypeMap' => [
113:                 'json' => ['json_decode', true],
114:                 'xml' => [[$this, 'convertXml']],
115:             ]
116:         ];
117:         parent::__construct($registry, $config);
118:     }
119: 
120:     /**
121:      * Events supported by this component.
122:      *
123:      * @return array
124:      */
125:     public function implementedEvents()
126:     {
127:         return [
128:             'Controller.startup' => 'startup',
129:             'Controller.beforeRender' => 'beforeRender',
130:             'Controller.beforeRedirect' => 'beforeRedirect',
131:         ];
132:     }
133: 
134:     /**
135:      * @param array $config The config data.
136:      * @return void
137:      * @deprecated 3.4.0 Unused. To be removed in 4.0.0
138:      */
139:     public function initialize(array $config)
140:     {
141:     }
142: 
143:     /**
144:      * Set the extension based on the accept headers.
145:      * Compares the accepted types and configured extensions.
146:      * If there is one common type, that is assigned as the ext/content type for the response.
147:      * The type with the highest weight will be set. If the highest weight has more
148:      * than one type matching the extensions, the order in which extensions are specified
149:      * determines which type will be set.
150:      *
151:      * If html is one of the preferred types, no content type will be set, this
152:      * is to avoid issues with browsers that prefer HTML and several other content types.
153:      *
154:      * @param \Cake\Http\ServerRequest $request The request instance.
155:      * @param \Cake\Http\Response $response The response instance.
156:      * @return void
157:      */
158:     protected function _setExtension($request, $response)
159:     {
160:         $accept = $request->parseAccept();
161:         if (empty($accept) || current($accept)[0] === 'text/html') {
162:             return;
163:         }
164: 
165:         $accepts = $response->mapType($accept);
166:         $preferredTypes = current($accepts);
167:         if (array_intersect($preferredTypes, ['html', 'xhtml'])) {
168:             return;
169:         }
170: 
171:         $extensions = array_unique(
172:             array_merge(Router::extensions(), array_keys($this->getConfig('viewClassMap')))
173:         );
174:         foreach ($accepts as $types) {
175:             $ext = array_intersect($extensions, $types);
176:             if ($ext) {
177:                 $this->ext = current($ext);
178:                 break;
179:             }
180:         }
181:     }
182: 
183:     /**
184:      * The startup method of the RequestHandler enables several automatic behaviors
185:      * related to the detection of certain properties of the HTTP request, including:
186:      *
187:      * If the XML data is POSTed, the data is parsed into an XML object, which is assigned
188:      * to the $data property of the controller, which can then be saved to a model object.
189:      *
190:      * @param \Cake\Event\Event $event The startup event that was fired.
191:      * @return void
192:      */
193:     public function startup(Event $event)
194:     {
195:         /** @var \Cake\Controller\Controller $controller */
196:         $controller = $event->getSubject();
197:         $request = $controller->getRequest();
198:         $response = $controller->getResponse();
199: 
200:         if ($request->getParam('_ext')) {
201:             $this->ext = $request->getParam('_ext');
202:         }
203:         if (!$this->ext || in_array($this->ext, ['html', 'htm'])) {
204:             $this->_setExtension($request, $response);
205:         }
206: 
207:         $isAjax = $request->is('ajax');
208:         $controller->setRequest($request->withParam('isAjax', $isAjax));
209: 
210:         if (!$this->ext && $isAjax) {
211:             $this->ext = 'ajax';
212:         }
213: 
214:         if ($request->is(['get', 'head', 'options'])) {
215:             return;
216:         }
217: 
218:         if ($request->getParsedBody() !== []) {
219:             return;
220:         }
221:         foreach ($this->getConfig('inputTypeMap') as $type => $handler) {
222:             if (!is_callable($handler[0])) {
223:                 throw new RuntimeException(sprintf("Invalid callable for '%s' type.", $type));
224:             }
225:             if ($this->requestedWith($type)) {
226:                 $input = $request->input(...$handler);
227:                 $controller->setRequest($request->withParsedBody((array)$input));
228:             }
229:         }
230:     }
231: 
232:     /**
233:      * Helper method to parse xml input data, due to lack of anonymous functions
234:      * this lives here.
235:      *
236:      * @param string $xml XML string.
237:      * @return array Xml array data
238:      */
239:     public function convertXml($xml)
240:     {
241:         try {
242:             $xml = Xml::build($xml, ['return' => 'domdocument', 'readFile' => false]);
243:             // We might not get child nodes if there are nested inline entities.
244:             if ((int)$xml->childNodes->length > 0) {
245:                 return Xml::toArray($xml);
246:             }
247: 
248:             return [];
249:         } catch (XmlException $e) {
250:             return [];
251:         }
252:     }
253: 
254:     /**
255:      * Handles (fakes) redirects for AJAX requests using requestAction()
256:      *
257:      * @param \Cake\Event\Event $event The Controller.beforeRedirect event.
258:      * @param string|array $url A string or array containing the redirect location
259:      * @param \Cake\Http\Response $response The response object.
260:      * @return \Cake\Http\Response|null The response object if the redirect is caught.
261:      * @deprecated 3.3.5 This functionality will be removed in 4.0.0. You can disable this function
262:      *   now by setting the `enableBeforeRedirect` config option to false.
263:      */
264:     public function beforeRedirect(Event $event, $url, Response $response)
265:     {
266:         if (!$this->getConfig('enableBeforeRedirect')) {
267:             return null;
268:         }
269:         deprecationWarning(
270:             'RequestHandlerComponent::beforeRedirect() is deprecated. ' .
271:             'This functionality will be removed in 4.0.0. Set the `enableBeforeRedirect` ' .
272:             'option to `false` to disable this warning.'
273:         );
274:         $request = $this->getController()->getRequest();
275:         if (!$request->is('ajax')) {
276:             return null;
277:         }
278:         if (empty($url)) {
279:             return null;
280:         }
281:         if (is_array($url)) {
282:             $url = Router::url($url + ['_base' => false]);
283:         }
284:         $query = [];
285:         if (strpos($url, '?') !== false) {
286:             list($url, $querystr) = explode('?', $url, 2);
287:             parse_str($querystr, $query);
288:         }
289:         /** @var \Cake\Controller\Controller $controller */
290:         $controller = $event->getSubject();
291:         $response->body($controller->requestAction($url, [
292:             'return',
293:             'bare' => false,
294:             'environment' => [
295:                 'REQUEST_METHOD' => 'GET'
296:             ],
297:             'query' => $query,
298:             'cookies' => $request->getCookieParams()
299:         ]));
300: 
301:         return $response->withStatus(200);
302:     }
303: 
304:     /**
305:      * Checks if the response can be considered different according to the request
306:      * headers, and the caching response headers. If it was not modified, then the
307:      * render process is skipped. And the client will get a blank response with a
308:      * "304 Not Modified" header.
309:      *
310:      * - If Router::extensions() is enabled, the layout and template type are
311:      *   switched based on the parsed extension or `Accept` header. For example,
312:      *   if `controller/action.xml` is requested, the view path becomes
313:      *   `app/View/Controller/xml/action.ctp`. Also if `controller/action` is
314:      *   requested with `Accept: application/xml` in the headers the view
315:      *   path will become `app/View/Controller/xml/action.ctp`. Layout and template
316:      *   types will only switch to mime-types recognized by Cake\Http\Response.
317:      *   If you need to declare additional mime-types, you can do so using
318:      *   Cake\Http\Response::type() in your controller's beforeFilter() method.
319:      * - If a helper with the same name as the extension exists, it is added to
320:      *   the controller.
321:      * - If the extension is of a type that RequestHandler understands, it will
322:      *   set that Content-type in the response header.
323:      *
324:      * @param \Cake\Event\Event $event The Controller.beforeRender event.
325:      * @return bool false if the render process should be aborted
326:      * @throws \Cake\Http\Exception\NotFoundException If invoked extension is not configured.
327:      */
328:     public function beforeRender(Event $event)
329:     {
330:         /** @var \Cake\Controller\Controller $controller */
331:         $controller = $event->getSubject();
332:         $response = $controller->getResponse();
333:         $request = $controller->getRequest();
334: 
335:         if ($this->ext && !in_array($this->ext, ['html', 'htm'])) {
336:             if (!$response->getMimeType($this->ext)) {
337:                 throw new NotFoundException('Invoked extension not recognized/configured: ' . $this->ext);
338:             }
339: 
340:             $this->renderAs($controller, $this->ext);
341:             $response = $controller->response;
342:         } else {
343:             $response = $response->withCharset(Configure::read('App.encoding'));
344:         }
345: 
346:         if ($this->_config['checkHttpCache'] &&
347:             $response->checkNotModified($request)
348:         ) {
349:             $controller->setResponse($response);
350: 
351:             return false;
352:         }
353:         $controller->setResponse($response);
354:     }
355: 
356:     /**
357:      * Returns true if the current call accepts an XML response, false otherwise
358:      *
359:      * @return bool True if client accepts an XML response
360:      * @deprecated 3.7.0 Use RequestHandler::prefers('xml') instead.
361:      */
362:     public function isXml()
363:     {
364:         deprecationWarning(
365:             'RequestHandlerComponent::isXml() is deprecated. Use RequestHandlerComponent::prefers(\'xml\') instead.'
366:         );
367: 
368:         return $this->prefers('xml');
369:     }
370: 
371:     /**
372:      * Returns true if the current call accepts an RSS response, false otherwise
373:      *
374:      * @return bool True if client accepts an RSS response
375:      * @deprecated 3.7.0 Use RequestHandler::prefers('rss') instead.
376:      */
377:     public function isRss()
378:     {
379:         deprecationWarning(
380:             'RequestHandlerComponent::isRss() is deprecated. Use RequestHandlerComponent::prefers(\'rss\') instead.'
381:         );
382: 
383:         return $this->prefers('rss');
384:     }
385: 
386:     /**
387:      * Returns true if the current call accepts an Atom response, false otherwise
388:      *
389:      * @return bool True if client accepts an Atom response
390:      * @deprecated 3.7.0 Use RequestHandler::prefers('atom') instead.
391:      */
392:     public function isAtom()
393:     {
394:         deprecationWarning(
395:             'RequestHandlerComponent::isAtom() is deprecated. Use RequestHandlerComponent::prefers(\'atom\') instead.'
396:         );
397: 
398:         return $this->prefers('atom');
399:     }
400: 
401:     /**
402:      * Returns true if user agent string matches a mobile web browser, or if the
403:      * client accepts WAP content.
404:      *
405:      * @return bool True if user agent is a mobile web browser
406:      * @deprecated 3.7.0 Use ServerRequest::is('mobile') instead.
407:      */
408:     public function isMobile()
409:     {
410:         deprecationWarning(
411:             'RequestHandlerComponent::isMobile() is deprecated. Use ServerRequest::is(\'mobile\') instead.'
412:         );
413: 
414:         $request = $this->getController()->getRequest();
415: 
416:         return $request->is('mobile') || $this->accepts('wap');
417:     }
418: 
419:     /**
420:      * Returns true if the client accepts WAP content
421:      *
422:      * @return bool
423:      * @deprecated 3.7.0 Use RequestHandler::prefers('wap') instead.
424:      */
425:     public function isWap()
426:     {
427:         deprecationWarning(
428:             'RequestHandlerComponent::isWap() is deprecated. Use RequestHandlerComponent::prefers(\'wap\') instead.'
429:         );
430: 
431:         return $this->prefers('wap');
432:     }
433: 
434:     /**
435:      * Determines which content types the client accepts. Acceptance is based on
436:      * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
437:      * header. Unlike Cake\Http\ServerRequest::accepts() this method deals entirely with mapped content types.
438:      *
439:      * Usage:
440:      *
441:      * ```
442:      * $this->RequestHandler->accepts(['xml', 'html', 'json']);
443:      * ```
444:      *
445:      * Returns true if the client accepts any of the supplied types.
446:      *
447:      * ```
448:      * $this->RequestHandler->accepts('xml');
449:      * ```
450:      *
451:      * Returns true if the client accepts xml.
452:      *
453:      * @param string|array|null $type Can be null (or no parameter), a string type name, or an
454:      *   array of types
455:      * @return mixed If null or no parameter is passed, returns an array of content
456:      *   types the client accepts. If a string is passed, returns true
457:      *   if the client accepts it. If an array is passed, returns true
458:      *   if the client accepts one or more elements in the array.
459:      */
460:     public function accepts($type = null)
461:     {
462:         $controller = $this->getController();
463:         $request = $controller->getRequest();
464:         $response = $controller->getResponse();
465:         $accepted = $request->accepts();
466: 
467:         if (!$type) {
468:             return $response->mapType($accepted);
469:         }
470:         if (is_array($type)) {
471:             foreach ($type as $t) {
472:                 $t = $this->mapAlias($t);
473:                 if (in_array($t, $accepted)) {
474:                     return true;
475:                 }
476:             }
477: 
478:             return false;
479:         }
480:         if (is_string($type)) {
481:             return in_array($this->mapAlias($type), $accepted);
482:         }
483: 
484:         return false;
485:     }
486: 
487:     /**
488:      * Determines the content type of the data the client has sent (i.e. in a POST request)
489:      *
490:      * @param string|array|null $type Can be null (or no parameter), a string type name, or an array of types
491:      * @return mixed If a single type is supplied a boolean will be returned. If no type is provided
492:      *   The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
493:      *   in the request content type will be returned.
494:      */
495:     public function requestedWith($type = null)
496:     {
497:         $controller = $this->getController();
498:         $request = $controller->getRequest();
499:         $response = $controller->getResponse();
500: 
501:         if (!$request->is('post') &&
502:             !$request->is('put') &&
503:             !$request->is('patch') &&
504:             !$request->is('delete')
505:         ) {
506:             return null;
507:         }
508:         if (is_array($type)) {
509:             foreach ($type as $t) {
510:                 if ($this->requestedWith($t)) {
511:                     return $t;
512:                 }
513:             }
514: 
515:             return false;
516:         }
517: 
518:         list($contentType) = explode(';', $request->contentType());
519:         if ($type === null) {
520:             return $response->mapType($contentType);
521:         }
522:         if (is_string($type)) {
523:             return ($type === $response->mapType($contentType));
524:         }
525:     }
526: 
527:     /**
528:      * Determines which content-types the client prefers. If no parameters are given,
529:      * the single content-type that the client most likely prefers is returned. If $type is
530:      * an array, the first item in the array that the client accepts is returned.
531:      * Preference is determined primarily by the file extension parsed by the Router
532:      * if provided, and secondarily by the list of content-types provided in
533:      * HTTP_ACCEPT.
534:      *
535:      * @param string|array|null $type An optional array of 'friendly' content-type names, i.e.
536:      *   'html', 'xml', 'js', etc.
537:      * @return mixed If $type is null or not provided, the first content-type in the
538:      *    list, based on preference, is returned. If a single type is provided
539:      *    a boolean will be returned if that type is preferred.
540:      *    If an array of types are provided then the first preferred type is returned.
541:      *    If no type is provided the first preferred type is returned.
542:      */
543:     public function prefers($type = null)
544:     {
545:         $controller = $this->getController();
546:         $request = $controller->getRequest();
547:         $response = $controller->getResponse();
548:         $acceptRaw = $request->parseAccept();
549: 
550:         if (empty($acceptRaw)) {
551:             return $type ? $type === $this->ext : $this->ext;
552:         }
553:         $accepts = $response->mapType(array_shift($acceptRaw));
554: 
555:         if (!$type) {
556:             if (empty($this->ext) && !empty($accepts)) {
557:                 return $accepts[0];
558:             }
559: 
560:             return $this->ext;
561:         }
562: 
563:         $types = (array)$type;
564: 
565:         if (count($types) === 1) {
566:             if ($this->ext) {
567:                 return in_array($this->ext, $types);
568:             }
569: 
570:             return in_array($types[0], $accepts);
571:         }
572: 
573:         $intersect = array_values(array_intersect($accepts, $types));
574:         if (!$intersect) {
575:             return false;
576:         }
577: 
578:         return $intersect[0];
579:     }
580: 
581:     /**
582:      * Sets either the view class if one exists or the layout and template path of the view.
583:      * The names of these are derived from the $type input parameter.
584:      *
585:      * ### Usage:
586:      *
587:      * Render the response as an 'ajax' response.
588:      *
589:      * ```
590:      * $this->RequestHandler->renderAs($this, 'ajax');
591:      * ```
592:      *
593:      * Render the response as an xml file and force the result as a file download.
594:      *
595:      * ```
596:      * $this->RequestHandler->renderAs($this, 'xml', ['attachment' => 'myfile.xml'];
597:      * ```
598:      *
599:      * @param \Cake\Controller\Controller $controller A reference to a controller object
600:      * @param string $type Type of response to send (e.g: 'ajax')
601:      * @param array $options Array of options to use
602:      * @return void
603:      * @see \Cake\Controller\Component\RequestHandlerComponent::respondAs()
604:      */
605:     public function renderAs(Controller $controller, $type, array $options = [])
606:     {
607:         $defaults = ['charset' => 'UTF-8'];
608:         $viewClassMap = $this->getConfig('viewClassMap');
609: 
610:         if (Configure::read('App.encoding') !== null) {
611:             $defaults['charset'] = Configure::read('App.encoding');
612:         }
613:         $options += $defaults;
614: 
615:         $builder = $controller->viewBuilder();
616:         if (array_key_exists($type, $viewClassMap)) {
617:             $view = $viewClassMap[$type];
618:         } else {
619:             $view = Inflector::classify($type);
620:         }
621: 
622:         $viewClass = null;
623:         if ($builder->getClassName() === null) {
624:             $viewClass = App::className($view, 'View', 'View');
625:         }
626: 
627:         if ($viewClass) {
628:             $controller->viewClass = $viewClass;
629:             $builder->setClassName($viewClass);
630:         } else {
631:             if (!$this->_renderType) {
632:                 $builder->setTemplatePath($builder->getTemplatePath() . DIRECTORY_SEPARATOR . $type);
633:             } else {
634:                 $builder->setTemplatePath(preg_replace(
635:                     "/([\/\\\\]{$this->_renderType})$/",
636:                     DIRECTORY_SEPARATOR . $type,
637:                     $builder->getTemplatePath()
638:                 ));
639:             }
640: 
641:             $this->_renderType = $type;
642:             $builder->setLayoutPath($type);
643:         }
644: 
645:         $response = $controller->response;
646:         if ($response->getMimeType($type)) {
647:             $this->respondAs($type, $options);
648:         }
649:     }
650: 
651:     /**
652:      * Sets the response header based on type map index name. This wraps several methods
653:      * available on Cake\Http\Response. It also allows you to use Content-Type aliases.
654:      *
655:      * @param string|array $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
656:      *    like 'application/x-shockwave'.
657:      * @param array $options If $type is a friendly type name that is associated with
658:      *    more than one type of content, $index is used to select which content-type to use.
659:      * @return bool Returns false if the friendly type name given in $type does
660:      *    not exist in the type map, or if the Content-type header has
661:      *    already been set by this method.
662:      */
663:     public function respondAs($type, array $options = [])
664:     {
665:         $defaults = ['index' => null, 'charset' => null, 'attachment' => false];
666:         $options += $defaults;
667: 
668:         $cType = $type;
669:         $controller = $this->getController();
670:         $response = $controller->getResponse();
671:         $request = $controller->getRequest();
672: 
673:         if (strpos($type, '/') === false) {
674:             $cType = $response->getMimeType($type);
675:         }
676:         if (is_array($cType)) {
677:             if (isset($cType[$options['index']])) {
678:                 $cType = $cType[$options['index']];
679:             }
680: 
681:             if ($this->prefers($cType)) {
682:                 $cType = $this->prefers($cType);
683:             } else {
684:                 $cType = $cType[0];
685:             }
686:         }
687: 
688:         if (!$type) {
689:             return false;
690:         }
691:         if (!$request->getParam('requested')) {
692:             $response = $response->withType($cType);
693:         }
694:         if (!empty($options['charset'])) {
695:             $response = $response->withCharset($options['charset']);
696:         }
697:         if (!empty($options['attachment'])) {
698:             $response = $response->withDownload($options['attachment']);
699:         }
700:         $controller->setResponse($response);
701: 
702:         return true;
703:     }
704: 
705:     /**
706:      * Returns the current response type (Content-type header), or null if not alias exists
707:      *
708:      * @return mixed A string content type alias, or raw content type if no alias map exists,
709:      *  otherwise null
710:      * @deprecated 3.7.0 Use $response->mapType($response->getType()) instead.
711:      */
712:     public function responseType()
713:     {
714:         deprecationWarning(
715:             'RequestHandlerComponent::responseType() is deprecated. Use $response->mapType($response->getType()) instead.'
716:         );
717: 
718:         $response = $this->getController()->response;
719: 
720:         return $response->mapType($response->getType());
721:     }
722: 
723:     /**
724:      * Maps a content type alias back to its mime-type(s)
725:      *
726:      * @param string|array $alias String alias to convert back into a content type. Or an array of aliases to map.
727:      * @return string|null|array Null on an undefined alias. String value of the mapped alias type. If an
728:      *   alias maps to more than one content type, the first one will be returned. If an array is provided
729:      *   for $alias, an array of mapped types will be returned.
730:      */
731:     public function mapAlias($alias)
732:     {
733:         if (is_array($alias)) {
734:             return array_map([$this, 'mapAlias'], $alias);
735:         }
736:         $response = $this->getController()->response;
737:         $type = $response->getMimeType($alias);
738:         if ($type) {
739:             if (is_array($type)) {
740:                 return $type[0];
741:             }
742: 
743:             return $type;
744:         }
745: 
746:         return null;
747:     }
748: 
749:     /**
750:      * Add a new mapped input type. Mapped input types are automatically
751:      * converted by RequestHandlerComponent during the startup() callback.
752:      *
753:      * @param string $type The type alias being converted, ie. json
754:      * @param array $handler The handler array for the type. The first index should
755:      *    be the handling callback, all other arguments should be additional parameters
756:      *    for the handler.
757:      * @return void
758:      * @throws \Cake\Core\Exception\Exception
759:      * @deprecated 3.1.0 Use setConfig('addInputType', ...) instead.
760:      */
761:     public function addInputType($type, $handler)
762:     {
763:         deprecationWarning(
764:             'RequestHandlerComponent::addInputType() is deprecated. Use setConfig("inputTypeMap", ...) instead.'
765:         );
766:         if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
767:             throw new Exception('You must give a handler callback.');
768:         }
769:         $this->setConfig('inputTypeMap.' . $type, $handler);
770:     }
771: 
772:     /**
773:      * Getter/setter for viewClassMap
774:      *
775:      * @param array|string|null $type The type string or array with format `['type' => 'viewClass']` to map one or more
776:      * @param array|null $viewClass The viewClass to be used for the type without `View` appended
777:      * @return array|string Returns viewClass when only string $type is set, else array with viewClassMap
778:      * @deprecated 3.1.0 Use setConfig('viewClassMap', ...) instead.
779:      */
780:     public function viewClassMap($type = null, $viewClass = null)
781:     {
782:         deprecationWarning(
783:             'RequestHandlerComponent::viewClassMap() is deprecated. Use setConfig("viewClassMap", ...) instead.'
784:         );
785:         if (!$viewClass && is_string($type)) {
786:             return $this->getConfig('viewClassMap.' . $type);
787:         }
788:         if (is_string($type)) {
789:             $this->setConfig('viewClassMap.' . $type, $viewClass);
790:         } elseif (is_array($type)) {
791:             $this->setConfig('viewClassMap', $type, true);
792:         }
793: 
794:         return $this->getConfig('viewClassMap');
795:     }
796: }
797: 
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