vendor/guzzlehttp/guzzle/src/MessageFormatter.php

204 lines · 7969 bytes

  1<?php
  2
  3namespace GuzzleHttp;
  4
  5use Psr\Http\Message\MessageInterface;
  6use Psr\Http\Message\RequestInterface;
  7use Psr\Http\Message\ResponseInterface;
  8
  9/**
 10 * Formats log messages using variable substitutions for requests, responses,
 11 * and other transactional data.
 12 *
 13 * The following variable substitutions are supported:
 14 *
 15 * - {request}:        Full HTTP request message
 16 * - {response}:       Full HTTP response message
 17 * - {ts}:             ISO 8601 date in GMT
 18 * - {date_iso_8601}   ISO 8601 date in GMT
 19 * - {date_common_log} Apache common log date using the configured timezone.
 20 * - {host}:           Host of the request
 21 * - {method}:         Method of the request
 22 * - {uri}:            URI of the request
 23 * - {version}:        Protocol version
 24 * - {target}:         Request target of the request (path + query + fragment)
 25 * - {hostname}:       Hostname of the machine that sent the request
 26 * - {code}:           Status code of the response (if available)
 27 * - {phrase}:         Reason phrase of the response  (if available)
 28 * - {error}:          Any error messages (if available)
 29 * - {req_header_*}:   Replace `*` with the lowercased name of a request header to add to the message
 30 * - {res_header_*}:   Replace `*` with the lowercased name of a response header to add to the message
 31 * - {req_headers}:    Request headers
 32 * - {res_headers}:    Response headers
 33 * - {req_body}:       Request body
 34 * - {res_body}:       Response body
 35 *
 36 * @final
 37 */
 38class MessageFormatter implements MessageFormatterInterface
 39{
 40    /**
 41     * Apache Common Log Format.
 42     *
 43     * @see https://httpd.apache.org/docs/2.4/logs.html#common
 44     *
 45     * @var string
 46     */
 47    public const CLF = '{hostname} {req_header_User-Agent} - [{date_common_log}] "{method} {target} HTTP/{version}" {code} {res_header_Content-Length}';
 48    public const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
 49    public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
 50
 51    /**
 52     * @var string Template used to format log messages
 53     */
 54    private $template;
 55
 56    /**
 57     * @param string $template Log message template
 58     */
 59    public function __construct(?string $template = self::CLF)
 60    {
 61        $this->template = $template ?: self::CLF;
 62    }
 63
 64    /**
 65     * Returns a formatted message string.
 66     *
 67     * @param RequestInterface       $request  Request that was sent
 68     * @param ResponseInterface|null $response Response that was received
 69     * @param \Throwable|null        $error    Exception that was received
 70     */
 71    public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string
 72    {
 73        $cache = [];
 74
 75        $result = \preg_replace_callback(
 76            '/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
 77            function (array $matches) use ($request, $response, $error, &$cache) {
 78                if (isset($cache[$matches[1]])) {
 79                    return $cache[$matches[1]];
 80                }
 81
 82                $result = '';
 83                switch ($matches[1]) {
 84                    case 'request':
 85                        $result = Psr7\Message::toString($request);
 86                        break;
 87                    case 'response':
 88                        $result = $response ? Psr7\Message::toString($response) : '';
 89                        break;
 90                    case 'req_headers':
 91                        $result = \trim($request->getMethod()
 92                                .' '.$request->getRequestTarget(), " \n\r\t\0\x0B")
 93                            .' HTTP/'.$request->getProtocolVersion()."\r\n"
 94                            .$this->headers($request);
 95                        break;
 96                    case 'res_headers':
 97                        $result = $response ?
 98                            \sprintf(
 99                                'HTTP/%s %d %s',
100                                $response->getProtocolVersion(),
101                                $response->getStatusCode(),
102                                $response->getReasonPhrase()
103                            )."\r\n".$this->headers($response)
104                            : 'NULL';
105                        break;
106                    case 'req_body':
107                        $result = $request->getBody()->__toString();
108                        break;
109                    case 'res_body':
110                        if (!$response instanceof ResponseInterface) {
111                            $result = 'NULL';
112                            break;
113                        }
114
115                        $body = $response->getBody();
116
117                        if (!$body->isSeekable()) {
118                            $result = 'RESPONSE_NOT_LOGGEABLE';
119                            break;
120                        }
121
122                        $result = $response->getBody()->__toString();
123                        break;
124                    case 'ts':
125                    case 'date_iso_8601':
126                        $result = \gmdate('c');
127                        break;
128                    case 'date_common_log':
129                        $result = \date('d/M/Y:H:i:s O');
130                        break;
131                    case 'method':
132                        $result = $request->getMethod();
133                        break;
134                    case 'version':
135                        $result = $request->getProtocolVersion();
136                        break;
137                    case 'uri':
138                    case 'url':
139                        $result = $request->getUri()->__toString();
140                        break;
141                    case 'target':
142                        $result = $request->getRequestTarget();
143                        break;
144                    case 'req_version':
145                        $result = $request->getProtocolVersion();
146                        break;
147                    case 'res_version':
148                        $result = $response
149                            ? $response->getProtocolVersion()
150                            : 'NULL';
151                        break;
152                    case 'host':
153                        $result = $request->getHeaderLine('Host');
154                        break;
155                    case 'hostname':
156                        $result = \gethostname();
157                        break;
158                    case 'code':
159                        $result = $response ? $response->getStatusCode() : 'NULL';
160                        break;
161                    case 'phrase':
162                        $result = $response ? $response->getReasonPhrase() : 'NULL';
163                        break;
164                    case 'error':
165                        $result = $error ? $error->getMessage() : 'NULL';
166                        break;
167                    default:
168                        // handle prefixed dynamic headers
169                        if (\strpos($matches[1], 'req_header_') === 0) {
170                            $result = $request->getHeaderLine(\substr($matches[1], 11));
171                        } elseif (\strpos($matches[1], 'res_header_') === 0) {
172                            $result = $response
173                                ? $response->getHeaderLine(\substr($matches[1], 11))
174                                : 'NULL';
175                        }
176                }
177
178                $cache[$matches[1]] = $result;
179
180                return $result;
181            },
182            $this->template
183        );
184
185        if ($result === null) {
186            throw new \RuntimeException('Unable to format message: '.\preg_last_error_msg());
187        }
188
189        return $result;
190    }
191
192    /**
193     * Get headers from message as string
194     */
195    private function headers(MessageInterface $message): string
196    {
197        $result = '';
198        foreach ($message->getHeaders() as $name => $values) {
199            $result .= $name.': '.\implode(', ', $values)."\r\n";
200        }
201
202        return \trim($result, " \n\r\t\0\x0B");
203    }
204}