MessageTrait.php 7.6 KB

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