HttpFoundationFactory.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\PsrHttpMessage\Factory;
  11. use Psr\Http\Message\ResponseInterface;
  12. use Psr\Http\Message\ServerRequestInterface;
  13. use Psr\Http\Message\StreamInterface;
  14. use Psr\Http\Message\UploadedFileInterface;
  15. use Psr\Http\Message\UriInterface;
  16. use Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface;
  17. use Symfony\Component\HttpFoundation\Cookie;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpFoundation\StreamedResponse;
  21. /**
  22. * {@inheritdoc}
  23. *
  24. * @author Kévin Dunglas <dunglas@gmail.com>
  25. */
  26. class HttpFoundationFactory implements HttpFoundationFactoryInterface
  27. {
  28. /**
  29. * @var int The maximum output buffering size for each iteration when sending the response
  30. */
  31. private $responseBufferMaxLength;
  32. public function __construct(int $responseBufferMaxLength = 16372)
  33. {
  34. $this->responseBufferMaxLength = $responseBufferMaxLength;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. *
  39. * @return Request
  40. */
  41. public function createRequest(ServerRequestInterface $psrRequest, bool $streamed = false)
  42. {
  43. $server = [];
  44. $uri = $psrRequest->getUri();
  45. if ($uri instanceof UriInterface) {
  46. $server['SERVER_NAME'] = $uri->getHost();
  47. $server['SERVER_PORT'] = $uri->getPort() ?: ('https' === $uri->getScheme() ? 443 : 80);
  48. $server['REQUEST_URI'] = $uri->getPath();
  49. $server['QUERY_STRING'] = $uri->getQuery();
  50. if ('' !== $server['QUERY_STRING']) {
  51. $server['REQUEST_URI'] .= '?'.$server['QUERY_STRING'];
  52. }
  53. if ('https' === $uri->getScheme()) {
  54. $server['HTTPS'] = 'on';
  55. }
  56. }
  57. $server['REQUEST_METHOD'] = $psrRequest->getMethod();
  58. $server = array_replace($psrRequest->getServerParams(), $server);
  59. $parsedBody = $psrRequest->getParsedBody();
  60. $parsedBody = \is_array($parsedBody) ? $parsedBody : [];
  61. $request = new Request(
  62. $psrRequest->getQueryParams(),
  63. $parsedBody,
  64. $psrRequest->getAttributes(),
  65. $psrRequest->getCookieParams(),
  66. $this->getFiles($psrRequest->getUploadedFiles()),
  67. $server,
  68. $streamed ? $psrRequest->getBody()->detach() : $psrRequest->getBody()->__toString()
  69. );
  70. $request->headers->add($psrRequest->getHeaders());
  71. return $request;
  72. }
  73. /**
  74. * Converts to the input array to $_FILES structure.
  75. */
  76. private function getFiles(array $uploadedFiles): array
  77. {
  78. $files = [];
  79. foreach ($uploadedFiles as $key => $value) {
  80. if ($value instanceof UploadedFileInterface) {
  81. $files[$key] = $this->createUploadedFile($value);
  82. } else {
  83. $files[$key] = $this->getFiles($value);
  84. }
  85. }
  86. return $files;
  87. }
  88. /**
  89. * Creates Symfony UploadedFile instance from PSR-7 ones.
  90. */
  91. private function createUploadedFile(UploadedFileInterface $psrUploadedFile): UploadedFile
  92. {
  93. return new UploadedFile($psrUploadedFile, function () { return $this->getTemporaryPath(); });
  94. }
  95. /**
  96. * Gets a temporary file path.
  97. *
  98. * @return string
  99. */
  100. protected function getTemporaryPath()
  101. {
  102. return tempnam(sys_get_temp_dir(), uniqid('symfony', true));
  103. }
  104. /**
  105. * {@inheritdoc}
  106. *
  107. * @return Response
  108. */
  109. public function createResponse(ResponseInterface $psrResponse, bool $streamed = false)
  110. {
  111. $cookies = $psrResponse->getHeader('Set-Cookie');
  112. $psrResponse = $psrResponse->withoutHeader('Set-Cookie');
  113. if ($streamed) {
  114. $response = new StreamedResponse(
  115. $this->createStreamedResponseCallback($psrResponse->getBody()),
  116. $psrResponse->getStatusCode(),
  117. $psrResponse->getHeaders()
  118. );
  119. } else {
  120. $response = new Response(
  121. $psrResponse->getBody()->__toString(),
  122. $psrResponse->getStatusCode(),
  123. $psrResponse->getHeaders()
  124. );
  125. }
  126. $response->setProtocolVersion($psrResponse->getProtocolVersion());
  127. foreach ($cookies as $cookie) {
  128. $response->headers->setCookie($this->createCookie($cookie));
  129. }
  130. return $response;
  131. }
  132. /**
  133. * Creates a Cookie instance from a cookie string.
  134. *
  135. * Some snippets have been taken from the Guzzle project: https://github.com/guzzle/guzzle/blob/5.3/src/Cookie/SetCookie.php#L34
  136. *
  137. * @throws \InvalidArgumentException
  138. */
  139. private function createCookie(string $cookie): Cookie
  140. {
  141. foreach (explode(';', $cookie) as $part) {
  142. $part = trim($part);
  143. $data = explode('=', $part, 2);
  144. $name = $data[0];
  145. $value = isset($data[1]) ? trim($data[1], " \n\r\t\0\x0B\"") : null;
  146. if (!isset($cookieName)) {
  147. $cookieName = $name;
  148. $cookieValue = $value;
  149. continue;
  150. }
  151. if ('expires' === strtolower($name) && null !== $value) {
  152. $cookieExpire = new \DateTime($value);
  153. continue;
  154. }
  155. if ('path' === strtolower($name) && null !== $value) {
  156. $cookiePath = $value;
  157. continue;
  158. }
  159. if ('domain' === strtolower($name) && null !== $value) {
  160. $cookieDomain = $value;
  161. continue;
  162. }
  163. if ('secure' === strtolower($name)) {
  164. $cookieSecure = true;
  165. continue;
  166. }
  167. if ('httponly' === strtolower($name)) {
  168. $cookieHttpOnly = true;
  169. continue;
  170. }
  171. if ('samesite' === strtolower($name) && null !== $value) {
  172. $samesite = $value;
  173. continue;
  174. }
  175. }
  176. if (!isset($cookieName)) {
  177. throw new \InvalidArgumentException('The value of the Set-Cookie header is malformed.');
  178. }
  179. return new Cookie(
  180. $cookieName,
  181. $cookieValue,
  182. $cookieExpire ?? 0,
  183. $cookiePath ?? '/',
  184. $cookieDomain ?? null,
  185. isset($cookieSecure),
  186. isset($cookieHttpOnly),
  187. true,
  188. $samesite ?? null
  189. );
  190. }
  191. private function createStreamedResponseCallback(StreamInterface $body): callable
  192. {
  193. return function () use ($body) {
  194. if ($body->isSeekable()) {
  195. $body->rewind();
  196. }
  197. if (!$body->isReadable()) {
  198. echo $body;
  199. return;
  200. }
  201. while (!$body->eof()) {
  202. echo $body->read($this->responseBufferMaxLength);
  203. }
  204. };
  205. }
  206. }