MultipartStream.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\StreamInterface;
  5. /**
  6. * Stream that when read returns bytes for a streaming multipart or
  7. * multipart/form-data stream.
  8. */
  9. final class MultipartStream implements StreamInterface
  10. {
  11. use StreamDecoratorTrait;
  12. /** @var string */
  13. private $boundary;
  14. /** @var StreamInterface */
  15. private $stream;
  16. /**
  17. * @param array $elements Array of associative arrays, each containing a
  18. * required "name" key mapping to the form field,
  19. * name, a required "contents" key mapping to a
  20. * StreamInterface/resource/string, an optional
  21. * "headers" associative array of custom headers,
  22. * and an optional "filename" key mapping to a
  23. * string to send as the filename in the part.
  24. * @param string $boundary You can optionally provide a specific boundary
  25. *
  26. * @throws \InvalidArgumentException
  27. */
  28. public function __construct(array $elements = [], string $boundary = null)
  29. {
  30. $this->boundary = $boundary ?: bin2hex(random_bytes(20));
  31. $this->stream = $this->createStream($elements);
  32. }
  33. public function getBoundary(): string
  34. {
  35. return $this->boundary;
  36. }
  37. public function isWritable(): bool
  38. {
  39. return false;
  40. }
  41. /**
  42. * Get the headers needed before transferring the content of a POST file
  43. *
  44. * @param array<string, string> $headers
  45. */
  46. private function getHeaders(array $headers): string
  47. {
  48. $str = '';
  49. foreach ($headers as $key => $value) {
  50. $str .= "{$key}: {$value}\r\n";
  51. }
  52. return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n";
  53. }
  54. /**
  55. * Create the aggregate stream that will be used to upload the POST data
  56. */
  57. protected function createStream(array $elements = []): StreamInterface
  58. {
  59. $stream = new AppendStream();
  60. foreach ($elements as $element) {
  61. if (!is_array($element)) {
  62. throw new \UnexpectedValueException("An array is expected");
  63. }
  64. $this->addElement($stream, $element);
  65. }
  66. // Add the trailing boundary with CRLF
  67. $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n"));
  68. return $stream;
  69. }
  70. private function addElement(AppendStream $stream, array $element): void
  71. {
  72. foreach (['contents', 'name'] as $key) {
  73. if (!array_key_exists($key, $element)) {
  74. throw new \InvalidArgumentException("A '{$key}' key is required");
  75. }
  76. }
  77. $element['contents'] = Utils::streamFor($element['contents']);
  78. if (empty($element['filename'])) {
  79. $uri = $element['contents']->getMetadata('uri');
  80. if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') {
  81. $element['filename'] = $uri;
  82. }
  83. }
  84. [$body, $headers] = $this->createElement(
  85. $element['name'],
  86. $element['contents'],
  87. $element['filename'] ?? null,
  88. $element['headers'] ?? []
  89. );
  90. $stream->addStream(Utils::streamFor($this->getHeaders($headers)));
  91. $stream->addStream($body);
  92. $stream->addStream(Utils::streamFor("\r\n"));
  93. }
  94. private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array
  95. {
  96. // Set a default content-disposition header if one was no provided
  97. $disposition = $this->getHeader($headers, 'content-disposition');
  98. if (!$disposition) {
  99. $headers['Content-Disposition'] = ($filename === '0' || $filename)
  100. ? sprintf(
  101. 'form-data; name="%s"; filename="%s"',
  102. $name,
  103. basename($filename)
  104. )
  105. : "form-data; name=\"{$name}\"";
  106. }
  107. // Set a default content-length header if one was no provided
  108. $length = $this->getHeader($headers, 'content-length');
  109. if (!$length) {
  110. if ($length = $stream->getSize()) {
  111. $headers['Content-Length'] = (string) $length;
  112. }
  113. }
  114. // Set a default Content-Type if one was not supplied
  115. $type = $this->getHeader($headers, 'content-type');
  116. if (!$type && ($filename === '0' || $filename)) {
  117. if ($type = MimeType::fromFilename($filename)) {
  118. $headers['Content-Type'] = $type;
  119. }
  120. }
  121. return [$stream, $headers];
  122. }
  123. private function getHeader(array $headers, string $key)
  124. {
  125. $lowercaseHeader = strtolower($key);
  126. foreach ($headers as $k => $v) {
  127. if (strtolower($k) === $lowercaseHeader) {
  128. return $v;
  129. }
  130. }
  131. return null;
  132. }
  133. }