HttpFoundationFactory.php 6.8 KB

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