Message.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\MessageInterface;
  5. use Psr\Http\Message\RequestInterface;
  6. use Psr\Http\Message\ResponseInterface;
  7. final class Message
  8. {
  9. /**
  10. * Returns the string representation of an HTTP message.
  11. *
  12. * @param MessageInterface $message Message to convert to a string.
  13. */
  14. public static function toString(MessageInterface $message): string
  15. {
  16. if ($message instanceof RequestInterface) {
  17. $msg = trim($message->getMethod() . ' '
  18. . $message->getRequestTarget())
  19. . ' HTTP/' . $message->getProtocolVersion();
  20. if (!$message->hasHeader('host')) {
  21. $msg .= "\r\nHost: " . $message->getUri()->getHost();
  22. }
  23. } elseif ($message instanceof ResponseInterface) {
  24. $msg = 'HTTP/' . $message->getProtocolVersion() . ' '
  25. . $message->getStatusCode() . ' '
  26. . $message->getReasonPhrase();
  27. } else {
  28. throw new \InvalidArgumentException('Unknown message type');
  29. }
  30. foreach ($message->getHeaders() as $name => $values) {
  31. if (strtolower($name) === 'set-cookie') {
  32. foreach ($values as $value) {
  33. $msg .= "\r\n{$name}: " . $value;
  34. }
  35. } else {
  36. $msg .= "\r\n{$name}: " . implode(', ', $values);
  37. }
  38. }
  39. return "{$msg}\r\n\r\n" . $message->getBody();
  40. }
  41. /**
  42. * Get a short summary of the message body.
  43. *
  44. * Will return `null` if the response is not printable.
  45. *
  46. * @param MessageInterface $message The message to get the body summary
  47. * @param int $truncateAt The maximum allowed size of the summary
  48. */
  49. public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string
  50. {
  51. $body = $message->getBody();
  52. if (!$body->isSeekable() || !$body->isReadable()) {
  53. return null;
  54. }
  55. $size = $body->getSize();
  56. if ($size === 0) {
  57. return null;
  58. }
  59. $summary = $body->read($truncateAt);
  60. $body->rewind();
  61. if ($size > $truncateAt) {
  62. $summary .= ' (truncated...)';
  63. }
  64. // Matches any printable character, including unicode characters:
  65. // letters, marks, numbers, punctuation, spacing, and separators.
  66. if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) {
  67. return null;
  68. }
  69. return $summary;
  70. }
  71. /**
  72. * Attempts to rewind a message body and throws an exception on failure.
  73. *
  74. * The body of the message will only be rewound if a call to `tell()`
  75. * returns a value other than `0`.
  76. *
  77. * @param MessageInterface $message Message to rewind
  78. *
  79. * @throws \RuntimeException
  80. */
  81. public static function rewindBody(MessageInterface $message): void
  82. {
  83. $body = $message->getBody();
  84. if ($body->tell()) {
  85. $body->rewind();
  86. }
  87. }
  88. /**
  89. * Parses an HTTP message into an associative array.
  90. *
  91. * The array contains the "start-line" key containing the start line of
  92. * the message, "headers" key containing an associative array of header
  93. * array values, and a "body" key containing the body of the message.
  94. *
  95. * @param string $message HTTP request or response to parse.
  96. */
  97. public static function parseMessage(string $message): array
  98. {
  99. if (!$message) {
  100. throw new \InvalidArgumentException('Invalid message');
  101. }
  102. $message = ltrim($message, "\r\n");
  103. $messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
  104. if ($messageParts === false || count($messageParts) !== 2) {
  105. throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
  106. }
  107. [$rawHeaders, $body] = $messageParts;
  108. $rawHeaders .= "\r\n"; // Put back the delimiter we split previously
  109. $headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
  110. if ($headerParts === false || count($headerParts) !== 2) {
  111. throw new \InvalidArgumentException('Invalid message: Missing status line');
  112. }
  113. [$startLine, $rawHeaders] = $headerParts;
  114. if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
  115. // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
  116. $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
  117. }
  118. /** @var array[] $headerLines */
  119. $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
  120. // If these aren't the same, then one line didn't match and there's an invalid header.
  121. if ($count !== substr_count($rawHeaders, "\n")) {
  122. // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
  123. if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
  124. throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
  125. }
  126. throw new \InvalidArgumentException('Invalid header syntax');
  127. }
  128. $headers = [];
  129. foreach ($headerLines as $headerLine) {
  130. $headers[$headerLine[1]][] = $headerLine[2];
  131. }
  132. return [
  133. 'start-line' => $startLine,
  134. 'headers' => $headers,
  135. 'body' => $body,
  136. ];
  137. }
  138. /**
  139. * Constructs a URI for an HTTP request message.
  140. *
  141. * @param string $path Path from the start-line
  142. * @param array $headers Array of headers (each value an array).
  143. */
  144. public static function parseRequestUri(string $path, array $headers): string
  145. {
  146. $hostKey = array_filter(array_keys($headers), function ($k) {
  147. // Numeric array keys are converted to int by PHP.
  148. $k = (string) $k;
  149. return strtolower($k) === 'host';
  150. });
  151. // If no host is found, then a full URI cannot be constructed.
  152. if (!$hostKey) {
  153. return $path;
  154. }
  155. $host = $headers[reset($hostKey)][0];
  156. $scheme = substr($host, -4) === ':443' ? 'https' : 'http';
  157. return $scheme . '://' . $host . '/' . ltrim($path, '/');
  158. }
  159. /**
  160. * Parses a request message string into a request object.
  161. *
  162. * @param string $message Request message string.
  163. */
  164. public static function parseRequest(string $message): RequestInterface
  165. {
  166. $data = self::parseMessage($message);
  167. $matches = [];
  168. if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
  169. throw new \InvalidArgumentException('Invalid request string');
  170. }
  171. $parts = explode(' ', $data['start-line'], 3);
  172. $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
  173. $request = new Request(
  174. $parts[0],
  175. $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
  176. $data['headers'],
  177. $data['body'],
  178. $version
  179. );
  180. return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
  181. }
  182. /**
  183. * Parses a response message string into a response object.
  184. *
  185. * @param string $message Response message string.
  186. */
  187. public static function parseResponse(string $message): ResponseInterface
  188. {
  189. $data = self::parseMessage($message);
  190. // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
  191. // between status-code and reason-phrase is required. But browsers accept
  192. // responses without space and reason as well.
  193. if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
  194. throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
  195. }
  196. $parts = explode(' ', $data['start-line'], 3);
  197. return new Response(
  198. (int) $parts[1],
  199. $data['headers'],
  200. $data['body'],
  201. explode('/', $parts[0])[1],
  202. $parts[2] ?? null
  203. );
  204. }
  205. }