酒店预订平台
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

253 líneas
8.1 KiB

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