ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Request.php
Go to the documentation of this file.
1 <?php
9 namespace Slim\Http;
10 
11 use Closure;
18 use Slim\Collection;
21 
33 class Request extends Message implements ServerRequestInterface
34 {
40  protected $method;
41 
47  protected $originalMethod;
48 
54  protected $uri;
55 
61  protected $requestTarget;
62 
68  protected $queryParams;
69 
75  protected $cookies;
76 
82  protected $serverParams;
83 
89  protected $attributes;
90 
96  protected $bodyParsed = false;
97 
103  protected $bodyParsers = [];
104 
110  protected $uploadedFiles;
111 
118  protected $validMethods = [
119  'CONNECT' => 1,
120  'DELETE' => 1,
121  'GET' => 1,
122  'HEAD' => 1,
123  'OPTIONS' => 1,
124  'PATCH' => 1,
125  'POST' => 1,
126  'PUT' => 1,
127  'TRACE' => 1,
128  ];
129 
138  public static function createFromEnvironment(Environment $environment)
139  {
140  $method = $environment['REQUEST_METHOD'];
141  $uri = Uri::createFromEnvironment($environment);
143  $cookies = Cookies::parseHeader($headers->get('Cookie', []));
144  $serverParams = $environment->all();
145  $body = new RequestBody();
147 
149 
150  if ($method === 'POST' &&
151  in_array($request->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data'])
152  ) {
153  // parsed body must be $_POST
154  $request = $request->withParsedBody($_POST);
155  }
156  return $request;
157  }
158 
173  public function __construct(
174  $method,
177  array $cookies,
178  array $serverParams,
180  array $uploadedFiles = []
181  ) {
182  try {
183  $this->originalMethod = $this->filterMethod($method);
184  } catch (InvalidMethodException $e) {
185  $this->originalMethod = $method;
186  }
187 
188  $this->uri = $uri;
189  $this->headers = $headers;
190  $this->cookies = $cookies;
191  $this->serverParams = $serverParams;
192  $this->attributes = new Collection();
193  $this->body = $body;
194  $this->uploadedFiles = $uploadedFiles;
195 
196  if (isset($serverParams['SERVER_PROTOCOL'])) {
197  $this->protocolVersion = str_replace('HTTP/', '', $serverParams['SERVER_PROTOCOL']);
198  }
199 
200  if (!$this->headers->has('Host') && $this->uri->getHost() !== '') {
201  $port = $this->uri->getPort() ? ":{$this->uri->getPort()}" : '';
202 
203  $this->headers->set('Host', $this->uri->getHost() . $port);
204  }
205 
206  $this->registerMediaTypeParser('application/json', function ($input) {
207  $result = json_decode($input, true);
208  if (!is_array($result)) {
209  return null;
210  }
211  return $result;
212  });
213 
214  $this->registerMediaTypeParser('application/xml', function ($input) {
215  $backup = libxml_disable_entity_loader(true);
216  $backup_errors = libxml_use_internal_errors(true);
217  $result = simplexml_load_string($input);
218  libxml_disable_entity_loader($backup);
219  libxml_clear_errors();
220  libxml_use_internal_errors($backup_errors);
221  if ($result === false) {
222  return null;
223  }
224  return $result;
225  });
226 
227  $this->registerMediaTypeParser('text/xml', function ($input) {
228  $backup = libxml_disable_entity_loader(true);
229  $backup_errors = libxml_use_internal_errors(true);
230  $result = simplexml_load_string($input);
231  libxml_disable_entity_loader($backup);
232  libxml_clear_errors();
233  libxml_use_internal_errors($backup_errors);
234  if ($result === false) {
235  return null;
236  }
237  return $result;
238  });
239 
240  $this->registerMediaTypeParser('application/x-www-form-urlencoded', function ($input) {
241  parse_str($input, $data);
242  return $data;
243  });
244 
245  // if the request had an invalid method, we can throw it now
246  if (isset($e) && $e instanceof InvalidMethodException) {
247  throw $e;
248  }
249  }
250 
257  public function __clone()
258  {
259  $this->headers = clone $this->headers;
260  $this->attributes = clone $this->attributes;
261  $this->body = clone $this->body;
262  }
263 
264  /*******************************************************************************
265  * Method
266  ******************************************************************************/
267 
273  public function getMethod()
274  {
275  if ($this->method === null) {
276  $this->method = $this->originalMethod;
277  $customMethod = $this->getHeaderLine('X-Http-Method-Override');
278 
279  if ($customMethod) {
280  $this->method = $this->filterMethod($customMethod);
281  } elseif ($this->originalMethod === 'POST') {
282  $overrideMethod = $this->filterMethod($this->getParsedBodyParam('_METHOD'));
283  if ($overrideMethod !== null) {
284  $this->method = $overrideMethod;
285  }
286 
287  if ($this->getBody()->eof()) {
288  $this->getBody()->rewind();
289  }
290  }
291  }
292 
293  return $this->method;
294  }
295 
303  public function getOriginalMethod()
304  {
305  return $this->originalMethod;
306  }
307 
323  public function withMethod($method)
324  {
325  $method = $this->filterMethod($method);
326  $clone = clone $this;
327  $clone->originalMethod = $method;
328  $clone->method = $method;
329 
330  return $clone;
331  }
332 
340  protected function filterMethod($method)
341  {
342  if ($method === null) {
343  return $method;
344  }
345 
346  if (!is_string($method)) {
347  throw new InvalidArgumentException(sprintf(
348  'Unsupported HTTP method; must be a string, received %s',
349  (is_object($method) ? get_class($method) : gettype($method))
350  ));
351  }
352 
353  $method = strtoupper($method);
354  if (preg_match("/^[!#$%&'*+.^_`|~0-9a-z-]+$/i", $method) !== 1) {
355  throw new InvalidMethodException($this, $method);
356  }
357 
358  return $method;
359  }
360 
369  public function isMethod($method)
370  {
371  return $this->getMethod() === $method;
372  }
373 
381  public function isGet()
382  {
383  return $this->isMethod('GET');
384  }
385 
393  public function isPost()
394  {
395  return $this->isMethod('POST');
396  }
397 
405  public function isPut()
406  {
407  return $this->isMethod('PUT');
408  }
409 
417  public function isPatch()
418  {
419  return $this->isMethod('PATCH');
420  }
421 
429  public function isDelete()
430  {
431  return $this->isMethod('DELETE');
432  }
433 
441  public function isHead()
442  {
443  return $this->isMethod('HEAD');
444  }
445 
453  public function isOptions()
454  {
455  return $this->isMethod('OPTIONS');
456  }
457 
465  public function isXhr()
466  {
467  return $this->getHeaderLine('X-Requested-With') === 'XMLHttpRequest';
468  }
469 
470  /*******************************************************************************
471  * URI
472  ******************************************************************************/
473 
490  public function getRequestTarget()
491  {
492  if ($this->requestTarget) {
493  return $this->requestTarget;
494  }
495 
496  if ($this->uri === null) {
497  return '/';
498  }
499 
500  $basePath = $this->uri->getBasePath();
501  $path = $this->uri->getPath();
502  $path = $basePath . '/' . ltrim($path, '/');
503 
504  $query = $this->uri->getQuery();
505  if ($query) {
506  $path .= '?' . $query;
507  }
508  $this->requestTarget = $path;
509 
510  return $this->requestTarget;
511  }
512 
532  {
533  if (preg_match('#\s#', $requestTarget)) {
534  throw new InvalidArgumentException(
535  'Invalid request target provided; must be a string and cannot contain whitespace'
536  );
537  }
538  $clone = clone $this;
539  $clone->requestTarget = $requestTarget;
540 
541  return $clone;
542  }
543 
553  public function getUri()
554  {
555  return $this->uri;
556  }
557 
588  public function withUri(UriInterface $uri, $preserveHost = false)
589  {
590  $clone = clone $this;
591  $clone->uri = $uri;
592 
593  if (!$preserveHost) {
594  if ($uri->getHost() !== '') {
595  $clone->headers->set('Host', $uri->getHost());
596  }
597  } else {
598  if ($uri->getHost() !== '' && (!$this->hasHeader('Host') || $this->getHeaderLine('Host') === '')) {
599  $clone->headers->set('Host', $uri->getHost());
600  }
601  }
602 
603  return $clone;
604  }
605 
613  public function getContentType()
614  {
615  $result = $this->getHeader('Content-Type');
616 
617  return $result ? $result[0] : null;
618  }
619 
627  public function getMediaType()
628  {
629  $contentType = $this->getContentType();
630  if ($contentType) {
631  $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
632 
633  return strtolower($contentTypeParts[0]);
634  }
635 
636  return null;
637  }
638 
646  public function getMediaTypeParams()
647  {
648  $contentType = $this->getContentType();
649  $contentTypeParams = [];
650  if ($contentType) {
651  $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
652  $contentTypePartsLength = count($contentTypeParts);
653  for ($i = 1; $i < $contentTypePartsLength; $i++) {
654  $paramParts = explode('=', $contentTypeParts[$i]);
655  $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
656  }
657  }
658 
659  return $contentTypeParams;
660  }
661 
669  public function getContentCharset()
670  {
671  $mediaTypeParams = $this->getMediaTypeParams();
672  if (isset($mediaTypeParams['charset'])) {
673  return $mediaTypeParams['charset'];
674  }
675 
676  return null;
677  }
678 
686  public function getContentLength()
687  {
688  $result = $this->headers->get('Content-Length');
689 
690  return $result ? (int)$result[0] : null;
691  }
692 
693  /*******************************************************************************
694  * Cookies
695  ******************************************************************************/
696 
707  public function getCookieParams()
708  {
709  return $this->cookies;
710  }
711 
722  public function getCookieParam($key, $default = null)
723  {
724  $cookies = $this->getCookieParams();
725  $result = $default;
726  if (isset($cookies[$key])) {
727  $result = $cookies[$key];
728  }
729 
730  return $result;
731  }
732 
750  public function withCookieParams(array $cookies)
751  {
752  $clone = clone $this;
753  $clone->cookies = $cookies;
754 
755  return $clone;
756  }
757 
758  /*******************************************************************************
759  * Query Params
760  ******************************************************************************/
761 
774  public function getQueryParams()
775  {
776  if (is_array($this->queryParams)) {
777  return $this->queryParams;
778  }
779 
780  if ($this->uri === null) {
781  return [];
782  }
783 
784  parse_str($this->uri->getQuery(), $this->queryParams); // <-- URL decodes data
785 
786  return $this->queryParams;
787  }
788 
811  public function withQueryParams(array $query)
812  {
813  $clone = clone $this;
814  $clone->queryParams = $query;
815 
816  return $clone;
817  }
818 
819  /*******************************************************************************
820  * File Params
821  ******************************************************************************/
822 
835  public function getUploadedFiles()
836  {
837  return $this->uploadedFiles;
838  }
839 
851  public function withUploadedFiles(array $uploadedFiles)
852  {
853  $clone = clone $this;
854  $clone->uploadedFiles = $uploadedFiles;
855 
856  return $clone;
857  }
858 
859  /*******************************************************************************
860  * Server Params
861  ******************************************************************************/
862 
872  public function getServerParams()
873  {
874  return $this->serverParams;
875  }
876 
886  public function getServerParam($key, $default = null)
887  {
888  $serverParams = $this->getServerParams();
889 
890  return isset($serverParams[$key]) ? $serverParams[$key] : $default;
891  }
892 
893  /*******************************************************************************
894  * Attributes
895  ******************************************************************************/
896 
908  public function getAttributes()
909  {
910  return $this->attributes->all();
911  }
912 
928  public function getAttribute($name, $default = null)
929  {
930  return $this->attributes->get($name, $default);
931  }
932 
948  public function withAttribute($name, $value)
949  {
950  $clone = clone $this;
951  $clone->attributes->set($name, $value);
952 
953  return $clone;
954  }
955 
971  public function withAttributes(array $attributes)
972  {
973  $clone = clone $this;
974  $clone->attributes = new Collection($attributes);
975 
976  return $clone;
977  }
978 
993  public function withoutAttribute($name)
994  {
995  $clone = clone $this;
996  $clone->attributes->remove($name);
997 
998  return $clone;
999  }
1000 
1001  /*******************************************************************************
1002  * Body
1003  ******************************************************************************/
1004 
1021  public function getParsedBody()
1022  {
1023  if ($this->bodyParsed !== false) {
1024  return $this->bodyParsed;
1025  }
1026 
1027  if (!$this->body) {
1028  return null;
1029  }
1030 
1031  $mediaType = $this->getMediaType();
1032 
1033  // look for a media type with a structured syntax suffix (RFC 6839)
1034  $parts = explode('+', $mediaType);
1035  if (count($parts) >= 2) {
1036  $mediaType = 'application/' . $parts[count($parts)-1];
1037  }
1038 
1039  if (isset($this->bodyParsers[$mediaType]) === true) {
1040  $body = (string)$this->getBody();
1041  $parsed = $this->bodyParsers[$mediaType]($body);
1042 
1043  if (!is_null($parsed) && !is_object($parsed) && !is_array($parsed)) {
1044  throw new RuntimeException(
1045  'Request body media type parser return value must be an array, an object, or null'
1046  );
1047  }
1048  $this->bodyParsed = $parsed;
1049  return $this->bodyParsed;
1050  }
1051 
1052  return null;
1053  }
1054 
1083  public function withParsedBody($data)
1084  {
1085  if (!is_null($data) && !is_object($data) && !is_array($data)) {
1086  throw new InvalidArgumentException('Parsed body value must be an array, an object, or null');
1087  }
1088 
1089  $clone = clone $this;
1090  $clone->bodyParsed = $data;
1091 
1092  return $clone;
1093  }
1094 
1102  public function reparseBody()
1103  {
1104  $this->bodyParsed = false;
1105 
1106  return $this;
1107  }
1108 
1119  public function registerMediaTypeParser($mediaType, callable $callable)
1120  {
1121  if ($callable instanceof Closure) {
1122  $callable = $callable->bindTo($this);
1123  }
1124  $this->bodyParsers[(string)$mediaType] = $callable;
1125  }
1126 
1127  /*******************************************************************************
1128  * Parameters (e.g., POST and GET data)
1129  ******************************************************************************/
1130 
1141  public function getParam($key, $default = null)
1142  {
1143  $postParams = $this->getParsedBody();
1144  $getParams = $this->getQueryParams();
1145  $result = $default;
1146  if (is_array($postParams) && isset($postParams[$key])) {
1147  $result = $postParams[$key];
1148  } elseif (is_object($postParams) && property_exists($postParams, $key)) {
1149  $result = $postParams->$key;
1150  } elseif (isset($getParams[$key])) {
1151  $result = $getParams[$key];
1152  }
1153 
1154  return $result;
1155  }
1156 
1167  public function getParsedBodyParam($key, $default = null)
1168  {
1169  $postParams = $this->getParsedBody();
1170  $result = $default;
1171  if (is_array($postParams) && isset($postParams[$key])) {
1172  $result = $postParams[$key];
1173  } elseif (is_object($postParams) && property_exists($postParams, $key)) {
1174  $result = $postParams->$key;
1175  }
1176 
1177  return $result;
1178  }
1179 
1190  public function getQueryParam($key, $default = null)
1191  {
1192  $getParams = $this->getQueryParams();
1193  $result = $default;
1194  if (isset($getParams[$key])) {
1195  $result = $getParams[$key];
1196  }
1197 
1198  return $result;
1199  }
1200 
1209  public function getParams(array $only = null)
1210  {
1211  $params = $this->getQueryParams();
1212  $postParams = $this->getParsedBody();
1213  if ($postParams) {
1214  $params = array_replace($params, (array)$postParams);
1215  }
1216 
1217  if ($only) {
1218  $onlyParams = [];
1219  foreach ($only as $key) {
1220  if (array_key_exists($key, $params)) {
1221  $onlyParams[$key] = $params[$key];
1222  }
1223  }
1224  return $onlyParams;
1225  }
1226 
1227  return $params;
1228  }
1229 }
getAttributes()
Retrieve attributes derived from the request.
Definition: Request.php:908
$path
Definition: aliased.php:25
__construct( $method, UriInterface $uri, HeadersInterface $headers, array $cookies, array $serverParams, StreamInterface $body, array $uploadedFiles=[])
Create new HTTP request.
Definition: Request.php:173
getBody()
Gets the body of the message.
Definition: Message.php:279
Representation of an incoming, server-side HTTP request.
isHead()
Is this a HEAD request?
Definition: Request.php:441
getHost()
Retrieve the host component of the URI.
withCookieParams(array $cookies)
Return an instance with the specified cookies.
Definition: Request.php:750
isOptions()
Is this a OPTIONS request?
Definition: Request.php:453
withoutAttribute($name)
Return an instance that removes the specified derived request attribute.
Definition: Request.php:993
$result
isPatch()
Is this a PATCH request?
Definition: Request.php:417
getHeaderLine($name)
Retrieves a comma-separated string of the values for a single header.
Definition: Message.php:198
getCookieParam($key, $default=null)
Fetch cookie value from cookies sent by the client to the server.
Definition: Request.php:722
foreach($paths as $path) $request
Definition: asyncclient.php:32
Abstract message (base class for Request and Response)
Definition: Message.php:25
Collection.
Definition: Collection.php:21
getParsedBody()
Retrieve any parameters provided in the request body.
Definition: Request.php:1021
static static createFromEnvironment(Environment $environment)
Create new headers collection with data extracted from the application Environment object...
Definition: Headers.php:51
getMethod()
Retrieves the HTTP method of the request.
Definition: Request.php:273
isXhr()
Is this an XHR request?
Definition: Request.php:465
getCookieParams()
Retrieve cookies.
Definition: Request.php:707
static createFromEnvironment(Environment $env)
Create new Uri from environment.
Definition: Uri.php:166
Value object representing a URI.
getParsedBodyParam($key, $default=null)
Fetch parameter value from request body.
Definition: Request.php:1167
Request.
Definition: Request.php:33
withAttributes(array $attributes)
Create a new instance with the specified derived request attributes.
Definition: Request.php:971
isMethod($method)
Does this request use a given method?
Definition: Request.php:369
withRequestTarget($requestTarget)
Return an instance with the specific request-target.
Definition: Request.php:531
withUri(UriInterface $uri, $preserveHost=false)
Returns an instance with the provided URI.
Definition: Request.php:588
isPost()
Is this a POST request?
Definition: Request.php:393
getQueryParams()
Retrieve query string arguments.
Definition: Request.php:774
reparseBody()
Force Body to be parsed again.
Definition: Request.php:1102
getParam($key, $default=null)
Fetch request parameter value from body or query string (in that order).
Definition: Request.php:1141
__clone()
This method is applied to the cloned object after PHP performs an initial shallow-copy.
Definition: Request.php:257
getServerParam($key, $default=null)
Retrieve a server parameter.
Definition: Request.php:886
isDelete()
Is this a DELETE request?
Definition: Request.php:429
getRequestTarget()
Retrieves the message&#39;s request target.
Definition: Request.php:490
static parseHeader($header)
Parse HTTP request Cookie: header and extract into a PHP associative array.
Definition: Cookies.php:172
getOriginalMethod()
Get the original HTTP method (ignore override).
Definition: Request.php:303
getContentType()
Get request content type.
Definition: Request.php:613
Slim Framework (https://slimframework.com)
Definition: Body.php:9
getContentLength()
Get request content length, if known.
Definition: Request.php:686
isPut()
Is this a PUT request?
Definition: Request.php:405
getMediaTypeParams()
Get request media type params, if known.
Definition: Request.php:646
all()
Get all items in collection.
Definition: Collection.php:85
hasHeader($name)
Checks if a header exists by the given case-insensitive name.
Definition: Message.php:155
getServerParams()
Retrieve server parameters.
Definition: Request.php:872
$query
static createFromEnvironment(Environment $environment)
Create new HTTP request with data extracted from the application Environment object.
Definition: Request.php:138
Provides a PSR-7 implementation of a reusable raw request body.
Definition: RequestBody.php:14
$default
Definition: build.php:20
registerMediaTypeParser($mediaType, callable $callable)
Register media type parser.
Definition: Request.php:1119
filterMethod($method)
Validate the HTTP method.
Definition: Request.php:340
getHeader($name)
Retrieves a message header value by the given case-insensitive name.
Definition: Message.php:174
getParams(array $only=null)
Fetch associative array of body and query string parameters.
Definition: Request.php:1209
isGet()
Is this a GET request?
Definition: Request.php:381
withAttribute($name, $value)
Return an instance with the specified derived request attribute.
Definition: Request.php:948
$i
Definition: disco.tpl.php:19
withParsedBody($data)
Return an instance with the specified body parameters.
Definition: Request.php:1083
getMediaType()
Get request media type, if known.
Definition: Request.php:627
getUri()
Retrieves the URI instance.
Definition: Request.php:553
if($path[strlen($path) - 1]==='/') if(is_dir($path)) if(!file_exists($path)) if(preg_match('#\.php$#D', mb_strtolower($path, 'UTF-8'))) $contentType
Definition: module.php:144
getAttribute($name, $default=null)
Retrieve a single derived request attribute.
Definition: Request.php:928
static createFromEnvironment(Environment $env)
Create a normalized tree of UploadedFile instances from the Environment.
getUploadedFiles()
Retrieve normalized file upload data.
Definition: Request.php:835
withMethod($method)
Return an instance with the provided HTTP method.
Definition: Request.php:323
getQueryParam($key, $default=null)
Fetch parameter value from query string.
Definition: Request.php:1190
withUploadedFiles(array $uploadedFiles)
Create a new instance with the specified uploaded files.
Definition: Request.php:851
$key
Definition: croninfo.php:18
$_POST["username"]
getContentCharset()
Get request content character set, if known.
Definition: Request.php:669
withQueryParams(array $query)
Return an instance with the specified query string arguments.
Definition: Request.php:811
Describes a data stream.
$data
Definition: bench.php:6