ServerRequest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. namespace GuzzleHttp\Psr7;
  3. use InvalidArgumentException;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use Psr\Http\Message\UriInterface;
  6. use Psr\Http\Message\StreamInterface;
  7. use Psr\Http\Message\UploadedFileInterface;
  8. /**
  9. * Server-side HTTP request
  10. *
  11. * Extends the Request definition to add methods for accessing incoming data,
  12. * specifically server parameters, cookies, matched path parameters, query
  13. * string arguments, body parameters, and upload file information.
  14. *
  15. * "Attributes" are discovered via decomposing the request (and usually
  16. * specifically the URI path), and typically will be injected by the application.
  17. *
  18. * Requests are considered immutable; all methods that might change state are
  19. * implemented such that they retain the internal state of the current
  20. * message and return a new instance that contains the changed state.
  21. */
  22. class ServerRequest extends Request implements ServerRequestInterface
  23. {
  24. /**
  25. * @var array
  26. */
  27. private $attributes = [];
  28. /**
  29. * @var array
  30. */
  31. private $cookieParams = [];
  32. /**
  33. * @var null|array|object
  34. */
  35. private $parsedBody;
  36. /**
  37. * @var array
  38. */
  39. private $queryParams = [];
  40. /**
  41. * @var array
  42. */
  43. private $serverParams;
  44. /**
  45. * @var array
  46. */
  47. private $uploadedFiles = [];
  48. /**
  49. * @param string $method HTTP method
  50. * @param string|UriInterface $uri URI
  51. * @param array $headers Request headers
  52. * @param string|null|resource|StreamInterface $body Request body
  53. * @param string $version Protocol version
  54. * @param array $serverParams Typically the $_SERVER superglobal
  55. */
  56. public function __construct(
  57. $method,
  58. $uri,
  59. array $headers = [],
  60. $body = null,
  61. $version = '1.1',
  62. array $serverParams = []
  63. ) {
  64. $this->serverParams = $serverParams;
  65. parent::__construct($method, $uri, $headers, $body, $version);
  66. }
  67. /**
  68. * Return an UploadedFile instance array.
  69. *
  70. * @param array $files A array which respect $_FILES structure
  71. * @throws InvalidArgumentException for unrecognized values
  72. * @return array
  73. */
  74. public static function normalizeFiles(array $files)
  75. {
  76. $normalized = [];
  77. foreach ($files as $key => $value) {
  78. if ($value instanceof UploadedFileInterface) {
  79. $normalized[$key] = $value;
  80. } elseif (is_array($value) && isset($value['tmp_name'])) {
  81. $normalized[$key] = self::createUploadedFileFromSpec($value);
  82. } elseif (is_array($value)) {
  83. $normalized[$key] = self::normalizeFiles($value);
  84. continue;
  85. } else {
  86. throw new InvalidArgumentException('Invalid value in files specification');
  87. }
  88. }
  89. return $normalized;
  90. }
  91. /**
  92. * Create and return an UploadedFile instance from a $_FILES specification.
  93. *
  94. * If the specification represents an array of values, this method will
  95. * delegate to normalizeNestedFileSpec() and return that return value.
  96. *
  97. * @param array $value $_FILES struct
  98. * @return array|UploadedFileInterface
  99. */
  100. private static function createUploadedFileFromSpec(array $value)
  101. {
  102. if (is_array($value['tmp_name'])) {
  103. return self::normalizeNestedFileSpec($value);
  104. }
  105. return new UploadedFile(
  106. $value['tmp_name'],
  107. (int) $value['size'],
  108. (int) $value['error'],
  109. $value['name'],
  110. $value['type']
  111. );
  112. }
  113. /**
  114. * Normalize an array of file specifications.
  115. *
  116. * Loops through all nested files and returns a normalized array of
  117. * UploadedFileInterface instances.
  118. *
  119. * @param array $files
  120. * @return UploadedFileInterface[]
  121. */
  122. private static function normalizeNestedFileSpec(array $files = [])
  123. {
  124. $normalizedFiles = [];
  125. foreach (array_keys($files['tmp_name']) as $key) {
  126. $spec = [
  127. 'tmp_name' => $files['tmp_name'][$key],
  128. 'size' => $files['size'][$key],
  129. 'error' => $files['error'][$key],
  130. 'name' => $files['name'][$key],
  131. 'type' => $files['type'][$key],
  132. ];
  133. $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
  134. }
  135. return $normalizedFiles;
  136. }
  137. /**
  138. * Return a ServerRequest populated with superglobals:
  139. * $_GET
  140. * $_POST
  141. * $_COOKIE
  142. * $_FILES
  143. * $_SERVER
  144. *
  145. * @return ServerRequestInterface
  146. */
  147. public static function fromGlobals()
  148. {
  149. $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
  150. $headers = getallheaders();
  151. $uri = self::getUriFromGlobals();
  152. $body = new CachingStream(new LazyOpenStream('php://input', 'r+'));
  153. $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1';
  154. $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER);
  155. return $serverRequest
  156. ->withCookieParams($_COOKIE)
  157. ->withQueryParams($_GET)
  158. ->withParsedBody($_POST)
  159. ->withUploadedFiles(self::normalizeFiles($_FILES));
  160. }
  161. private static function extractHostAndPortFromAuthority($authority)
  162. {
  163. $uri = 'http://'.$authority;
  164. $parts = parse_url($uri);
  165. if (false === $parts) {
  166. return [null, null];
  167. }
  168. $host = isset($parts['host']) ? $parts['host'] : null;
  169. $port = isset($parts['port']) ? $parts['port'] : null;
  170. return [$host, $port];
  171. }
  172. /**
  173. * Get a Uri populated with values from $_SERVER.
  174. *
  175. * @return UriInterface
  176. */
  177. public static function getUriFromGlobals()
  178. {
  179. $uri = new Uri('');
  180. $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http');
  181. $hasPort = false;
  182. if (isset($_SERVER['HTTP_HOST'])) {
  183. list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']);
  184. if ($host !== null) {
  185. $uri = $uri->withHost($host);
  186. }
  187. if ($port !== null) {
  188. $hasPort = true;
  189. $uri = $uri->withPort($port);
  190. }
  191. } elseif (isset($_SERVER['SERVER_NAME'])) {
  192. $uri = $uri->withHost($_SERVER['SERVER_NAME']);
  193. } elseif (isset($_SERVER['SERVER_ADDR'])) {
  194. $uri = $uri->withHost($_SERVER['SERVER_ADDR']);
  195. }
  196. if (!$hasPort && isset($_SERVER['SERVER_PORT'])) {
  197. $uri = $uri->withPort($_SERVER['SERVER_PORT']);
  198. }
  199. $hasQuery = false;
  200. if (isset($_SERVER['REQUEST_URI'])) {
  201. $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
  202. $uri = $uri->withPath($requestUriParts[0]);
  203. if (isset($requestUriParts[1])) {
  204. $hasQuery = true;
  205. $uri = $uri->withQuery($requestUriParts[1]);
  206. }
  207. }
  208. if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) {
  209. $uri = $uri->withQuery($_SERVER['QUERY_STRING']);
  210. }
  211. return $uri;
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. public function getServerParams()
  217. {
  218. return $this->serverParams;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function getUploadedFiles()
  224. {
  225. return $this->uploadedFiles;
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. public function withUploadedFiles(array $uploadedFiles)
  231. {
  232. $new = clone $this;
  233. $new->uploadedFiles = $uploadedFiles;
  234. return $new;
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. public function getCookieParams()
  240. {
  241. return $this->cookieParams;
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. public function withCookieParams(array $cookies)
  247. {
  248. $new = clone $this;
  249. $new->cookieParams = $cookies;
  250. return $new;
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. public function getQueryParams()
  256. {
  257. return $this->queryParams;
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function withQueryParams(array $query)
  263. {
  264. $new = clone $this;
  265. $new->queryParams = $query;
  266. return $new;
  267. }
  268. /**
  269. * {@inheritdoc}
  270. */
  271. public function getParsedBody()
  272. {
  273. return $this->parsedBody;
  274. }
  275. /**
  276. * {@inheritdoc}
  277. */
  278. public function withParsedBody($data)
  279. {
  280. $new = clone $this;
  281. $new->parsedBody = $data;
  282. return $new;
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function getAttributes()
  288. {
  289. return $this->attributes;
  290. }
  291. /**
  292. * {@inheritdoc}
  293. */
  294. public function getAttribute($attribute, $default = null)
  295. {
  296. if (false === array_key_exists($attribute, $this->attributes)) {
  297. return $default;
  298. }
  299. return $this->attributes[$attribute];
  300. }
  301. /**
  302. * {@inheritdoc}
  303. */
  304. public function withAttribute($attribute, $value)
  305. {
  306. $new = clone $this;
  307. $new->attributes[$attribute] = $value;
  308. return $new;
  309. }
  310. /**
  311. * {@inheritdoc}
  312. */
  313. public function withoutAttribute($attribute)
  314. {
  315. if (false === array_key_exists($attribute, $this->attributes)) {
  316. return $this;
  317. }
  318. $new = clone $this;
  319. unset($new->attributes[$attribute]);
  320. return $new;
  321. }
  322. }