HttpFoundationFactory.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. public function createRequest(ServerRequestInterface $psrRequest, bool $streamed = false)
  40. {
  41. $server = [];
  42. $uri = $psrRequest->getUri();
  43. if ($uri instanceof UriInterface) {
  44. $server['SERVER_NAME'] = $uri->getHost();
  45. $server['SERVER_PORT'] = $uri->getPort() ?: ('https' === $uri->getScheme() ? 443 : 80);
  46. $server['REQUEST_URI'] = $uri->getPath();
  47. $server['QUERY_STRING'] = $uri->getQuery();
  48. if ('https' === $uri->getScheme()) {
  49. $server['HTTPS'] = 'on';
  50. }
  51. }
  52. $server['REQUEST_METHOD'] = $psrRequest->getMethod();
  53. $server = array_replace($server, $psrRequest->getServerParams());
  54. $parsedBody = $psrRequest->getParsedBody();
  55. $parsedBody = \is_array($parsedBody) ? $parsedBody : [];
  56. $request = new Request(
  57. $psrRequest->getQueryParams(),
  58. $parsedBody,
  59. $psrRequest->getAttributes(),
  60. $psrRequest->getCookieParams(),
  61. $this->getFiles($psrRequest->getUploadedFiles()),
  62. $server,
  63. $streamed ? $psrRequest->getBody()->detach() : $psrRequest->getBody()->__toString()
  64. );
  65. $request->headers->add($psrRequest->getHeaders());
  66. return $request;
  67. }
  68. /**
  69. * Converts to the input array to $_FILES structure.
  70. */
  71. private function getFiles(array $uploadedFiles): array
  72. {
  73. $files = [];
  74. foreach ($uploadedFiles as $key => $value) {
  75. if ($value instanceof UploadedFileInterface) {
  76. $files[$key] = $this->createUploadedFile($value);
  77. } else {
  78. $files[$key] = $this->getFiles($value);
  79. }
  80. }
  81. return $files;
  82. }
  83. /**
  84. * Creates Symfony UploadedFile instance from PSR-7 ones.
  85. */
  86. private function createUploadedFile(UploadedFileInterface $psrUploadedFile): UploadedFile
  87. {
  88. return new UploadedFile($psrUploadedFile, function () { return $this->getTemporaryPath(); });
  89. }
  90. /**
  91. * Gets a temporary file path.
  92. *
  93. * @return string
  94. */
  95. protected function getTemporaryPath()
  96. {
  97. return tempnam(sys_get_temp_dir(), uniqid('symfony', true));
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function createResponse(ResponseInterface $psrResponse, bool $streamed = false)
  103. {
  104. $cookies = $psrResponse->getHeader('Set-Cookie');
  105. $psrResponse = $psrResponse->withoutHeader('Set-Cookie');
  106. if ($streamed) {
  107. $response = new StreamedResponse(
  108. $this->createStreamedResponseCallback($psrResponse->getBody()),
  109. $psrResponse->getStatusCode(),
  110. $psrResponse->getHeaders()
  111. );
  112. } else {
  113. $response = new Response(
  114. $psrResponse->getBody()->__toString(),
  115. $psrResponse->getStatusCode(),
  116. $psrResponse->getHeaders()
  117. );
  118. }
  119. $response->setProtocolVersion($psrResponse->getProtocolVersion());
  120. foreach ($cookies as $cookie) {
  121. $response->headers->setCookie($this->createCookie($cookie));
  122. }
  123. return $response;
  124. }
  125. /**
  126. * Creates a Cookie instance from a cookie string.
  127. *
  128. * Some snippets have been taken from the Guzzle project: https://github.com/guzzle/guzzle/blob/5.3/src/Cookie/SetCookie.php#L34
  129. *
  130. * @throws \InvalidArgumentException
  131. */
  132. private function createCookie(string $cookie): Cookie
  133. {
  134. foreach (explode(';', $cookie) as $part) {
  135. $part = trim($part);
  136. $data = explode('=', $part, 2);
  137. $name = $data[0];
  138. $value = isset($data[1]) ? trim($data[1], " \n\r\t\0\x0B\"") : null;
  139. if (!isset($cookieName)) {
  140. $cookieName = $name;
  141. $cookieValue = $value;
  142. continue;
  143. }
  144. if ('expires' === strtolower($name) && null !== $value) {
  145. $cookieExpire = new \DateTime($value);
  146. continue;
  147. }
  148. if ('path' === strtolower($name) && null !== $value) {
  149. $cookiePath = $value;
  150. continue;
  151. }
  152. if ('domain' === strtolower($name) && null !== $value) {
  153. $cookieDomain = $value;
  154. continue;
  155. }
  156. if ('secure' === strtolower($name)) {
  157. $cookieSecure = true;
  158. continue;
  159. }
  160. if ('httponly' === strtolower($name)) {
  161. $cookieHttpOnly = true;
  162. continue;
  163. }
  164. if ('samesite' === strtolower($name) && null !== $value) {
  165. $samesite = $value;
  166. continue;
  167. }
  168. }
  169. if (!isset($cookieName)) {
  170. throw new \InvalidArgumentException('The value of the Set-Cookie header is malformed.');
  171. }
  172. return new Cookie(
  173. $cookieName,
  174. $cookieValue,
  175. isset($cookieExpire) ? $cookieExpire : 0,
  176. isset($cookiePath) ? $cookiePath : '/',
  177. isset($cookieDomain) ? $cookieDomain : null,
  178. isset($cookieSecure),
  179. isset($cookieHttpOnly),
  180. false,
  181. isset($samesite) ? $samesite : null
  182. );
  183. }
  184. private function createStreamedResponseCallback(StreamInterface $body): callable
  185. {
  186. return function () use ($body) {
  187. if ($body->isSeekable()) {
  188. $body->rewind();
  189. }
  190. if (!$body->isReadable()) {
  191. echo $body;
  192. return;
  193. }
  194. while (!$body->eof()) {
  195. echo $body->read($this->responseBufferMaxLength);
  196. }
  197. };
  198. }
  199. }