Message.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. $body->rewind();
  60. $summary = $body->read($truncateAt);
  61. $body->rewind();
  62. if ($size > $truncateAt) {
  63. $summary .= ' (truncated...)';
  64. }
  65. // Matches any printable character, including unicode characters:
  66. // letters, marks, numbers, punctuation, spacing, and separators.
  67. if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) {
  68. return null;
  69. }
  70. return $summary;
  71. }
  72. /**
  73. * Attempts to rewind a message body and throws an exception on failure.
  74. *
  75. * The body of the message will only be rewound if a call to `tell()`
  76. * returns a value other than `0`.
  77. *
  78. * @param MessageInterface $message Message to rewind
  79. *
  80. * @throws \RuntimeException
  81. */
  82. public static function rewindBody(MessageInterface $message): void
  83. {
  84. $body = $message->getBody();
  85. if ($body->tell()) {
  86. $body->rewind();
  87. }
  88. }
  89. /**
  90. * Parses an HTTP message into an associative array.
  91. *
  92. * The array contains the "start-line" key containing the start line of
  93. * the message, "headers" key containing an associative array of header
  94. * array values, and a "body" key containing the body of the message.
  95. *
  96. * @param string $message HTTP request or response to parse.
  97. */
  98. public static function parseMessage(string $message): array
  99. {
  100. if (!$message) {
  101. throw new \InvalidArgumentException('Invalid message');
  102. }
  103. $message = ltrim($message, "\r\n");
  104. $messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
  105. if ($messageParts === false || count($messageParts) !== 2) {
  106. throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
  107. }
  108. [$rawHeaders, $body] = $messageParts;
  109. $rawHeaders .= "\r\n"; // Put back the delimiter we split previously
  110. $headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
  111. if ($headerParts === false || count($headerParts) !== 2) {
  112. throw new \InvalidArgumentException('Invalid message: Missing status line');
  113. }
  114. [$startLine, $rawHeaders] = $headerParts;
  115. if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
  116. // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
  117. $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
  118. }
  119. /** @var array[] $headerLines */
  120. $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
  121. // If these aren't the same, then one line didn't match and there's an invalid header.
  122. if ($count !== substr_count($rawHeaders, "\n")) {
  123. // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
  124. if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
  125. throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
  126. }
  127. throw new \InvalidArgumentException('Invalid header syntax');
  128. }
  129. $headers = [];
  130. foreach ($headerLines as $headerLine) {
  131. $headers[$headerLine[1]][] = $headerLine[2];
  132. }
  133. return [
  134. 'start-line' => $startLine,
  135. 'headers' => $headers,
  136. 'body' => $body,
  137. ];
  138. }
  139. /**
  140. * Constructs a URI for an HTTP request message.
  141. *
  142. * @param string $path Path from the start-line
  143. * @param array $headers Array of headers (each value an array).
  144. */
  145. public static function parseRequestUri(string $path, array $headers): string
  146. {
  147. $hostKey = array_filter(array_keys($headers), function ($k) {
  148. // Numeric array keys are converted to int by PHP.
  149. $k = (string) $k;
  150. return strtolower($k) === 'host';
  151. });
  152. // If no host is found, then a full URI cannot be constructed.
  153. if (!$hostKey) {
  154. return $path;
  155. }
  156. $host = $headers[reset($hostKey)][0];
  157. $scheme = substr($host, -4) === ':443' ? 'https' : 'http';
  158. return $scheme . '://' . $host . '/' . ltrim($path, '/');
  159. }
  160. /**
  161. * Parses a request message string into a request object.
  162. *
  163. * @param string $message Request message string.
  164. */
  165. public static function parseRequest(string $message): RequestInterface
  166. {
  167. $data = self::parseMessage($message);
  168. $matches = [];
  169. if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
  170. throw new \InvalidArgumentException('Invalid request string');
  171. }
  172. $parts = explode(' ', $data['start-line'], 3);
  173. $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
  174. $request = new Request(
  175. $parts[0],
  176. $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
  177. $data['headers'],
  178. $data['body'],
  179. $version
  180. );
  181. return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
  182. }
  183. /**
  184. * Parses a response message string into a response object.
  185. *
  186. * @param string $message Response message string.
  187. */
  188. public static function parseResponse(string $message): ResponseInterface
  189. {
  190. $data = self::parseMessage($message);
  191. // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
  192. // between status-code and reason-phrase is required. But browsers accept
  193. // responses without space and reason as well.
  194. if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
  195. throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
  196. }
  197. $parts = explode(' ', $data['start-line'], 3);
  198. return new Response(
  199. (int) $parts[1],
  200. $data['headers'],
  201. $data['body'],
  202. explode('/', $parts[0])[1],
  203. $parts[2] ?? null
  204. );
  205. }
  206. }