MessageTrait.php 7.6 KB

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