MultipartStream.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 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. /**
  95. * @param string[] $headers
  96. *
  97. * @return array{0: StreamInterface, 1: string[]}
  98. */
  99. private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array
  100. {
  101. // Set a default content-disposition header if one was no provided
  102. $disposition = self::getHeader($headers, 'content-disposition');
  103. if (!$disposition) {
  104. $headers['Content-Disposition'] = ($filename === '0' || $filename)
  105. ? sprintf(
  106. 'form-data; name="%s"; filename="%s"',
  107. $name,
  108. basename($filename)
  109. )
  110. : "form-data; name=\"{$name}\"";
  111. }
  112. // Set a default content-length header if one was no provided
  113. $length = self::getHeader($headers, 'content-length');
  114. if (!$length) {
  115. if ($length = $stream->getSize()) {
  116. $headers['Content-Length'] = (string) $length;
  117. }
  118. }
  119. // Set a default Content-Type if one was not supplied
  120. $type = self::getHeader($headers, 'content-type');
  121. if (!$type && ($filename === '0' || $filename)) {
  122. $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream';
  123. }
  124. return [$stream, $headers];
  125. }
  126. /**
  127. * @param string[] $headers
  128. */
  129. private static function getHeader(array $headers, string $key): ?string
  130. {
  131. $lowercaseHeader = strtolower($key);
  132. foreach ($headers as $k => $v) {
  133. if (strtolower((string) $k) === $lowercaseHeader) {
  134. return $v;
  135. }
  136. }
  137. return null;
  138. }
  139. }