PsrHttpFactory.php 6.8 KB

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