MessageTrait.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\MessageInterface;
  5. use Psr\Http\Message\StreamInterface;
  6. /**
  7. * Trait implementing functionality common to requests and responses.
  8. */
  9. trait MessageTrait
  10. {
  11. /** @var string[][] Map of all registered headers, as original name => array of values */
  12. private array $headers = [];
  13. /** @var string[] Map of lowercase header name => original name at registration */
  14. private array $headerNames = [];
  15. private string $protocol = '1.1';
  16. private ?StreamInterface $stream = null;
  17. public function getProtocolVersion(): string
  18. {
  19. return $this->protocol;
  20. }
  21. /**
  22. * @return static
  23. */
  24. public function withProtocolVersion(string $version): MessageInterface
  25. {
  26. $this->assertProtocolVersion($version);
  27. if ($this->protocol === $version) {
  28. return $this;
  29. }
  30. $new = clone $this;
  31. $new->protocol = $version;
  32. return $new;
  33. }
  34. public function getHeaders(): array
  35. {
  36. return $this->headers;
  37. }
  38. public function hasHeader(string $name): bool
  39. {
  40. return isset($this->headerNames[Utils::asciiToLower($name)]);
  41. }
  42. public function getHeader(string $name): array
  43. {
  44. $header = Utils::asciiToLower($name);
  45. if (!isset($this->headerNames[$header])) {
  46. return [];
  47. }
  48. $header = $this->headerNames[$header];
  49. return $this->headers[$header];
  50. }
  51. public function getHeaderLine(string $name): string
  52. {
  53. return implode(', ', $this->getHeader($name));
  54. }
  55. /**
  56. * @return static
  57. */
  58. public function withHeader(string $name, $value): MessageInterface
  59. {
  60. $this->assertHeader($name);
  61. $value = $this->normalizeHeaderValue($name, $value);
  62. $normalized = Utils::asciiToLower($name);
  63. $new = clone $this;
  64. if (isset($new->headerNames[$normalized])) {
  65. unset($new->headers[$new->headerNames[$normalized]]);
  66. }
  67. $new->headerNames[$normalized] = $name;
  68. $new->headers[$name] = $value;
  69. return $new;
  70. }
  71. /**
  72. * @return static
  73. */
  74. public function withAddedHeader(string $name, $value): MessageInterface
  75. {
  76. $this->assertHeader($name);
  77. $value = $this->normalizeHeaderValue($name, $value);
  78. $normalized = Utils::asciiToLower($name);
  79. $new = clone $this;
  80. if (isset($new->headerNames[$normalized])) {
  81. $name = $this->headerNames[$normalized];
  82. $new->headers[$name] = array_merge($this->headers[$name], $value);
  83. } else {
  84. $new->headerNames[$normalized] = $name;
  85. $new->headers[$name] = $value;
  86. }
  87. return $new;
  88. }
  89. /**
  90. * @return static
  91. */
  92. public function withoutHeader(string $name): MessageInterface
  93. {
  94. $normalized = Utils::asciiToLower($name);
  95. if (!isset($this->headerNames[$normalized])) {
  96. return $this;
  97. }
  98. $name = $this->headerNames[$normalized];
  99. $new = clone $this;
  100. unset($new->headers[$name], $new->headerNames[$normalized]);
  101. return $new;
  102. }
  103. public function getBody(): StreamInterface
  104. {
  105. if (!$this->stream) {
  106. $this->stream = Utils::streamFor('');
  107. }
  108. return $this->stream;
  109. }
  110. /**
  111. * @return static
  112. */
  113. public function withBody(StreamInterface $body): MessageInterface
  114. {
  115. if ($body === $this->stream) {
  116. return $this;
  117. }
  118. $new = clone $this;
  119. $new->stream = $body;
  120. return $new;
  121. }
  122. /**
  123. * @param (string|string[])[] $headers
  124. */
  125. private function setHeaders(array $headers): void
  126. {
  127. $this->headerNames = $this->headers = [];
  128. foreach ($headers as $header => $value) {
  129. // Numeric array keys are converted to int by PHP.
  130. $header = (string) $header;
  131. $this->assertHeader($header);
  132. $value = $this->normalizeHeaderValue($header, $value);
  133. $normalized = Utils::asciiToLower($header);
  134. if (isset($this->headerNames[$normalized])) {
  135. $header = $this->headerNames[$normalized];
  136. $this->headers[$header] = array_merge($this->headers[$header], $value);
  137. } else {
  138. $this->headerNames[$normalized] = $header;
  139. $this->headers[$header] = $value;
  140. }
  141. }
  142. }
  143. /**
  144. * @param mixed $value
  145. *
  146. * @return string[]
  147. */
  148. private function normalizeHeaderValue(string $header, $value): array
  149. {
  150. if (is_array($value) && $value === []) {
  151. throw new \InvalidArgumentException('Header value must be a non-empty array or string.');
  152. }
  153. if (!is_array($value)) {
  154. return $this->trimAndValidateHeaderValues($header, [$value]);
  155. }
  156. return $this->trimAndValidateHeaderValues($header, $value);
  157. }
  158. /**
  159. * Trims whitespace from the header values.
  160. *
  161. * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field.
  162. *
  163. * header-field = field-name ":" OWS field-value OWS
  164. * OWS = *( SP / HTAB )
  165. *
  166. * @param mixed[] $values Header values
  167. *
  168. * @return string[] Trimmed header values
  169. *
  170. * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.5
  171. */
  172. private function trimAndValidateHeaderValues(string $header, array $values): array
  173. {
  174. return array_map(function ($value) use ($header): string {
  175. if (!is_string($value)) {
  176. throw new \InvalidArgumentException(sprintf(
  177. 'Header value must be a string or array of strings but %s provided.',
  178. \get_debug_type($value)
  179. ));
  180. }
  181. $trimmed = trim($value, " \t");
  182. $this->assertValue($header, $trimmed);
  183. return $trimmed;
  184. }, array_values($values));
  185. }
  186. /**
  187. * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.1
  188. */
  189. private function assertHeader(string $header): void
  190. {
  191. if (!Rfc9110::isToken($header)) {
  192. throw new \InvalidArgumentException(sprintf('Invalid header name: %s', DiagnosticValue::escape($header)));
  193. }
  194. }
  195. private function assertProtocolVersion(string $version): void
  196. {
  197. if (!Rfc9112::isValidProtocolVersion($version)) {
  198. throw new \InvalidArgumentException('Protocol version must be a valid HTTP version number.');
  199. }
  200. }
  201. /**
  202. * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.5
  203. *
  204. * field-value = *( field-content / obs-fold )
  205. * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
  206. * field-vchar = VCHAR / obs-text
  207. * VCHAR = %x21-7E
  208. * obs-text = %x80-FF
  209. * obs-fold = CRLF 1*( SP / HTAB )
  210. */
  211. private function assertValue(string $header, string $value): void
  212. {
  213. // The regular expression intentionally does not support the obs-fold
  214. // production, because as per RFC 9112#5.2:
  215. //
  216. // A sender MUST NOT generate a message that includes line folding
  217. // (i.e., that has any field-value that contains a match to the obs-fold
  218. // rule) unless the message is intended for packaging within the
  219. // message/http media type.
  220. //
  221. // Clients must not send a request with line folding and a server
  222. // sending folded headers is likely very rare. Line folding is a fairly
  223. // obscure feature of HTTP/1.1 and thus not accepting folding is not
  224. // likely to break any legitimate use case.
  225. if (!Rfc9110::isFieldValue($value)) {
  226. $reason = strpbrk($value, "\r\n") !== false
  227. ? 'must not contain CR or LF characters'
  228. : 'contains an invalid control character';
  229. throw new \InvalidArgumentException(sprintf('Header "%s" %s.', DiagnosticValue::escape($header), $reason));
  230. }
  231. }
  232. }