PsrHttpFactory.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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\ResponseFactoryInterface;
  12. use Psr\Http\Message\ResponseInterface;
  13. use Psr\Http\Message\ServerRequestFactoryInterface;
  14. use Psr\Http\Message\ServerRequestInterface;
  15. use Psr\Http\Message\StreamFactoryInterface;
  16. use Psr\Http\Message\UploadedFileFactoryInterface;
  17. use Psr\Http\Message\UploadedFileInterface;
  18. use Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface;
  19. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  20. use Symfony\Component\HttpFoundation\File\UploadedFile;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use Symfony\Component\HttpFoundation\StreamedResponse;
  24. /**
  25. * Builds Psr\HttpMessage instances using a PSR-17 implementation.
  26. *
  27. * @author Antonio J. García Lagar <aj@garcialagar.es>
  28. * @author Aurélien Pillevesse <aurelienpillevesse@hotmail.fr>
  29. */
  30. class PsrHttpFactory implements HttpMessageFactoryInterface
  31. {
  32. private $serverRequestFactory;
  33. private $streamFactory;
  34. private $uploadedFileFactory;
  35. private $responseFactory;
  36. public function __construct(ServerRequestFactoryInterface $serverRequestFactory, StreamFactoryInterface $streamFactory, UploadedFileFactoryInterface $uploadedFileFactory, ResponseFactoryInterface $responseFactory)
  37. {
  38. $this->serverRequestFactory = $serverRequestFactory;
  39. $this->streamFactory = $streamFactory;
  40. $this->uploadedFileFactory = $uploadedFileFactory;
  41. $this->responseFactory = $responseFactory;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. *
  46. * @return ServerRequestInterface
  47. */
  48. public function createRequest(Request $symfonyRequest)
  49. {
  50. $uri = $symfonyRequest->server->get('QUERY_STRING', '');
  51. $uri = $symfonyRequest->getSchemeAndHttpHost().$symfonyRequest->getBaseUrl().$symfonyRequest->getPathInfo().('' !== $uri ? '?'.$uri : '');
  52. $request = $this->serverRequestFactory->createServerRequest(
  53. $symfonyRequest->getMethod(),
  54. $uri,
  55. $symfonyRequest->server->all()
  56. );
  57. foreach ($symfonyRequest->headers->all() as $name => $value) {
  58. try {
  59. $request = $request->withHeader($name, $value);
  60. } catch (\InvalidArgumentException $e) {
  61. // ignore invalid header
  62. }
  63. }
  64. $body = $this->streamFactory->createStreamFromResource($symfonyRequest->getContent(true));
  65. if (method_exists(Request::class, 'getContentTypeFormat')) {
  66. $format = $symfonyRequest->getContentTypeFormat();
  67. } else {
  68. $format = $symfonyRequest->getContentType();
  69. }
  70. if ('json' === $format) {
  71. $parsedBody = json_decode($symfonyRequest->getContent(), true, 512, \JSON_BIGINT_AS_STRING);
  72. if (!\is_array($parsedBody)) {
  73. $parsedBody = null;
  74. }
  75. } else {
  76. $parsedBody = $symfonyRequest->request->all();
  77. }
  78. $request = $request
  79. ->withBody($body)
  80. ->withUploadedFiles($this->getFiles($symfonyRequest->files->all()))
  81. ->withCookieParams($symfonyRequest->cookies->all())
  82. ->withQueryParams($symfonyRequest->query->all())
  83. ->withParsedBody($parsedBody)
  84. ;
  85. foreach ($symfonyRequest->attributes->all() as $key => $value) {
  86. $request = $request->withAttribute($key, $value);
  87. }
  88. return $request;
  89. }
  90. /**
  91. * Converts Symfony uploaded files array to the PSR one.
  92. */
  93. private function getFiles(array $uploadedFiles): array
  94. {
  95. $files = [];
  96. foreach ($uploadedFiles as $key => $value) {
  97. if (null === $value) {
  98. $files[$key] = $this->uploadedFileFactory->createUploadedFile($this->streamFactory->createStream(), 0, \UPLOAD_ERR_NO_FILE);
  99. continue;
  100. }
  101. if ($value instanceof UploadedFile) {
  102. $files[$key] = $this->createUploadedFile($value);
  103. } else {
  104. $files[$key] = $this->getFiles($value);
  105. }
  106. }
  107. return $files;
  108. }
  109. /**
  110. * Creates a PSR-7 UploadedFile instance from a Symfony one.
  111. */
  112. private function createUploadedFile(UploadedFile $symfonyUploadedFile): UploadedFileInterface
  113. {
  114. return $this->uploadedFileFactory->createUploadedFile(
  115. $this->streamFactory->createStreamFromFile(
  116. $symfonyUploadedFile->getRealPath()
  117. ),
  118. (int) $symfonyUploadedFile->getSize(),
  119. $symfonyUploadedFile->getError(),
  120. $symfonyUploadedFile->getClientOriginalName(),
  121. $symfonyUploadedFile->getClientMimeType()
  122. );
  123. }
  124. /**
  125. * {@inheritdoc}
  126. *
  127. * @return ResponseInterface
  128. */
  129. public function createResponse(Response $symfonyResponse)
  130. {
  131. $response = $this->responseFactory->createResponse($symfonyResponse->getStatusCode(), Response::$statusTexts[$symfonyResponse->getStatusCode()] ?? '');
  132. if ($symfonyResponse instanceof BinaryFileResponse && !$symfonyResponse->headers->has('Content-Range')) {
  133. $stream = $this->streamFactory->createStreamFromFile(
  134. $symfonyResponse->getFile()->getPathname()
  135. );
  136. } else {
  137. $stream = $this->streamFactory->createStreamFromFile('php://temp', 'wb+');
  138. if ($symfonyResponse instanceof StreamedResponse || $symfonyResponse instanceof BinaryFileResponse) {
  139. ob_start(function ($buffer) use ($stream) {
  140. $stream->write($buffer);
  141. return '';
  142. }, 1);
  143. $symfonyResponse->sendContent();
  144. ob_end_clean();
  145. } else {
  146. $stream->write($symfonyResponse->getContent());
  147. }
  148. }
  149. $response = $response->withBody($stream);
  150. $headers = $symfonyResponse->headers->all();
  151. $cookies = $symfonyResponse->headers->getCookies();
  152. if (!empty($cookies)) {
  153. $headers['Set-Cookie'] = [];
  154. foreach ($cookies as $cookie) {
  155. $headers['Set-Cookie'][] = $cookie->__toString();
  156. }
  157. }
  158. foreach ($headers as $name => $value) {
  159. try {
  160. $response = $response->withHeader($name, $value);
  161. } catch (\InvalidArgumentException $e) {
  162. // ignore invalid header
  163. }
  164. }
  165. $protocolVersion = $symfonyResponse->getProtocolVersion();
  166. $response = $response->withProtocolVersion($protocolVersion);
  167. return $response;
  168. }
  169. }