MessageTrait.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
  6. * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
  8. */
  9. namespace Zend\Diactoros;
  10. use InvalidArgumentException;
  11. use Psr\Http\Message\StreamInterface;
  12. /**
  13. * Trait implementing the various methods defined in MessageInterface.
  14. *
  15. * @see https://github.com/php-fig/http-message/tree/master/src/MessageInterface.php
  16. */
  17. trait MessageTrait
  18. {
  19. /**
  20. * List of all registered headers, as key => array of values.
  21. *
  22. * @var array
  23. */
  24. protected $headers = [];
  25. /**
  26. * Map of normalized header name to original name used to register header.
  27. *
  28. * @var array
  29. */
  30. protected $headerNames = [];
  31. /**
  32. * @var string
  33. */
  34. private $protocol = '1.1';
  35. /**
  36. * @var StreamInterface
  37. */
  38. private $stream;
  39. /**
  40. * Retrieves the HTTP protocol version as a string.
  41. *
  42. * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
  43. *
  44. * @return string HTTP protocol version.
  45. */
  46. public function getProtocolVersion()
  47. {
  48. return $this->protocol;
  49. }
  50. /**
  51. * Return an instance with the specified HTTP protocol version.
  52. *
  53. * The version string MUST contain only the HTTP version number (e.g.,
  54. * "1.1", "1.0").
  55. *
  56. * This method MUST be implemented in such a way as to retain the
  57. * immutability of the message, and MUST return an instance that has the
  58. * new protocol version.
  59. *
  60. * @param string $version HTTP protocol version
  61. * @return static
  62. */
  63. public function withProtocolVersion($version)
  64. {
  65. $this->validateProtocolVersion($version);
  66. $new = clone $this;
  67. $new->protocol = $version;
  68. return $new;
  69. }
  70. /**
  71. * Retrieves all message headers.
  72. *
  73. * The keys represent the header name as it will be sent over the wire, and
  74. * each value is an array of strings associated with the header.
  75. *
  76. * // Represent the headers as a string
  77. * foreach ($message->getHeaders() as $name => $values) {
  78. * echo $name . ": " . implode(", ", $values);
  79. * }
  80. *
  81. * // Emit headers iteratively:
  82. * foreach ($message->getHeaders() as $name => $values) {
  83. * foreach ($values as $value) {
  84. * header(sprintf('%s: %s', $name, $value), false);
  85. * }
  86. * }
  87. *
  88. * @return array Returns an associative array of the message's headers. Each
  89. * key MUST be a header name, and each value MUST be an array of strings.
  90. */
  91. public function getHeaders()
  92. {
  93. return $this->headers;
  94. }
  95. /**
  96. * Checks if a header exists by the given case-insensitive name.
  97. *
  98. * @param string $header Case-insensitive header name.
  99. * @return bool Returns true if any header names match the given header
  100. * name using a case-insensitive string comparison. Returns false if
  101. * no matching header name is found in the message.
  102. */
  103. public function hasHeader($header)
  104. {
  105. return array_key_exists(strtolower($header), $this->headerNames);
  106. }
  107. /**
  108. * Retrieves a message header value by the given case-insensitive name.
  109. *
  110. * This method returns an array of all the header values of the given
  111. * case-insensitive header name.
  112. *
  113. * If the header does not appear in the message, this method MUST return an
  114. * empty array.
  115. *
  116. * @param string $header Case-insensitive header field name.
  117. * @return string[] An array of string values as provided for the given
  118. * header. If the header does not appear in the message, this method MUST
  119. * return an empty array.
  120. */
  121. public function getHeader($header)
  122. {
  123. if (! $this->hasHeader($header)) {
  124. return [];
  125. }
  126. $header = $this->headerNames[strtolower($header)];
  127. $value = $this->headers[$header];
  128. $value = is_array($value) ? $value : [$value];
  129. return $value;
  130. }
  131. /**
  132. * Retrieves a comma-separated string of the values for a single header.
  133. *
  134. * This method returns all of the header values of the given
  135. * case-insensitive header name as a string concatenated together using
  136. * a comma.
  137. *
  138. * NOTE: Not all header values may be appropriately represented using
  139. * comma concatenation. For such headers, use getHeader() instead
  140. * and supply your own delimiter when concatenating.
  141. *
  142. * If the header does not appear in the message, this method MUST return
  143. * an empty string.
  144. *
  145. * @param string $name Case-insensitive header field name.
  146. * @return string A string of values as provided for the given header
  147. * concatenated together using a comma. If the header does not appear in
  148. * the message, this method MUST return an empty string.
  149. */
  150. public function getHeaderLine($name)
  151. {
  152. $value = $this->getHeader($name);
  153. if (empty($value)) {
  154. return '';
  155. }
  156. return implode(',', $value);
  157. }
  158. /**
  159. * Return an instance with the provided header, replacing any existing
  160. * values of any headers with the same case-insensitive name.
  161. *
  162. * While header names are case-insensitive, the casing of the header will
  163. * be preserved by this function, and returned from getHeaders().
  164. *
  165. * This method MUST be implemented in such a way as to retain the
  166. * immutability of the message, and MUST return an instance that has the
  167. * new and/or updated header and value.
  168. *
  169. * @param string $header Case-insensitive header field name.
  170. * @param string|string[] $value Header value(s).
  171. * @return static
  172. * @throws \InvalidArgumentException for invalid header names or values.
  173. */
  174. public function withHeader($header, $value)
  175. {
  176. if (is_string($value)) {
  177. $value = [$value];
  178. }
  179. if (! is_array($value) || ! $this->arrayContainsOnlyStrings($value)) {
  180. throw new InvalidArgumentException(
  181. 'Invalid header value; must be a string or array of strings'
  182. );
  183. }
  184. HeaderSecurity::assertValidName($header);
  185. self::assertValidHeaderValue($value);
  186. $normalized = strtolower($header);
  187. $new = clone $this;
  188. if ($new->hasHeader($header)) {
  189. unset($new->headers[$new->headerNames[$normalized]]);
  190. }
  191. $new->headerNames[$normalized] = $header;
  192. $new->headers[$header] = $value;
  193. return $new;
  194. }
  195. /**
  196. * Return an instance with the specified header appended with the
  197. * given value.
  198. *
  199. * Existing values for the specified header will be maintained. The new
  200. * value(s) will be appended to the existing list. If the header did not
  201. * exist previously, it will be added.
  202. *
  203. * This method MUST be implemented in such a way as to retain the
  204. * immutability of the message, and MUST return an instance that has the
  205. * new header and/or value.
  206. *
  207. * @param string $header Case-insensitive header field name to add.
  208. * @param string|string[] $value Header value(s).
  209. * @return static
  210. * @throws \InvalidArgumentException for invalid header names or values.
  211. */
  212. public function withAddedHeader($header, $value)
  213. {
  214. if (is_string($value)) {
  215. $value = [ $value ];
  216. }
  217. if (! is_array($value) || ! $this->arrayContainsOnlyStrings($value)) {
  218. throw new InvalidArgumentException(
  219. 'Invalid header value; must be a string or array of strings'
  220. );
  221. }
  222. HeaderSecurity::assertValidName($header);
  223. self::assertValidHeaderValue($value);
  224. if (! $this->hasHeader($header)) {
  225. return $this->withHeader($header, $value);
  226. }
  227. $normalized = strtolower($header);
  228. $header = $this->headerNames[$normalized];
  229. $new = clone $this;
  230. $new->headers[$header] = array_merge($this->headers[$header], $value);
  231. return $new;
  232. }
  233. /**
  234. * Return an instance without the specified header.
  235. *
  236. * Header resolution MUST be done without case-sensitivity.
  237. *
  238. * This method MUST be implemented in such a way as to retain the
  239. * immutability of the message, and MUST return an instance that removes
  240. * the named header.
  241. *
  242. * @param string $header Case-insensitive header field name to remove.
  243. * @return static
  244. */
  245. public function withoutHeader($header)
  246. {
  247. if (! $this->hasHeader($header)) {
  248. return clone $this;
  249. }
  250. $normalized = strtolower($header);
  251. $original = $this->headerNames[$normalized];
  252. $new = clone $this;
  253. unset($new->headers[$original], $new->headerNames[$normalized]);
  254. return $new;
  255. }
  256. /**
  257. * Gets the body of the message.
  258. *
  259. * @return StreamInterface Returns the body as a stream.
  260. */
  261. public function getBody()
  262. {
  263. return $this->stream;
  264. }
  265. /**
  266. * Return an instance with the specified message body.
  267. *
  268. * The body MUST be a StreamInterface object.
  269. *
  270. * This method MUST be implemented in such a way as to retain the
  271. * immutability of the message, and MUST return a new instance that has the
  272. * new body stream.
  273. *
  274. * @param StreamInterface $body Body.
  275. * @return static
  276. * @throws \InvalidArgumentException When the body is not valid.
  277. */
  278. public function withBody(StreamInterface $body)
  279. {
  280. $new = clone $this;
  281. $new->stream = $body;
  282. return $new;
  283. }
  284. private function getStream($stream, $modeIfNotInstance)
  285. {
  286. if ($stream instanceof StreamInterface) {
  287. return $stream;
  288. }
  289. if (! is_string($stream) && ! is_resource($stream)) {
  290. throw new InvalidArgumentException(
  291. 'Stream must be a string stream resource identifier, '
  292. . 'an actual stream resource, '
  293. . 'or a Psr\Http\Message\StreamInterface implementation'
  294. );
  295. }
  296. return new Stream($stream, $modeIfNotInstance);
  297. }
  298. /**
  299. * Test that an array contains only strings
  300. *
  301. * @param array $array
  302. * @return bool
  303. */
  304. private function arrayContainsOnlyStrings(array $array)
  305. {
  306. return array_reduce($array, [__CLASS__, 'filterStringValue'], true);
  307. }
  308. /**
  309. * Filter a set of headers to ensure they are in the correct internal format.
  310. *
  311. * Used by message constructors to allow setting all initial headers at once.
  312. *
  313. * @param array $originalHeaders Headers to filter.
  314. * @return array Filtered headers and names.
  315. */
  316. private function filterHeaders(array $originalHeaders)
  317. {
  318. $headerNames = $headers = [];
  319. foreach ($originalHeaders as $header => $value) {
  320. if (! is_string($header)) {
  321. throw new InvalidArgumentException(sprintf(
  322. 'Invalid header name; expected non-empty string, received %s',
  323. gettype($header)
  324. ));
  325. }
  326. if (! is_array($value) && ! is_string($value) && ! is_numeric($value)) {
  327. throw new InvalidArgumentException(sprintf(
  328. 'Invalid header value type; expected number, string, or array; received %s',
  329. (is_object($value) ? get_class($value) : gettype($value))
  330. ));
  331. }
  332. if (is_array($value)) {
  333. array_walk($value, function ($item) {
  334. if (! is_string($item) && ! is_numeric($item)) {
  335. throw new InvalidArgumentException(sprintf(
  336. 'Invalid header value type; expected number, string, or array; received %s',
  337. (is_object($item) ? get_class($item) : gettype($item))
  338. ));
  339. }
  340. });
  341. }
  342. if (! is_array($value)) {
  343. $value = [ $value ];
  344. }
  345. $headerNames[strtolower($header)] = $header;
  346. $headers[$header] = $value;
  347. }
  348. return [$headerNames, $headers];
  349. }
  350. /**
  351. * Test if a value is a string
  352. *
  353. * Used with array_reduce.
  354. *
  355. * @param bool $carry
  356. * @param mixed $item
  357. * @return bool
  358. */
  359. private static function filterStringValue($carry, $item)
  360. {
  361. if (! is_string($item)) {
  362. return false;
  363. }
  364. return $carry;
  365. }
  366. /**
  367. * Assert that the provided header values are valid.
  368. *
  369. * @see http://tools.ietf.org/html/rfc7230#section-3.2
  370. * @param string[] $values
  371. * @throws InvalidArgumentException
  372. */
  373. private static function assertValidHeaderValue(array $values)
  374. {
  375. array_walk($values, __NAMESPACE__ . '\HeaderSecurity::assertValid');
  376. }
  377. /**
  378. * Validate the HTTP protocol version
  379. *
  380. * @param string $version
  381. * @throws InvalidArgumentException on invalid HTTP protocol version
  382. */
  383. private function validateProtocolVersion($version)
  384. {
  385. if (empty($version)) {
  386. throw new InvalidArgumentException(sprintf(
  387. 'HTTP protocol version can not be empty'
  388. ));
  389. }
  390. if (! is_string($version)) {
  391. throw new InvalidArgumentException(sprintf(
  392. 'Unsupported HTTP protocol version; must be a string, received %s',
  393. (is_object($version) ? get_class($version) : gettype($version))
  394. ));
  395. }
  396. // HTTP/1 uses a "<major>.<minor>" numbering scheme to indicate
  397. // versions of the protocol, while HTTP/2 does not.
  398. if (! preg_match('#^(1\.[01]|2)$#', $version)) {
  399. throw new InvalidArgumentException(sprintf(
  400. 'Unsupported HTTP protocol version "%s" provided',
  401. $version
  402. ));
  403. }
  404. }
  405. }