ServerRequest.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Http;
  17. use BadMethodCallException;
  18. use Cake\Core\Configure;
  19. use Cake\Core\Exception\CakeException;
  20. use Cake\Http\Cookie\CookieCollection;
  21. use Cake\Http\Exception\MethodNotAllowedException;
  22. use Cake\Utility\Hash;
  23. use InvalidArgumentException;
  24. use Laminas\Diactoros\PhpInputStream;
  25. use Laminas\Diactoros\Stream;
  26. use Laminas\Diactoros\UploadedFile;
  27. use Psr\Http\Message\ServerRequestInterface;
  28. use Psr\Http\Message\StreamInterface;
  29. use Psr\Http\Message\UploadedFileInterface;
  30. use Psr\Http\Message\UriInterface;
  31. /**
  32. * A class that helps wrap Request information and particulars about a single request.
  33. * Provides methods commonly used to introspect on the request headers and request body.
  34. */
  35. class ServerRequest implements ServerRequestInterface
  36. {
  37. /**
  38. * Array of parameters parsed from the URL.
  39. *
  40. * @var array
  41. */
  42. protected $params = [
  43. 'plugin' => null,
  44. 'controller' => null,
  45. 'action' => null,
  46. '_ext' => null,
  47. 'pass' => [],
  48. ];
  49. /**
  50. * Array of POST data. Will contain form data as well as uploaded files.
  51. * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
  52. * data.
  53. *
  54. * @var object|array|null
  55. */
  56. protected $data = [];
  57. /**
  58. * Array of query string arguments
  59. *
  60. * @var array
  61. */
  62. protected $query = [];
  63. /**
  64. * Array of cookie data.
  65. *
  66. * @var array<string, mixed>
  67. */
  68. protected $cookies = [];
  69. /**
  70. * Array of environment data.
  71. *
  72. * @var array<string, mixed>
  73. */
  74. protected $_environment = [];
  75. /**
  76. * Base URL path.
  77. *
  78. * @var string
  79. */
  80. protected $base;
  81. /**
  82. * webroot path segment for the request.
  83. *
  84. * @var string
  85. */
  86. protected $webroot = '/';
  87. /**
  88. * Whether to trust HTTP_X headers set by most load balancers.
  89. * Only set to true if your application runs behind load balancers/proxies
  90. * that you control.
  91. *
  92. * @var bool
  93. */
  94. public $trustProxy = false;
  95. /**
  96. * Trusted proxies list
  97. *
  98. * @var array<string>
  99. */
  100. protected $trustedProxies = [];
  101. /**
  102. * The built in detectors used with `is()` can be modified with `addDetector()`.
  103. *
  104. * There are several ways to specify a detector, see \Cake\Http\ServerRequest::addDetector() for the
  105. * various formats and ways to define detectors.
  106. *
  107. * @var array<callable|array>
  108. */
  109. protected static $_detectors = [
  110. 'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
  111. 'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
  112. 'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
  113. 'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
  114. 'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
  115. 'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
  116. 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
  117. 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
  118. 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
  119. 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
  120. 'xml' => [
  121. 'accept' => ['application/xml', 'text/xml'],
  122. 'exclude' => ['text/html'],
  123. 'param' => '_ext',
  124. 'value' => 'xml',
  125. ],
  126. ];
  127. /**
  128. * Instance cache for results of is(something) calls
  129. *
  130. * @var array<string, bool>
  131. */
  132. protected $_detectorCache = [];
  133. /**
  134. * Request body stream. Contains php://input unless `input` constructor option is used.
  135. *
  136. * @var \Psr\Http\Message\StreamInterface
  137. */
  138. protected $stream;
  139. /**
  140. * Uri instance
  141. *
  142. * @var \Psr\Http\Message\UriInterface
  143. */
  144. protected $uri;
  145. /**
  146. * Instance of a Session object relative to this request
  147. *
  148. * @var \Cake\Http\Session
  149. */
  150. protected $session;
  151. /**
  152. * Instance of a FlashMessage object relative to this request
  153. *
  154. * @var \Cake\Http\FlashMessage
  155. */
  156. protected $flash;
  157. /**
  158. * Store the additional attributes attached to the request.
  159. *
  160. * @var array<string, mixed>
  161. */
  162. protected $attributes = [];
  163. /**
  164. * A list of properties that emulated by the PSR7 attribute methods.
  165. *
  166. * @var array<string>
  167. */
  168. protected $emulatedAttributes = ['session', 'flash', 'webroot', 'base', 'params', 'here'];
  169. /**
  170. * Array of Psr\Http\Message\UploadedFileInterface objects.
  171. *
  172. * @var array
  173. */
  174. protected $uploadedFiles = [];
  175. /**
  176. * The HTTP protocol version used.
  177. *
  178. * @var string|null
  179. */
  180. protected $protocol;
  181. /**
  182. * The request target if overridden
  183. *
  184. * @var string|null
  185. */
  186. protected $requestTarget;
  187. /**
  188. * Create a new request object.
  189. *
  190. * You can supply the data as either an array or as a string. If you use
  191. * a string you can only supply the URL for the request. Using an array will
  192. * let you provide the following keys:
  193. *
  194. * - `post` POST data or non query string data
  195. * - `query` Additional data from the query string.
  196. * - `files` Uploaded files in a normalized structure, with each leaf an instance of UploadedFileInterface.
  197. * - `cookies` Cookies for this request.
  198. * - `environment` $_SERVER and $_ENV data.
  199. * - `url` The URL without the base path for the request.
  200. * - `uri` The PSR7 UriInterface object. If null, one will be created from `url` or `environment`.
  201. * - `base` The base URL for the request.
  202. * - `webroot` The webroot directory for the request.
  203. * - `input` The data that would come from php://input this is useful for simulating
  204. * requests with put, patch or delete data.
  205. * - `session` An instance of a Session object
  206. *
  207. * @param array<string, mixed> $config An array of request data to create a request with.
  208. */
  209. public function __construct(array $config = [])
  210. {
  211. $config += [
  212. 'params' => $this->params,
  213. 'query' => [],
  214. 'post' => [],
  215. 'files' => [],
  216. 'cookies' => [],
  217. 'environment' => [],
  218. 'url' => '',
  219. 'uri' => null,
  220. 'base' => '',
  221. 'webroot' => '',
  222. 'input' => null,
  223. ];
  224. $this->_setConfig($config);
  225. }
  226. /**
  227. * Process the config/settings data into properties.
  228. *
  229. * @param array<string, mixed> $config The config data to use.
  230. * @return void
  231. */
  232. protected function _setConfig(array $config): void
  233. {
  234. if (empty($config['session'])) {
  235. $config['session'] = new Session([
  236. 'cookiePath' => $config['base'],
  237. ]);
  238. }
  239. if (empty($config['environment']['REQUEST_METHOD'])) {
  240. $config['environment']['REQUEST_METHOD'] = 'GET';
  241. }
  242. $this->cookies = $config['cookies'];
  243. if (isset($config['uri'])) {
  244. if (!$config['uri'] instanceof UriInterface) {
  245. throw new CakeException('The `uri` key must be an instance of ' . UriInterface::class);
  246. }
  247. $uri = $config['uri'];
  248. } else {
  249. if ($config['url'] !== '') {
  250. $config = $this->processUrlOption($config);
  251. }
  252. $uri = ServerRequestFactory::createUri($config['environment']);
  253. }
  254. $this->_environment = $config['environment'];
  255. $this->uri = $uri;
  256. $this->base = $config['base'];
  257. $this->webroot = $config['webroot'];
  258. if (isset($config['input'])) {
  259. $stream = new Stream('php://memory', 'rw');
  260. $stream->write($config['input']);
  261. $stream->rewind();
  262. } else {
  263. $stream = new PhpInputStream();
  264. }
  265. $this->stream = $stream;
  266. $this->data = $config['post'];
  267. $this->uploadedFiles = $config['files'];
  268. $this->query = $config['query'];
  269. $this->params = $config['params'];
  270. $this->session = $config['session'];
  271. $this->flash = new FlashMessage($this->session);
  272. }
  273. /**
  274. * Set environment vars based on `url` option to facilitate UriInterface instance generation.
  275. *
  276. * `query` option is also updated based on URL's querystring.
  277. *
  278. * @param array<string, mixed> $config Config array.
  279. * @return array<string, mixed> Update config.
  280. */
  281. protected function processUrlOption(array $config): array
  282. {
  283. if ($config['url'][0] !== '/') {
  284. $config['url'] = '/' . $config['url'];
  285. }
  286. if (strpos($config['url'], '?') !== false) {
  287. [$config['url'], $config['environment']['QUERY_STRING']] = explode('?', $config['url']);
  288. parse_str($config['environment']['QUERY_STRING'], $queryArgs);
  289. $config['query'] += $queryArgs;
  290. }
  291. $config['environment']['REQUEST_URI'] = $config['url'];
  292. return $config;
  293. }
  294. /**
  295. * Get the content type used in this request.
  296. *
  297. * @return string|null
  298. */
  299. public function contentType(): ?string
  300. {
  301. $type = $this->getEnv('CONTENT_TYPE');
  302. if ($type) {
  303. return $type;
  304. }
  305. return $this->getEnv('HTTP_CONTENT_TYPE');
  306. }
  307. /**
  308. * Returns the instance of the Session object for this request
  309. *
  310. * @return \Cake\Http\Session
  311. */
  312. public function getSession(): Session
  313. {
  314. return $this->session;
  315. }
  316. /**
  317. * Returns the instance of the FlashMessage object for this request
  318. *
  319. * @return \Cake\Http\FlashMessage
  320. */
  321. public function getFlash(): FlashMessage
  322. {
  323. return $this->flash;
  324. }
  325. /**
  326. * Get the IP the client is using, or says they are using.
  327. *
  328. * @return string The client IP.
  329. */
  330. public function clientIp(): string
  331. {
  332. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_FOR')) {
  333. $addresses = array_map('trim', explode(',', (string)$this->getEnv('HTTP_X_FORWARDED_FOR')));
  334. $trusted = (count($this->trustedProxies) > 0);
  335. $n = count($addresses);
  336. if ($trusted) {
  337. $trusted = array_diff($addresses, $this->trustedProxies);
  338. $trusted = (count($trusted) === 1);
  339. }
  340. if ($trusted) {
  341. return $addresses[0];
  342. }
  343. return $addresses[$n - 1];
  344. }
  345. if ($this->trustProxy && $this->getEnv('HTTP_X_REAL_IP')) {
  346. $ipaddr = $this->getEnv('HTTP_X_REAL_IP');
  347. } elseif ($this->trustProxy && $this->getEnv('HTTP_CLIENT_IP')) {
  348. $ipaddr = $this->getEnv('HTTP_CLIENT_IP');
  349. } else {
  350. $ipaddr = $this->getEnv('REMOTE_ADDR');
  351. }
  352. return trim((string)$ipaddr);
  353. }
  354. /**
  355. * register trusted proxies
  356. *
  357. * @param array<string> $proxies ips list of trusted proxies
  358. * @return void
  359. */
  360. public function setTrustedProxies(array $proxies): void
  361. {
  362. $this->trustedProxies = $proxies;
  363. $this->trustProxy = true;
  364. $this->uri = $this->uri->withScheme($this->scheme());
  365. }
  366. /**
  367. * Get trusted proxies
  368. *
  369. * @return array<string>
  370. */
  371. public function getTrustedProxies(): array
  372. {
  373. return $this->trustedProxies;
  374. }
  375. /**
  376. * Returns the referer that referred this request.
  377. *
  378. * @param bool $local Attempt to return a local address.
  379. * Local addresses do not contain hostnames.
  380. * @return string|null The referring address for this request or null.
  381. */
  382. public function referer(bool $local = true): ?string
  383. {
  384. $ref = $this->getEnv('HTTP_REFERER');
  385. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  386. if (!empty($ref) && !empty($base)) {
  387. if ($local && strpos($ref, $base) === 0) {
  388. $ref = substr($ref, strlen($base));
  389. if ($ref === '' || strpos($ref, '//') === 0) {
  390. $ref = '/';
  391. }
  392. if ($ref[0] !== '/') {
  393. $ref = '/' . $ref;
  394. }
  395. return $ref;
  396. }
  397. if (!$local) {
  398. return $ref;
  399. }
  400. }
  401. return null;
  402. }
  403. /**
  404. * Missing method handler, handles wrapping older style isAjax() type methods
  405. *
  406. * @param string $name The method called
  407. * @param array $params Array of parameters for the method call
  408. * @return bool
  409. * @throws \BadMethodCallException when an invalid method is called.
  410. */
  411. public function __call(string $name, array $params)
  412. {
  413. if (strpos($name, 'is') === 0) {
  414. $type = strtolower(substr($name, 2));
  415. array_unshift($params, $type);
  416. return $this->is(...$params);
  417. }
  418. throw new BadMethodCallException(sprintf('Method "%s()" does not exist', $name));
  419. }
  420. /**
  421. * Check whether a Request is a certain type.
  422. *
  423. * Uses the built-in detection rules as well as additional rules
  424. * defined with {@link \Cake\Http\ServerRequest::addDetector()}. Any detector can be called
  425. * as `is($type)` or `is$Type()`.
  426. *
  427. * @param array<string>|string $type The type of request you want to check. If an array
  428. * this method will return true if the request matches any type.
  429. * @param mixed ...$args List of arguments
  430. * @return bool Whether the request is the type you are checking.
  431. */
  432. public function is($type, ...$args): bool
  433. {
  434. if (is_array($type)) {
  435. foreach ($type as $_type) {
  436. if ($this->is($_type)) {
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. $type = strtolower($type);
  443. if (!isset(static::$_detectors[$type])) {
  444. return false;
  445. }
  446. if ($args) {
  447. return $this->_is($type, $args);
  448. }
  449. return $this->_detectorCache[$type] = $this->_detectorCache[$type] ?? $this->_is($type, $args);
  450. }
  451. /**
  452. * Clears the instance detector cache, used by the is() function
  453. *
  454. * @return void
  455. */
  456. public function clearDetectorCache(): void
  457. {
  458. $this->_detectorCache = [];
  459. }
  460. /**
  461. * Worker for the public is() function
  462. *
  463. * @param string $type The type of request you want to check.
  464. * @param array $args Array of custom detector arguments.
  465. * @return bool Whether the request is the type you are checking.
  466. */
  467. protected function _is(string $type, array $args): bool
  468. {
  469. $detect = static::$_detectors[$type];
  470. if (is_callable($detect)) {
  471. array_unshift($args, $this);
  472. return $detect(...$args);
  473. }
  474. if (isset($detect['env']) && $this->_environmentDetector($detect)) {
  475. return true;
  476. }
  477. if (isset($detect['header']) && $this->_headerDetector($detect)) {
  478. return true;
  479. }
  480. if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
  481. return true;
  482. }
  483. if (isset($detect['param']) && $this->_paramDetector($detect)) {
  484. return true;
  485. }
  486. return false;
  487. }
  488. /**
  489. * Detects if a specific accept header is present.
  490. *
  491. * @param array $detect Detector options array.
  492. * @return bool Whether the request is the type you are checking.
  493. */
  494. protected function _acceptHeaderDetector(array $detect): bool
  495. {
  496. $content = new ContentTypeNegotiation();
  497. $options = $detect['accept'];
  498. // Some detectors overlap with the default browser Accept header
  499. // For these types we use an exclude list to refine our content type
  500. // detection.
  501. $exclude = $detect['exclude'] ?? null;
  502. if ($exclude) {
  503. $options = array_merge($options, $exclude);
  504. }
  505. $accepted = $content->preferredType($this, $options);
  506. if ($accepted === null) {
  507. return false;
  508. }
  509. if ($exclude && in_array($accepted, $exclude, true)) {
  510. return false;
  511. }
  512. return true;
  513. }
  514. /**
  515. * Detects if a specific header is present.
  516. *
  517. * @param array $detect Detector options array.
  518. * @return bool Whether the request is the type you are checking.
  519. */
  520. protected function _headerDetector(array $detect): bool
  521. {
  522. foreach ($detect['header'] as $header => $value) {
  523. $header = $this->getEnv('http_' . $header);
  524. if ($header !== null) {
  525. if (!is_string($value) && !is_bool($value) && is_callable($value)) {
  526. return $value($header);
  527. }
  528. return $header === $value;
  529. }
  530. }
  531. return false;
  532. }
  533. /**
  534. * Detects if a specific request parameter is present.
  535. *
  536. * @param array $detect Detector options array.
  537. * @return bool Whether the request is the type you are checking.
  538. */
  539. protected function _paramDetector(array $detect): bool
  540. {
  541. $key = $detect['param'];
  542. if (isset($detect['value'])) {
  543. $value = $detect['value'];
  544. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  545. }
  546. if (isset($detect['options'])) {
  547. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  548. }
  549. return false;
  550. }
  551. /**
  552. * Detects if a specific environment variable is present.
  553. *
  554. * @param array $detect Detector options array.
  555. * @return bool Whether the request is the type you are checking.
  556. */
  557. protected function _environmentDetector(array $detect): bool
  558. {
  559. if (isset($detect['env'])) {
  560. if (isset($detect['value'])) {
  561. return $this->getEnv($detect['env']) == $detect['value'];
  562. }
  563. if (isset($detect['pattern'])) {
  564. return (bool)preg_match($detect['pattern'], (string)$this->getEnv($detect['env']));
  565. }
  566. if (isset($detect['options'])) {
  567. $pattern = '/' . implode('|', $detect['options']) . '/i';
  568. return (bool)preg_match($pattern, (string)$this->getEnv($detect['env']));
  569. }
  570. }
  571. return false;
  572. }
  573. /**
  574. * Check that a request matches all the given types.
  575. *
  576. * Allows you to test multiple types and union the results.
  577. * See Request::is() for how to add additional types and the
  578. * built-in types.
  579. *
  580. * @param array<string> $types The types to check.
  581. * @return bool Success.
  582. * @see \Cake\Http\ServerRequest::is()
  583. */
  584. public function isAll(array $types): bool
  585. {
  586. foreach ($types as $type) {
  587. if (!$this->is($type)) {
  588. return false;
  589. }
  590. }
  591. return true;
  592. }
  593. /**
  594. * Add a new detector to the list of detectors that a request can use.
  595. * There are several different types of detectors that can be set.
  596. *
  597. * ### Callback comparison
  598. *
  599. * Callback detectors allow you to provide a callable to handle the check.
  600. * The callback will receive the request object as its only parameter.
  601. *
  602. * ```
  603. * addDetector('custom', function ($request) { //Return a boolean });
  604. * ```
  605. *
  606. * ### Environment value comparison
  607. *
  608. * An environment value comparison, compares a value fetched from `env()` to a known value
  609. * the environment value is equality checked against the provided value.
  610. *
  611. * ```
  612. * addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST']);
  613. * ```
  614. *
  615. * ### Request parameter comparison
  616. *
  617. * Allows for custom detectors on the request parameters.
  618. *
  619. * ```
  620. * addDetector('admin', ['param' => 'prefix', 'value' => 'admin']);
  621. * ```
  622. *
  623. * ### Accept comparison
  624. *
  625. * Allows for detector to compare against Accept header value.
  626. *
  627. * ```
  628. * addDetector('csv', ['accept' => 'text/csv']);
  629. * ```
  630. *
  631. * ### Header comparison
  632. *
  633. * Allows for one or more headers to be compared.
  634. *
  635. * ```
  636. * addDetector('fancy', ['header' => ['X-Fancy' => 1]);
  637. * ```
  638. *
  639. * The `param`, `env` and comparison types allow the following
  640. * value comparison options:
  641. *
  642. * ### Pattern value comparison
  643. *
  644. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  645. *
  646. * ```
  647. * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
  648. * ```
  649. *
  650. * ### Option based comparison
  651. *
  652. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  653. * to add an already defined options detector will merge the options.
  654. *
  655. * ```
  656. * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
  657. * ```
  658. *
  659. * You can also make compare against multiple values
  660. * using the `options` key. This is useful when you want to check
  661. * if a request value is in a list of options.
  662. *
  663. * `addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'csv']]`
  664. *
  665. * @param string $name The name of the detector.
  666. * @param callable|array $detector A callable or options array for the detector definition.
  667. * @return void
  668. */
  669. public static function addDetector(string $name, $detector): void
  670. {
  671. $name = strtolower($name);
  672. if (is_callable($detector)) {
  673. static::$_detectors[$name] = $detector;
  674. return;
  675. }
  676. if (isset(static::$_detectors[$name], $detector['options'])) {
  677. /** @psalm-suppress PossiblyInvalidArgument */
  678. $detector = Hash::merge(static::$_detectors[$name], $detector);
  679. }
  680. static::$_detectors[$name] = $detector;
  681. }
  682. /**
  683. * Normalize a header name into the SERVER version.
  684. *
  685. * @param string $name The header name.
  686. * @return string The normalized header name.
  687. */
  688. protected function normalizeHeaderName(string $name): string
  689. {
  690. $name = str_replace('-', '_', strtoupper($name));
  691. if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'], true)) {
  692. $name = 'HTTP_' . $name;
  693. }
  694. return $name;
  695. }
  696. /**
  697. * Get all headers in the request.
  698. *
  699. * Returns an associative array where the header names are
  700. * the keys and the values are a list of header values.
  701. *
  702. * While header names are not case-sensitive, getHeaders() will normalize
  703. * the headers.
  704. *
  705. * @return array<string[]> An associative array of headers and their values.
  706. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  707. */
  708. public function getHeaders(): array
  709. {
  710. $headers = [];
  711. foreach ($this->_environment as $key => $value) {
  712. $name = null;
  713. if (strpos($key, 'HTTP_') === 0) {
  714. $name = substr($key, 5);
  715. }
  716. if (strpos($key, 'CONTENT_') === 0) {
  717. $name = $key;
  718. }
  719. if ($name !== null) {
  720. $name = str_replace('_', ' ', strtolower($name));
  721. $name = str_replace(' ', '-', ucwords($name));
  722. $headers[$name] = (array)$value;
  723. }
  724. }
  725. return $headers;
  726. }
  727. /**
  728. * Check if a header is set in the request.
  729. *
  730. * @param string $name The header you want to get (case-insensitive)
  731. * @return bool Whether the header is defined.
  732. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  733. */
  734. public function hasHeader($name): bool
  735. {
  736. $name = $this->normalizeHeaderName($name);
  737. return isset($this->_environment[$name]);
  738. }
  739. /**
  740. * Get a single header from the request.
  741. *
  742. * Return the header value as an array. If the header
  743. * is not present an empty array will be returned.
  744. *
  745. * @param string $name The header you want to get (case-insensitive)
  746. * @return array<string> An associative array of headers and their values.
  747. * If the header doesn't exist, an empty array will be returned.
  748. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  749. */
  750. public function getHeader($name): array
  751. {
  752. $name = $this->normalizeHeaderName($name);
  753. if (isset($this->_environment[$name])) {
  754. return (array)$this->_environment[$name];
  755. }
  756. return [];
  757. }
  758. /**
  759. * Get a single header as a string from the request.
  760. *
  761. * @param string $name The header you want to get (case-insensitive)
  762. * @return string Header values collapsed into a comma separated string.
  763. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  764. */
  765. public function getHeaderLine($name): string
  766. {
  767. $value = $this->getHeader($name);
  768. return implode(', ', $value);
  769. }
  770. /**
  771. * Get a modified request with the provided header.
  772. *
  773. * @param string $name The header name.
  774. * @param array|string $value The header value
  775. * @return static
  776. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  777. */
  778. public function withHeader($name, $value)
  779. {
  780. $new = clone $this;
  781. $name = $this->normalizeHeaderName($name);
  782. $new->_environment[$name] = $value;
  783. return $new;
  784. }
  785. /**
  786. * Get a modified request with the provided header.
  787. *
  788. * Existing header values will be retained. The provided value
  789. * will be appended into the existing values.
  790. *
  791. * @param string $name The header name.
  792. * @param array|string $value The header value
  793. * @return static
  794. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  795. */
  796. public function withAddedHeader($name, $value)
  797. {
  798. $new = clone $this;
  799. $name = $this->normalizeHeaderName($name);
  800. $existing = [];
  801. if (isset($new->_environment[$name])) {
  802. $existing = (array)$new->_environment[$name];
  803. }
  804. $existing = array_merge($existing, (array)$value);
  805. $new->_environment[$name] = $existing;
  806. return $new;
  807. }
  808. /**
  809. * Get a modified request without a provided header.
  810. *
  811. * @param string $name The header name to remove.
  812. * @return static
  813. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  814. */
  815. public function withoutHeader($name)
  816. {
  817. $new = clone $this;
  818. $name = $this->normalizeHeaderName($name);
  819. unset($new->_environment[$name]);
  820. return $new;
  821. }
  822. /**
  823. * Get the HTTP method used for this request.
  824. * There are a few ways to specify a method.
  825. *
  826. * - If your client supports it you can use native HTTP methods.
  827. * - You can set the HTTP-X-Method-Override header.
  828. * - You can submit an input with the name `_method`
  829. *
  830. * Any of these 3 approaches can be used to set the HTTP method used
  831. * by CakePHP internally, and will effect the result of this method.
  832. *
  833. * @return string The name of the HTTP method used.
  834. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  835. */
  836. public function getMethod(): string
  837. {
  838. return (string)$this->getEnv('REQUEST_METHOD');
  839. }
  840. /**
  841. * Update the request method and get a new instance.
  842. *
  843. * @param string $method The HTTP method to use.
  844. * @return static A new instance with the updated method.
  845. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  846. */
  847. public function withMethod($method)
  848. {
  849. $new = clone $this;
  850. if (
  851. !is_string($method) ||
  852. !preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)
  853. ) {
  854. throw new InvalidArgumentException(sprintf(
  855. 'Unsupported HTTP method "%s" provided',
  856. $method
  857. ));
  858. }
  859. $new->_environment['REQUEST_METHOD'] = $method;
  860. return $new;
  861. }
  862. /**
  863. * Get all the server environment parameters.
  864. *
  865. * Read all of the 'environment' or 'server' data that was
  866. * used to create this request.
  867. *
  868. * @return array
  869. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  870. */
  871. public function getServerParams(): array
  872. {
  873. return $this->_environment;
  874. }
  875. /**
  876. * Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values
  877. * use the alternative getQuery() method.
  878. *
  879. * @return array
  880. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  881. */
  882. public function getQueryParams(): array
  883. {
  884. return $this->query;
  885. }
  886. /**
  887. * Update the query string data and get a new instance.
  888. *
  889. * @param array $query The query string data to use
  890. * @return static A new instance with the updated query string data.
  891. * @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  892. */
  893. public function withQueryParams(array $query)
  894. {
  895. $new = clone $this;
  896. $new->query = $query;
  897. return $new;
  898. }
  899. /**
  900. * Get the host that the request was handled on.
  901. *
  902. * @return string|null
  903. */
  904. public function host(): ?string
  905. {
  906. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_HOST')) {
  907. return $this->getEnv('HTTP_X_FORWARDED_HOST');
  908. }
  909. return $this->getEnv('HTTP_HOST');
  910. }
  911. /**
  912. * Get the port the request was handled on.
  913. *
  914. * @return string|null
  915. */
  916. public function port(): ?string
  917. {
  918. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PORT')) {
  919. return $this->getEnv('HTTP_X_FORWARDED_PORT');
  920. }
  921. return $this->getEnv('SERVER_PORT');
  922. }
  923. /**
  924. * Get the current url scheme used for the request.
  925. *
  926. * e.g. 'http', or 'https'
  927. *
  928. * @return string|null The scheme used for the request.
  929. */
  930. public function scheme(): ?string
  931. {
  932. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PROTO')) {
  933. return $this->getEnv('HTTP_X_FORWARDED_PROTO');
  934. }
  935. return $this->getEnv('HTTPS') ? 'https' : 'http';
  936. }
  937. /**
  938. * Get the domain name and include $tldLength segments of the tld.
  939. *
  940. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  941. * While `example.co.uk` contains 2.
  942. * @return string Domain name without subdomains.
  943. */
  944. public function domain(int $tldLength = 1): string
  945. {
  946. $host = $this->host();
  947. if (empty($host)) {
  948. return '';
  949. }
  950. $segments = explode('.', $host);
  951. $domain = array_slice($segments, -1 * ($tldLength + 1));
  952. return implode('.', $domain);
  953. }
  954. /**
  955. * Get the subdomains for a host.
  956. *
  957. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  958. * While `example.co.uk` contains 2.
  959. * @return array<string> An array of subdomains.
  960. */
  961. public function subdomains(int $tldLength = 1): array
  962. {
  963. $host = $this->host();
  964. if (empty($host)) {
  965. return [];
  966. }
  967. $segments = explode('.', $host);
  968. return array_slice($segments, 0, -1 * ($tldLength + 1));
  969. }
  970. /**
  971. * Find out which content types the client accepts or check if they accept a
  972. * particular type of content.
  973. *
  974. * #### Get all types:
  975. *
  976. * ```
  977. * $this->request->accepts();
  978. * ```
  979. *
  980. * #### Check for a single type:
  981. *
  982. * ```
  983. * $this->request->accepts('application/json');
  984. * ```
  985. *
  986. * This method will order the returned content types by the preference values indicated
  987. * by the client.
  988. *
  989. * @param string|null $type The content type to check for. Leave null to get all types a client accepts.
  990. * @return array<string>|bool Either an array of all the types the client accepts or a boolean if they accept the
  991. * provided type.
  992. */
  993. public function accepts(?string $type = null)
  994. {
  995. $content = new ContentTypeNegotiation();
  996. if ($type) {
  997. return $content->preferredType($this, [$type]) !== null;
  998. }
  999. $accept = [];
  1000. foreach ($content->parseAccept($this) as $types) {
  1001. $accept = array_merge($accept, $types);
  1002. }
  1003. return $accept;
  1004. }
  1005. /**
  1006. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  1007. * as the keys, and pref values as the values.
  1008. *
  1009. * Generally you want to use {@link \Cake\Http\ServerRequest::accepts()} to get a simple list
  1010. * of the accepted content types.
  1011. *
  1012. * @return array An array of `prefValue => [content/types]`
  1013. * @deprecated 4.4.0 Use `accepts()` or `ContentTypeNegotiation` class instead.
  1014. */
  1015. public function parseAccept(): array
  1016. {
  1017. return (new ContentTypeNegotiation())->parseAccept($this);
  1018. }
  1019. /**
  1020. * Get the languages accepted by the client, or check if a specific language is accepted.
  1021. *
  1022. * Get the list of accepted languages:
  1023. *
  1024. * ```$request->acceptLanguage();```
  1025. *
  1026. * Check if a specific language is accepted:
  1027. *
  1028. * ```$request->acceptLanguage('es-es');```
  1029. *
  1030. * @param string|null $language The language to test.
  1031. * @return array|bool If a $language is provided, a boolean. Otherwise, the array of accepted languages.
  1032. */
  1033. public function acceptLanguage(?string $language = null)
  1034. {
  1035. $content = new ContentTypeNegotiation();
  1036. if ($language !== null) {
  1037. return $content->acceptLanguage($this, $language);
  1038. }
  1039. return $content->acceptedLanguages($this);
  1040. }
  1041. /**
  1042. * Read a specific query value or dotted path.
  1043. *
  1044. * Developers are encouraged to use getQueryParams() if they need the whole query array,
  1045. * as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params.
  1046. *
  1047. * ### PSR-7 Alternative
  1048. *
  1049. * ```
  1050. * $value = Hash::get($request->getQueryParams(), 'Post.id');
  1051. * ```
  1052. *
  1053. * @param string|null $name The name or dotted path to the query param or null to read all.
  1054. * @param mixed $default The default value if the named parameter is not set, and $name is not null.
  1055. * @return array|string|null Query data.
  1056. * @see ServerRequest::getQueryParams()
  1057. */
  1058. public function getQuery(?string $name = null, $default = null)
  1059. {
  1060. if ($name === null) {
  1061. return $this->query;
  1062. }
  1063. return Hash::get($this->query, $name, $default);
  1064. }
  1065. /**
  1066. * Provides a safe accessor for request data. Allows
  1067. * you to use Hash::get() compatible paths.
  1068. *
  1069. * ### Reading values.
  1070. *
  1071. * ```
  1072. * // get all data
  1073. * $request->getData();
  1074. *
  1075. * // Read a specific field.
  1076. * $request->getData('Post.title');
  1077. *
  1078. * // With a default value.
  1079. * $request->getData('Post.not there', 'default value');
  1080. * ```
  1081. *
  1082. * When reading values you will get `null` for keys/values that do not exist.
  1083. *
  1084. * Developers are encouraged to use getParsedBody() if they need the whole data array,
  1085. * as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params.
  1086. *
  1087. * ### PSR-7 Alternative
  1088. *
  1089. * ```
  1090. * $value = Hash::get($request->getParsedBody(), 'Post.id');
  1091. * ```
  1092. *
  1093. * @param string|null $name Dot separated name of the value to read. Or null to read all data.
  1094. * @param mixed $default The default data.
  1095. * @return mixed The value being read.
  1096. */
  1097. public function getData(?string $name = null, $default = null)
  1098. {
  1099. if ($name === null) {
  1100. return $this->data;
  1101. }
  1102. if (!is_array($this->data) && $name) {
  1103. return $default;
  1104. }
  1105. /** @psalm-suppress PossiblyNullArgument */
  1106. return Hash::get($this->data, $name, $default);
  1107. }
  1108. /**
  1109. * Read data from `php://input`. Useful when interacting with XML or JSON
  1110. * request body content.
  1111. *
  1112. * Getting input with a decoding function:
  1113. *
  1114. * ```
  1115. * $this->request->input('json_decode');
  1116. * ```
  1117. *
  1118. * Getting input using a decoding function, and additional params:
  1119. *
  1120. * ```
  1121. * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
  1122. * ```
  1123. *
  1124. * Any additional parameters are applied to the callback in the order they are given.
  1125. *
  1126. * @deprecated 4.1.0 Use `(string)$request->getBody()` to get the raw PHP input
  1127. * as string; use `BodyParserMiddleware` to parse the request body so that it's
  1128. * available as array/object through `$request->getParsedBody()`.
  1129. * @param callable|null $callback A decoding callback that will convert the string data to another
  1130. * representation. Leave empty to access the raw input data. You can also
  1131. * supply additional parameters for the decoding callback using var args, see above.
  1132. * @param mixed ...$args The additional arguments
  1133. * @return mixed The decoded/processed request data.
  1134. */
  1135. public function input(?callable $callback = null, ...$args)
  1136. {
  1137. deprecationWarning(
  1138. 'Use `(string)$request->getBody()` to get the raw PHP input as string; '
  1139. . 'use `BodyParserMiddleware` to parse the request body so that it\'s available as array/object '
  1140. . 'through $request->getParsedBody()'
  1141. );
  1142. $this->stream->rewind();
  1143. $input = $this->stream->getContents();
  1144. if ($callback) {
  1145. array_unshift($args, $input);
  1146. return $callback(...$args);
  1147. }
  1148. return $input;
  1149. }
  1150. /**
  1151. * Read cookie data from the request's cookie data.
  1152. *
  1153. * @param string $key The key or dotted path you want to read.
  1154. * @param array|string|null $default The default value if the cookie is not set.
  1155. * @return array|string|null Either the cookie value, or null if the value doesn't exist.
  1156. */
  1157. public function getCookie(string $key, $default = null)
  1158. {
  1159. return Hash::get($this->cookies, $key, $default);
  1160. }
  1161. /**
  1162. * Get a cookie collection based on the request's cookies
  1163. *
  1164. * The CookieCollection lets you interact with request cookies using
  1165. * `\Cake\Http\Cookie\Cookie` objects and can make converting request cookies
  1166. * into response cookies easier.
  1167. *
  1168. * This method will create a new cookie collection each time it is called.
  1169. * This is an optimization that allows fewer objects to be allocated until
  1170. * the more complex CookieCollection is needed. In general you should prefer
  1171. * `getCookie()` and `getCookieParams()` over this method. Using a CookieCollection
  1172. * is ideal if your cookies contain complex JSON encoded data.
  1173. *
  1174. * @return \Cake\Http\Cookie\CookieCollection
  1175. */
  1176. public function getCookieCollection(): CookieCollection
  1177. {
  1178. return CookieCollection::createFromServerRequest($this);
  1179. }
  1180. /**
  1181. * Replace the cookies in the request with those contained in
  1182. * the provided CookieCollection.
  1183. *
  1184. * @param \Cake\Http\Cookie\CookieCollection $cookies The cookie collection
  1185. * @return static
  1186. */
  1187. public function withCookieCollection(CookieCollection $cookies)
  1188. {
  1189. $new = clone $this;
  1190. $values = [];
  1191. foreach ($cookies as $cookie) {
  1192. $values[$cookie->getName()] = $cookie->getValue();
  1193. }
  1194. $new->cookies = $values;
  1195. return $new;
  1196. }
  1197. /**
  1198. * Get all the cookie data from the request.
  1199. *
  1200. * @return array<string, mixed> An array of cookie data.
  1201. */
  1202. public function getCookieParams(): array
  1203. {
  1204. return $this->cookies;
  1205. }
  1206. /**
  1207. * Replace the cookies and get a new request instance.
  1208. *
  1209. * @param array $cookies The new cookie data to use.
  1210. * @return static
  1211. */
  1212. public function withCookieParams(array $cookies)
  1213. {
  1214. $new = clone $this;
  1215. $new->cookies = $cookies;
  1216. return $new;
  1217. }
  1218. /**
  1219. * Get the parsed request body data.
  1220. *
  1221. * If the request Content-Type is either application/x-www-form-urlencoded
  1222. * or multipart/form-data, and the request method is POST, this will be the
  1223. * post data. For other content types, it may be the deserialized request
  1224. * body.
  1225. *
  1226. * @return object|array|null The deserialized body parameters, if any.
  1227. * These will typically be an array.
  1228. */
  1229. public function getParsedBody()
  1230. {
  1231. return $this->data;
  1232. }
  1233. /**
  1234. * Update the parsed body and get a new instance.
  1235. *
  1236. * @param object|array|null $data The deserialized body data. This will
  1237. * typically be in an array or object.
  1238. * @return static
  1239. */
  1240. public function withParsedBody($data)
  1241. {
  1242. $new = clone $this;
  1243. $new->data = $data;
  1244. return $new;
  1245. }
  1246. /**
  1247. * Retrieves the HTTP protocol version as a string.
  1248. *
  1249. * @return string HTTP protocol version.
  1250. */
  1251. public function getProtocolVersion(): string
  1252. {
  1253. if ($this->protocol) {
  1254. return $this->protocol;
  1255. }
  1256. // Lazily populate this data as it is generally not used.
  1257. preg_match('/^HTTP\/([\d.]+)$/', (string)$this->getEnv('SERVER_PROTOCOL'), $match);
  1258. $protocol = '1.1';
  1259. if (isset($match[1])) {
  1260. $protocol = $match[1];
  1261. }
  1262. $this->protocol = $protocol;
  1263. return $this->protocol;
  1264. }
  1265. /**
  1266. * Return an instance with the specified HTTP protocol version.
  1267. *
  1268. * The version string MUST contain only the HTTP version number (e.g.,
  1269. * "1.1", "1.0").
  1270. *
  1271. * @param string $version HTTP protocol version
  1272. * @return static
  1273. */
  1274. public function withProtocolVersion($version)
  1275. {
  1276. if (!preg_match('/^(1\.[01]|2)$/', $version)) {
  1277. throw new InvalidArgumentException("Unsupported protocol version '{$version}' provided");
  1278. }
  1279. $new = clone $this;
  1280. $new->protocol = $version;
  1281. return $new;
  1282. }
  1283. /**
  1284. * Get a value from the request's environment data.
  1285. * Fallback to using env() if the key is not set in the $environment property.
  1286. *
  1287. * @param string $key The key you want to read from.
  1288. * @param string|null $default Default value when trying to retrieve an environment
  1289. * variable's value that does not exist.
  1290. * @return string|null Either the environment value, or null if the value doesn't exist.
  1291. */
  1292. public function getEnv(string $key, ?string $default = null): ?string
  1293. {
  1294. $key = strtoupper($key);
  1295. if (!array_key_exists($key, $this->_environment)) {
  1296. $this->_environment[$key] = env($key);
  1297. }
  1298. return $this->_environment[$key] !== null ? (string)$this->_environment[$key] : $default;
  1299. }
  1300. /**
  1301. * Update the request with a new environment data element.
  1302. *
  1303. * Returns an updated request object. This method returns
  1304. * a *new* request object and does not mutate the request in-place.
  1305. *
  1306. * @param string $key The key you want to write to.
  1307. * @param string $value Value to set
  1308. * @return static
  1309. */
  1310. public function withEnv(string $key, string $value)
  1311. {
  1312. $new = clone $this;
  1313. $new->_environment[$key] = $value;
  1314. $new->clearDetectorCache();
  1315. return $new;
  1316. }
  1317. /**
  1318. * Allow only certain HTTP request methods, if the request method does not match
  1319. * a 405 error will be shown and the required "Allow" response header will be set.
  1320. *
  1321. * Example:
  1322. *
  1323. * $this->request->allowMethod('post');
  1324. * or
  1325. * $this->request->allowMethod(['post', 'delete']);
  1326. *
  1327. * If the request would be GET, response header "Allow: POST, DELETE" will be set
  1328. * and a 405 error will be returned.
  1329. *
  1330. * @param array<string>|string $methods Allowed HTTP request methods.
  1331. * @return true
  1332. * @throws \Cake\Http\Exception\MethodNotAllowedException
  1333. */
  1334. public function allowMethod($methods): bool
  1335. {
  1336. $methods = (array)$methods;
  1337. foreach ($methods as $method) {
  1338. if ($this->is($method)) {
  1339. return true;
  1340. }
  1341. }
  1342. $allowed = strtoupper(implode(', ', $methods));
  1343. $e = new MethodNotAllowedException();
  1344. $e->setHeader('Allow', $allowed);
  1345. throw $e;
  1346. }
  1347. /**
  1348. * Update the request with a new request data element.
  1349. *
  1350. * Returns an updated request object. This method returns
  1351. * a *new* request object and does not mutate the request in-place.
  1352. *
  1353. * Use `withParsedBody()` if you need to replace the all request data.
  1354. *
  1355. * @param string $name The dot separated path to insert $value at.
  1356. * @param mixed $value The value to insert into the request data.
  1357. * @return static
  1358. */
  1359. public function withData(string $name, $value)
  1360. {
  1361. $copy = clone $this;
  1362. if (is_array($copy->data)) {
  1363. $copy->data = Hash::insert($copy->data, $name, $value);
  1364. }
  1365. return $copy;
  1366. }
  1367. /**
  1368. * Update the request removing a data element.
  1369. *
  1370. * Returns an updated request object. This method returns
  1371. * a *new* request object and does not mutate the request in-place.
  1372. *
  1373. * @param string $name The dot separated path to remove.
  1374. * @return static
  1375. */
  1376. public function withoutData(string $name)
  1377. {
  1378. $copy = clone $this;
  1379. if (is_array($copy->data)) {
  1380. $copy->data = Hash::remove($copy->data, $name);
  1381. }
  1382. return $copy;
  1383. }
  1384. /**
  1385. * Update the request with a new routing parameter
  1386. *
  1387. * Returns an updated request object. This method returns
  1388. * a *new* request object and does not mutate the request in-place.
  1389. *
  1390. * @param string $name The dot separated path to insert $value at.
  1391. * @param mixed $value The value to insert into the the request parameters.
  1392. * @return static
  1393. */
  1394. public function withParam(string $name, $value)
  1395. {
  1396. $copy = clone $this;
  1397. $copy->params = Hash::insert($copy->params, $name, $value);
  1398. return $copy;
  1399. }
  1400. /**
  1401. * Safely access the values in $this->params.
  1402. *
  1403. * @param string $name The name or dotted path to parameter.
  1404. * @param mixed $default The default value if `$name` is not set. Default `null`.
  1405. * @return mixed
  1406. */
  1407. public function getParam(string $name, $default = null)
  1408. {
  1409. return Hash::get($this->params, $name, $default);
  1410. }
  1411. /**
  1412. * Return an instance with the specified request attribute.
  1413. *
  1414. * @param string $name The attribute name.
  1415. * @param mixed $value The value of the attribute.
  1416. * @return static
  1417. */
  1418. public function withAttribute($name, $value)
  1419. {
  1420. $new = clone $this;
  1421. if (in_array($name, $this->emulatedAttributes, true)) {
  1422. $new->{$name} = $value;
  1423. } else {
  1424. $new->attributes[$name] = $value;
  1425. }
  1426. return $new;
  1427. }
  1428. /**
  1429. * Return an instance without the specified request attribute.
  1430. *
  1431. * @param string $name The attribute name.
  1432. * @return static
  1433. * @throws \InvalidArgumentException
  1434. */
  1435. public function withoutAttribute($name)
  1436. {
  1437. $new = clone $this;
  1438. if (in_array($name, $this->emulatedAttributes, true)) {
  1439. throw new InvalidArgumentException(
  1440. "You cannot unset '$name'. It is a required CakePHP attribute."
  1441. );
  1442. }
  1443. unset($new->attributes[$name]);
  1444. return $new;
  1445. }
  1446. /**
  1447. * Read an attribute from the request, or get the default
  1448. *
  1449. * @param string $name The attribute name.
  1450. * @param mixed|null $default The default value if the attribute has not been set.
  1451. * @return mixed
  1452. */
  1453. public function getAttribute($name, $default = null)
  1454. {
  1455. if (in_array($name, $this->emulatedAttributes, true)) {
  1456. if ($name === 'here') {
  1457. return $this->base . $this->uri->getPath();
  1458. }
  1459. return $this->{$name};
  1460. }
  1461. if (array_key_exists($name, $this->attributes)) {
  1462. return $this->attributes[$name];
  1463. }
  1464. return $default;
  1465. }
  1466. /**
  1467. * Get all the attributes in the request.
  1468. *
  1469. * This will include the params, webroot, base, and here attributes that CakePHP
  1470. * provides.
  1471. *
  1472. * @return array<string, mixed>
  1473. */
  1474. public function getAttributes(): array
  1475. {
  1476. $emulated = [
  1477. 'params' => $this->params,
  1478. 'webroot' => $this->webroot,
  1479. 'base' => $this->base,
  1480. 'here' => $this->base . $this->uri->getPath(),
  1481. ];
  1482. return $this->attributes + $emulated;
  1483. }
  1484. /**
  1485. * Get the uploaded file from a dotted path.
  1486. *
  1487. * @param string $path The dot separated path to the file you want.
  1488. * @return \Psr\Http\Message\UploadedFileInterface|null
  1489. */
  1490. public function getUploadedFile(string $path): ?UploadedFileInterface
  1491. {
  1492. $file = Hash::get($this->uploadedFiles, $path);
  1493. if (!$file instanceof UploadedFile) {
  1494. return null;
  1495. }
  1496. return $file;
  1497. }
  1498. /**
  1499. * Get the array of uploaded files from the request.
  1500. *
  1501. * @return array
  1502. */
  1503. public function getUploadedFiles(): array
  1504. {
  1505. return $this->uploadedFiles;
  1506. }
  1507. /**
  1508. * Update the request replacing the files, and creating a new instance.
  1509. *
  1510. * @param array $uploadedFiles An array of uploaded file objects.
  1511. * @return static
  1512. * @throws \InvalidArgumentException when $files contains an invalid object.
  1513. */
  1514. public function withUploadedFiles(array $uploadedFiles)
  1515. {
  1516. $this->validateUploadedFiles($uploadedFiles, '');
  1517. $new = clone $this;
  1518. $new->uploadedFiles = $uploadedFiles;
  1519. return $new;
  1520. }
  1521. /**
  1522. * Recursively validate uploaded file data.
  1523. *
  1524. * @param array $uploadedFiles The new files array to validate.
  1525. * @param string $path The path thus far.
  1526. * @return void
  1527. * @throws \InvalidArgumentException If any leaf elements are not valid files.
  1528. */
  1529. protected function validateUploadedFiles(array $uploadedFiles, string $path): void
  1530. {
  1531. foreach ($uploadedFiles as $key => $file) {
  1532. if (is_array($file)) {
  1533. $this->validateUploadedFiles($file, $key . '.');
  1534. continue;
  1535. }
  1536. if (!$file instanceof UploadedFileInterface) {
  1537. throw new InvalidArgumentException("Invalid file at '{$path}{$key}'");
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Gets the body of the message.
  1543. *
  1544. * @return \Psr\Http\Message\StreamInterface Returns the body as a stream.
  1545. */
  1546. public function getBody(): StreamInterface
  1547. {
  1548. return $this->stream;
  1549. }
  1550. /**
  1551. * Return an instance with the specified message body.
  1552. *
  1553. * @param \Psr\Http\Message\StreamInterface $body The new request body
  1554. * @return static
  1555. */
  1556. public function withBody(StreamInterface $body)
  1557. {
  1558. $new = clone $this;
  1559. $new->stream = $body;
  1560. return $new;
  1561. }
  1562. /**
  1563. * Retrieves the URI instance.
  1564. *
  1565. * @return \Psr\Http\Message\UriInterface Returns a UriInterface instance
  1566. * representing the URI of the request.
  1567. */
  1568. public function getUri(): UriInterface
  1569. {
  1570. return $this->uri;
  1571. }
  1572. /**
  1573. * Return an instance with the specified uri
  1574. *
  1575. * *Warning* Replacing the Uri will not update the `base`, `webroot`,
  1576. * and `url` attributes.
  1577. *
  1578. * @param \Psr\Http\Message\UriInterface $uri The new request uri
  1579. * @param bool $preserveHost Whether the host should be retained.
  1580. * @return static
  1581. */
  1582. public function withUri(UriInterface $uri, $preserveHost = false)
  1583. {
  1584. $new = clone $this;
  1585. $new->uri = $uri;
  1586. if ($preserveHost && $this->hasHeader('Host')) {
  1587. return $new;
  1588. }
  1589. $host = $uri->getHost();
  1590. if (!$host) {
  1591. return $new;
  1592. }
  1593. $port = $uri->getPort();
  1594. if ($port) {
  1595. $host .= ':' . $port;
  1596. }
  1597. $new->_environment['HTTP_HOST'] = $host;
  1598. return $new;
  1599. }
  1600. /**
  1601. * Create a new instance with a specific request-target.
  1602. *
  1603. * You can use this method to overwrite the request target that is
  1604. * inferred from the request's Uri. This also lets you change the request
  1605. * target's form to an absolute-form, authority-form or asterisk-form
  1606. *
  1607. * @link https://tools.ietf.org/html/rfc7230#section-2.7 (for the various
  1608. * request-target forms allowed in request messages)
  1609. * @param string $requestTarget The request target.
  1610. * @return static
  1611. * @psalm-suppress MoreSpecificImplementedParamType
  1612. */
  1613. public function withRequestTarget($requestTarget)
  1614. {
  1615. $new = clone $this;
  1616. $new->requestTarget = $requestTarget;
  1617. return $new;
  1618. }
  1619. /**
  1620. * Retrieves the request's target.
  1621. *
  1622. * Retrieves the message's request-target either as it was requested,
  1623. * or as set with `withRequestTarget()`. By default this will return the
  1624. * application relative path without base directory, and the query string
  1625. * defined in the SERVER environment.
  1626. *
  1627. * @return string
  1628. */
  1629. public function getRequestTarget(): string
  1630. {
  1631. if ($this->requestTarget !== null) {
  1632. return $this->requestTarget;
  1633. }
  1634. $target = $this->uri->getPath();
  1635. if ($this->uri->getQuery()) {
  1636. $target .= '?' . $this->uri->getQuery();
  1637. }
  1638. if (empty($target)) {
  1639. $target = '/';
  1640. }
  1641. return $target;
  1642. }
  1643. /**
  1644. * Get the path of current request.
  1645. *
  1646. * @return string
  1647. * @since 3.6.1
  1648. */
  1649. public function getPath(): string
  1650. {
  1651. if ($this->requestTarget === null) {
  1652. return $this->uri->getPath();
  1653. }
  1654. [$path] = explode('?', $this->requestTarget);
  1655. return $path;
  1656. }
  1657. }