ServerRequest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. *
  72. * @return array
  73. *
  74. * @throws InvalidArgumentException for unrecognized values
  75. */
  76. public static function normalizeFiles(array $files)
  77. {
  78. $normalized = [];
  79. foreach ($files as $key => $value) {
  80. if ($value instanceof UploadedFileInterface) {
  81. $normalized[$key] = $value;
  82. } elseif (is_array($value) && isset($value['tmp_name'])) {
  83. $normalized[$key] = self::createUploadedFileFromSpec($value);
  84. } elseif (is_array($value)) {
  85. $normalized[$key] = self::normalizeFiles($value);
  86. continue;
  87. } else {
  88. throw new InvalidArgumentException('Invalid value in files specification');
  89. }
  90. }
  91. return $normalized;
  92. }
  93. /**
  94. * Create and return an UploadedFile instance from a $_FILES specification.
  95. *
  96. * If the specification represents an array of values, this method will
  97. * delegate to normalizeNestedFileSpec() and return that return value.
  98. *
  99. * @param array $value $_FILES struct
  100. * @return array|UploadedFileInterface
  101. */
  102. private static function createUploadedFileFromSpec(array $value)
  103. {
  104. if (is_array($value['tmp_name'])) {
  105. return self::normalizeNestedFileSpec($value);
  106. }
  107. return new UploadedFile(
  108. $value['tmp_name'],
  109. (int) $value['size'],
  110. (int) $value['error'],
  111. $value['name'],
  112. $value['type']
  113. );
  114. }
  115. /**
  116. * Normalize an array of file specifications.
  117. *
  118. * Loops through all nested files and returns a normalized array of
  119. * UploadedFileInterface instances.
  120. *
  121. * @param array $files
  122. * @return UploadedFileInterface[]
  123. */
  124. private static function normalizeNestedFileSpec(array $files = [])
  125. {
  126. $normalizedFiles = [];
  127. foreach (array_keys($files['tmp_name']) as $key) {
  128. $spec = [
  129. 'tmp_name' => $files['tmp_name'][$key],
  130. 'size' => $files['size'][$key],
  131. 'error' => $files['error'][$key],
  132. 'name' => $files['name'][$key],
  133. 'type' => $files['type'][$key],
  134. ];
  135. $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
  136. }
  137. return $normalizedFiles;
  138. }
  139. /**
  140. * Return a ServerRequest populated with superglobals:
  141. * $_GET
  142. * $_POST
  143. * $_COOKIE
  144. * $_FILES
  145. * $_SERVER
  146. *
  147. * @return ServerRequestInterface
  148. */
  149. public static function fromGlobals()
  150. {
  151. $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
  152. $headers = getallheaders();
  153. $uri = self::getUriFromGlobals();
  154. $body = new CachingStream(new LazyOpenStream('php://input', 'r+'));
  155. $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1';
  156. $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER);
  157. return $serverRequest
  158. ->withCookieParams($_COOKIE)
  159. ->withQueryParams($_GET)
  160. ->withParsedBody($_POST)
  161. ->withUploadedFiles(self::normalizeFiles($_FILES));
  162. }
  163. private static function extractHostAndPortFromAuthority($authority)
  164. {
  165. $uri = 'http://'.$authority;
  166. $parts = parse_url($uri);
  167. if (false === $parts) {
  168. return [null, null];
  169. }
  170. $host = isset($parts['host']) ? $parts['host'] : null;
  171. $port = isset($parts['port']) ? $parts['port'] : null;
  172. return [$host, $port];
  173. }
  174. /**
  175. * Get a Uri populated with values from $_SERVER.
  176. *
  177. * @return UriInterface
  178. */
  179. public static function getUriFromGlobals()
  180. {
  181. $uri = new Uri('');
  182. $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http');
  183. $hasPort = false;
  184. if (isset($_SERVER['HTTP_HOST'])) {
  185. list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']);
  186. if ($host !== null) {
  187. $uri = $uri->withHost($host);
  188. }
  189. if ($port !== null) {
  190. $hasPort = true;
  191. $uri = $uri->withPort($port);
  192. }
  193. } elseif (isset($_SERVER['SERVER_NAME'])) {
  194. $uri = $uri->withHost($_SERVER['SERVER_NAME']);
  195. } elseif (isset($_SERVER['SERVER_ADDR'])) {
  196. $uri = $uri->withHost($_SERVER['SERVER_ADDR']);
  197. }
  198. if (!$hasPort && isset($_SERVER['SERVER_PORT'])) {
  199. $uri = $uri->withPort($_SERVER['SERVER_PORT']);
  200. }
  201. $hasQuery = false;
  202. if (isset($_SERVER['REQUEST_URI'])) {
  203. $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
  204. $uri = $uri->withPath($requestUriParts[0]);
  205. if (isset($requestUriParts[1])) {
  206. $hasQuery = true;
  207. $uri = $uri->withQuery($requestUriParts[1]);
  208. }
  209. }
  210. if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) {
  211. $uri = $uri->withQuery($_SERVER['QUERY_STRING']);
  212. }
  213. return $uri;
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. public function getServerParams()
  219. {
  220. return $this->serverParams;
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function getUploadedFiles()
  226. {
  227. return $this->uploadedFiles;
  228. }
  229. /**
  230. * {@inheritdoc}
  231. */
  232. public function withUploadedFiles(array $uploadedFiles)
  233. {
  234. $new = clone $this;
  235. $new->uploadedFiles = $uploadedFiles;
  236. return $new;
  237. }
  238. /**
  239. * {@inheritdoc}
  240. */
  241. public function getCookieParams()
  242. {
  243. return $this->cookieParams;
  244. }
  245. /**
  246. * {@inheritdoc}
  247. */
  248. public function withCookieParams(array $cookies)
  249. {
  250. $new = clone $this;
  251. $new->cookieParams = $cookies;
  252. return $new;
  253. }
  254. /**
  255. * {@inheritdoc}
  256. */
  257. public function getQueryParams()
  258. {
  259. return $this->queryParams;
  260. }
  261. /**
  262. * {@inheritdoc}
  263. */
  264. public function withQueryParams(array $query)
  265. {
  266. $new = clone $this;
  267. $new->queryParams = $query;
  268. return $new;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function getParsedBody()
  274. {
  275. return $this->parsedBody;
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. public function withParsedBody($data)
  281. {
  282. $new = clone $this;
  283. $new->parsedBody = $data;
  284. return $new;
  285. }
  286. /**
  287. * {@inheritdoc}
  288. */
  289. public function getAttributes()
  290. {
  291. return $this->attributes;
  292. }
  293. /**
  294. * {@inheritdoc}
  295. */
  296. public function getAttribute($attribute, $default = null)
  297. {
  298. if (false === array_key_exists($attribute, $this->attributes)) {
  299. return $default;
  300. }
  301. return $this->attributes[$attribute];
  302. }
  303. /**
  304. * {@inheritdoc}
  305. */
  306. public function withAttribute($attribute, $value)
  307. {
  308. $new = clone $this;
  309. $new->attributes[$attribute] = $value;
  310. return $new;
  311. }
  312. /**
  313. * {@inheritdoc}
  314. */
  315. public function withoutAttribute($attribute)
  316. {
  317. if (false === array_key_exists($attribute, $this->attributes)) {
  318. return $this;
  319. }
  320. $new = clone $this;
  321. unset($new->attributes[$attribute]);
  322. return $new;
  323. }
  324. }