PsrHttpFactory.php 6.1 KB

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