@@ -6,12 +6,12 @@ |
||
6 | 6 | use OCA\FullTextSearch_Elasticsearch\Vendor\Psr\Http\Message\ResponseInterface; |
7 | 7 | interface MessageFormatterInterface |
8 | 8 | { |
9 | - /** |
|
10 | - * Returns a formatted message string. |
|
11 | - * |
|
12 | - * @param RequestInterface $request Request that was sent |
|
13 | - * @param ResponseInterface|null $response Response that was received |
|
14 | - * @param \Throwable|null $error Exception that was received |
|
15 | - */ |
|
16 | - public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null) : string; |
|
9 | + /** |
|
10 | + * Returns a formatted message string. |
|
11 | + * |
|
12 | + * @param RequestInterface $request Request that was sent |
|
13 | + * @param ResponseInterface|null $response Response that was received |
|
14 | + * @param \Throwable|null $error Exception that was received |
|
15 | + */ |
|
16 | + public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null) : string; |
|
17 | 17 | } |
@@ -10,116 +10,116 @@ |
||
10 | 10 | */ |
11 | 11 | final class CachingStream implements StreamInterface |
12 | 12 | { |
13 | - use StreamDecoratorTrait; |
|
14 | - /** @var StreamInterface Stream being wrapped */ |
|
15 | - private $remoteStream; |
|
16 | - /** @var int Number of bytes to skip reading due to a write on the buffer */ |
|
17 | - private $skipReadBytes = 0; |
|
18 | - /** |
|
19 | - * @var StreamInterface |
|
20 | - */ |
|
21 | - private $stream; |
|
22 | - /** |
|
23 | - * We will treat the buffer object as the body of the stream |
|
24 | - * |
|
25 | - * @param StreamInterface $stream Stream to cache. The cursor is assumed to be at the beginning of the stream. |
|
26 | - * @param StreamInterface $target Optionally specify where data is cached |
|
27 | - */ |
|
28 | - public function __construct(StreamInterface $stream, ?StreamInterface $target = null) |
|
29 | - { |
|
30 | - $this->remoteStream = $stream; |
|
31 | - $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); |
|
32 | - } |
|
33 | - public function getSize() : ?int |
|
34 | - { |
|
35 | - $remoteSize = $this->remoteStream->getSize(); |
|
36 | - if (null === $remoteSize) { |
|
37 | - return null; |
|
38 | - } |
|
39 | - return \max($this->stream->getSize(), $remoteSize); |
|
40 | - } |
|
41 | - public function rewind() : void |
|
42 | - { |
|
43 | - $this->seek(0); |
|
44 | - } |
|
45 | - public function seek($offset, $whence = \SEEK_SET) : void |
|
46 | - { |
|
47 | - if ($whence === \SEEK_SET) { |
|
48 | - $byte = $offset; |
|
49 | - } elseif ($whence === \SEEK_CUR) { |
|
50 | - $byte = $offset + $this->tell(); |
|
51 | - } elseif ($whence === \SEEK_END) { |
|
52 | - $size = $this->remoteStream->getSize(); |
|
53 | - if ($size === null) { |
|
54 | - $size = $this->cacheEntireStream(); |
|
55 | - } |
|
56 | - $byte = $size + $offset; |
|
57 | - } else { |
|
58 | - throw new \InvalidArgumentException('Invalid whence'); |
|
59 | - } |
|
60 | - $diff = $byte - $this->stream->getSize(); |
|
61 | - if ($diff > 0) { |
|
62 | - // Read the remoteStream until we have read in at least the amount |
|
63 | - // of bytes requested, or we reach the end of the file. |
|
64 | - while ($diff > 0 && !$this->remoteStream->eof()) { |
|
65 | - $this->read($diff); |
|
66 | - $diff = $byte - $this->stream->getSize(); |
|
67 | - } |
|
68 | - } else { |
|
69 | - // We can just do a normal seek since we've already seen this byte. |
|
70 | - $this->stream->seek($byte); |
|
71 | - } |
|
72 | - } |
|
73 | - public function read($length) : string |
|
74 | - { |
|
75 | - // Perform a regular read on any previously read data from the buffer |
|
76 | - $data = $this->stream->read($length); |
|
77 | - $remaining = $length - \strlen($data); |
|
78 | - // More data was requested so read from the remote stream |
|
79 | - if ($remaining) { |
|
80 | - // If data was written to the buffer in a position that would have |
|
81 | - // been filled from the remote stream, then we must skip bytes on |
|
82 | - // the remote stream to emulate overwriting bytes from that |
|
83 | - // position. This mimics the behavior of other PHP stream wrappers. |
|
84 | - $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes); |
|
85 | - if ($this->skipReadBytes) { |
|
86 | - $len = \strlen($remoteData); |
|
87 | - $remoteData = \substr($remoteData, $this->skipReadBytes); |
|
88 | - $this->skipReadBytes = \max(0, $this->skipReadBytes - $len); |
|
89 | - } |
|
90 | - $data .= $remoteData; |
|
91 | - $this->stream->write($remoteData); |
|
92 | - } |
|
93 | - return $data; |
|
94 | - } |
|
95 | - public function write($string) : int |
|
96 | - { |
|
97 | - // When appending to the end of the currently read stream, you'll want |
|
98 | - // to skip bytes from being read from the remote stream to emulate |
|
99 | - // other stream wrappers. Basically replacing bytes of data of a fixed |
|
100 | - // length. |
|
101 | - $overflow = \strlen($string) + $this->tell() - $this->remoteStream->tell(); |
|
102 | - if ($overflow > 0) { |
|
103 | - $this->skipReadBytes += $overflow; |
|
104 | - } |
|
105 | - return $this->stream->write($string); |
|
106 | - } |
|
107 | - public function eof() : bool |
|
108 | - { |
|
109 | - return $this->stream->eof() && $this->remoteStream->eof(); |
|
110 | - } |
|
111 | - /** |
|
112 | - * Close both the remote stream and buffer stream |
|
113 | - */ |
|
114 | - public function close() : void |
|
115 | - { |
|
116 | - $this->remoteStream->close(); |
|
117 | - $this->stream->close(); |
|
118 | - } |
|
119 | - private function cacheEntireStream() : int |
|
120 | - { |
|
121 | - $target = new FnStream(['write' => 'strlen']); |
|
122 | - Utils::copyToStream($this, $target); |
|
123 | - return $this->tell(); |
|
124 | - } |
|
13 | + use StreamDecoratorTrait; |
|
14 | + /** @var StreamInterface Stream being wrapped */ |
|
15 | + private $remoteStream; |
|
16 | + /** @var int Number of bytes to skip reading due to a write on the buffer */ |
|
17 | + private $skipReadBytes = 0; |
|
18 | + /** |
|
19 | + * @var StreamInterface |
|
20 | + */ |
|
21 | + private $stream; |
|
22 | + /** |
|
23 | + * We will treat the buffer object as the body of the stream |
|
24 | + * |
|
25 | + * @param StreamInterface $stream Stream to cache. The cursor is assumed to be at the beginning of the stream. |
|
26 | + * @param StreamInterface $target Optionally specify where data is cached |
|
27 | + */ |
|
28 | + public function __construct(StreamInterface $stream, ?StreamInterface $target = null) |
|
29 | + { |
|
30 | + $this->remoteStream = $stream; |
|
31 | + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); |
|
32 | + } |
|
33 | + public function getSize() : ?int |
|
34 | + { |
|
35 | + $remoteSize = $this->remoteStream->getSize(); |
|
36 | + if (null === $remoteSize) { |
|
37 | + return null; |
|
38 | + } |
|
39 | + return \max($this->stream->getSize(), $remoteSize); |
|
40 | + } |
|
41 | + public function rewind() : void |
|
42 | + { |
|
43 | + $this->seek(0); |
|
44 | + } |
|
45 | + public function seek($offset, $whence = \SEEK_SET) : void |
|
46 | + { |
|
47 | + if ($whence === \SEEK_SET) { |
|
48 | + $byte = $offset; |
|
49 | + } elseif ($whence === \SEEK_CUR) { |
|
50 | + $byte = $offset + $this->tell(); |
|
51 | + } elseif ($whence === \SEEK_END) { |
|
52 | + $size = $this->remoteStream->getSize(); |
|
53 | + if ($size === null) { |
|
54 | + $size = $this->cacheEntireStream(); |
|
55 | + } |
|
56 | + $byte = $size + $offset; |
|
57 | + } else { |
|
58 | + throw new \InvalidArgumentException('Invalid whence'); |
|
59 | + } |
|
60 | + $diff = $byte - $this->stream->getSize(); |
|
61 | + if ($diff > 0) { |
|
62 | + // Read the remoteStream until we have read in at least the amount |
|
63 | + // of bytes requested, or we reach the end of the file. |
|
64 | + while ($diff > 0 && !$this->remoteStream->eof()) { |
|
65 | + $this->read($diff); |
|
66 | + $diff = $byte - $this->stream->getSize(); |
|
67 | + } |
|
68 | + } else { |
|
69 | + // We can just do a normal seek since we've already seen this byte. |
|
70 | + $this->stream->seek($byte); |
|
71 | + } |
|
72 | + } |
|
73 | + public function read($length) : string |
|
74 | + { |
|
75 | + // Perform a regular read on any previously read data from the buffer |
|
76 | + $data = $this->stream->read($length); |
|
77 | + $remaining = $length - \strlen($data); |
|
78 | + // More data was requested so read from the remote stream |
|
79 | + if ($remaining) { |
|
80 | + // If data was written to the buffer in a position that would have |
|
81 | + // been filled from the remote stream, then we must skip bytes on |
|
82 | + // the remote stream to emulate overwriting bytes from that |
|
83 | + // position. This mimics the behavior of other PHP stream wrappers. |
|
84 | + $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes); |
|
85 | + if ($this->skipReadBytes) { |
|
86 | + $len = \strlen($remoteData); |
|
87 | + $remoteData = \substr($remoteData, $this->skipReadBytes); |
|
88 | + $this->skipReadBytes = \max(0, $this->skipReadBytes - $len); |
|
89 | + } |
|
90 | + $data .= $remoteData; |
|
91 | + $this->stream->write($remoteData); |
|
92 | + } |
|
93 | + return $data; |
|
94 | + } |
|
95 | + public function write($string) : int |
|
96 | + { |
|
97 | + // When appending to the end of the currently read stream, you'll want |
|
98 | + // to skip bytes from being read from the remote stream to emulate |
|
99 | + // other stream wrappers. Basically replacing bytes of data of a fixed |
|
100 | + // length. |
|
101 | + $overflow = \strlen($string) + $this->tell() - $this->remoteStream->tell(); |
|
102 | + if ($overflow > 0) { |
|
103 | + $this->skipReadBytes += $overflow; |
|
104 | + } |
|
105 | + return $this->stream->write($string); |
|
106 | + } |
|
107 | + public function eof() : bool |
|
108 | + { |
|
109 | + return $this->stream->eof() && $this->remoteStream->eof(); |
|
110 | + } |
|
111 | + /** |
|
112 | + * Close both the remote stream and buffer stream |
|
113 | + */ |
|
114 | + public function close() : void |
|
115 | + { |
|
116 | + $this->remoteStream->close(); |
|
117 | + $this->stream->close(); |
|
118 | + } |
|
119 | + private function cacheEntireStream() : int |
|
120 | + { |
|
121 | + $target = new FnStream(['write' => 'strlen']); |
|
122 | + Utils::copyToStream($this, $target); |
|
123 | + return $this->tell(); |
|
124 | + } |
|
125 | 125 | } |
@@ -10,121 +10,121 @@ |
||
10 | 10 | */ |
11 | 11 | final class MultipartStream implements StreamInterface |
12 | 12 | { |
13 | - use StreamDecoratorTrait; |
|
14 | - /** @var string */ |
|
15 | - private $boundary; |
|
16 | - /** @var StreamInterface */ |
|
17 | - private $stream; |
|
18 | - /** |
|
19 | - * @param array $elements Array of associative arrays, each containing a |
|
20 | - * required "name" key mapping to the form field, |
|
21 | - * name, a required "contents" key mapping to a |
|
22 | - * StreamInterface/resource/string, an optional |
|
23 | - * "headers" associative array of custom headers, |
|
24 | - * and an optional "filename" key mapping to a |
|
25 | - * string to send as the filename in the part. |
|
26 | - * @param string $boundary You can optionally provide a specific boundary |
|
27 | - * |
|
28 | - * @throws \InvalidArgumentException |
|
29 | - */ |
|
30 | - public function __construct(array $elements = [], ?string $boundary = null) |
|
31 | - { |
|
32 | - $this->boundary = $boundary ?: \bin2hex(\random_bytes(20)); |
|
33 | - $this->stream = $this->createStream($elements); |
|
34 | - } |
|
35 | - public function getBoundary() : string |
|
36 | - { |
|
37 | - return $this->boundary; |
|
38 | - } |
|
39 | - public function isWritable() : bool |
|
40 | - { |
|
41 | - return \false; |
|
42 | - } |
|
43 | - /** |
|
44 | - * Get the headers needed before transferring the content of a POST file |
|
45 | - * |
|
46 | - * @param string[] $headers |
|
47 | - */ |
|
48 | - private function getHeaders(array $headers) : string |
|
49 | - { |
|
50 | - $str = ''; |
|
51 | - foreach ($headers as $key => $value) { |
|
52 | - $str .= "{$key}: {$value}\r\n"; |
|
53 | - } |
|
54 | - return "--{$this->boundary}\r\n" . \trim($str) . "\r\n\r\n"; |
|
55 | - } |
|
56 | - /** |
|
57 | - * Create the aggregate stream that will be used to upload the POST data |
|
58 | - */ |
|
59 | - protected function createStream(array $elements = []) : StreamInterface |
|
60 | - { |
|
61 | - $stream = new AppendStream(); |
|
62 | - foreach ($elements as $element) { |
|
63 | - if (!\is_array($element)) { |
|
64 | - throw new \UnexpectedValueException('An array is expected'); |
|
65 | - } |
|
66 | - $this->addElement($stream, $element); |
|
67 | - } |
|
68 | - // Add the trailing boundary with CRLF |
|
69 | - $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); |
|
70 | - return $stream; |
|
71 | - } |
|
72 | - private function addElement(AppendStream $stream, array $element) : void |
|
73 | - { |
|
74 | - foreach (['contents', 'name'] as $key) { |
|
75 | - if (!\array_key_exists($key, $element)) { |
|
76 | - throw new \InvalidArgumentException("A '{$key}' key is required"); |
|
77 | - } |
|
78 | - } |
|
79 | - $element['contents'] = Utils::streamFor($element['contents']); |
|
80 | - if (empty($element['filename'])) { |
|
81 | - $uri = $element['contents']->getMetadata('uri'); |
|
82 | - if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { |
|
83 | - $element['filename'] = $uri; |
|
84 | - } |
|
85 | - } |
|
86 | - [$body, $headers] = $this->createElement($element['name'], $element['contents'], $element['filename'] ?? null, $element['headers'] ?? []); |
|
87 | - $stream->addStream(Utils::streamFor($this->getHeaders($headers))); |
|
88 | - $stream->addStream($body); |
|
89 | - $stream->addStream(Utils::streamFor("\r\n")); |
|
90 | - } |
|
91 | - /** |
|
92 | - * @param string[] $headers |
|
93 | - * |
|
94 | - * @return array{0: StreamInterface, 1: string[]} |
|
95 | - */ |
|
96 | - private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers) : array |
|
97 | - { |
|
98 | - // Set a default content-disposition header if one was no provided |
|
99 | - $disposition = self::getHeader($headers, 'content-disposition'); |
|
100 | - if (!$disposition) { |
|
101 | - $headers['Content-Disposition'] = $filename === '0' || $filename ? \sprintf('form-data; name="%s"; filename="%s"', $name, \basename($filename)) : "form-data; name=\"{$name}\""; |
|
102 | - } |
|
103 | - // Set a default content-length header if one was no provided |
|
104 | - $length = self::getHeader($headers, 'content-length'); |
|
105 | - if (!$length) { |
|
106 | - if ($length = $stream->getSize()) { |
|
107 | - $headers['Content-Length'] = (string) $length; |
|
108 | - } |
|
109 | - } |
|
110 | - // Set a default Content-Type if one was not supplied |
|
111 | - $type = self::getHeader($headers, 'content-type'); |
|
112 | - if (!$type && ($filename === '0' || $filename)) { |
|
113 | - $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; |
|
114 | - } |
|
115 | - return [$stream, $headers]; |
|
116 | - } |
|
117 | - /** |
|
118 | - * @param string[] $headers |
|
119 | - */ |
|
120 | - private static function getHeader(array $headers, string $key) : ?string |
|
121 | - { |
|
122 | - $lowercaseHeader = \strtolower($key); |
|
123 | - foreach ($headers as $k => $v) { |
|
124 | - if (\strtolower((string) $k) === $lowercaseHeader) { |
|
125 | - return $v; |
|
126 | - } |
|
127 | - } |
|
128 | - return null; |
|
129 | - } |
|
13 | + use StreamDecoratorTrait; |
|
14 | + /** @var string */ |
|
15 | + private $boundary; |
|
16 | + /** @var StreamInterface */ |
|
17 | + private $stream; |
|
18 | + /** |
|
19 | + * @param array $elements Array of associative arrays, each containing a |
|
20 | + * required "name" key mapping to the form field, |
|
21 | + * name, a required "contents" key mapping to a |
|
22 | + * StreamInterface/resource/string, an optional |
|
23 | + * "headers" associative array of custom headers, |
|
24 | + * and an optional "filename" key mapping to a |
|
25 | + * string to send as the filename in the part. |
|
26 | + * @param string $boundary You can optionally provide a specific boundary |
|
27 | + * |
|
28 | + * @throws \InvalidArgumentException |
|
29 | + */ |
|
30 | + public function __construct(array $elements = [], ?string $boundary = null) |
|
31 | + { |
|
32 | + $this->boundary = $boundary ?: \bin2hex(\random_bytes(20)); |
|
33 | + $this->stream = $this->createStream($elements); |
|
34 | + } |
|
35 | + public function getBoundary() : string |
|
36 | + { |
|
37 | + return $this->boundary; |
|
38 | + } |
|
39 | + public function isWritable() : bool |
|
40 | + { |
|
41 | + return \false; |
|
42 | + } |
|
43 | + /** |
|
44 | + * Get the headers needed before transferring the content of a POST file |
|
45 | + * |
|
46 | + * @param string[] $headers |
|
47 | + */ |
|
48 | + private function getHeaders(array $headers) : string |
|
49 | + { |
|
50 | + $str = ''; |
|
51 | + foreach ($headers as $key => $value) { |
|
52 | + $str .= "{$key}: {$value}\r\n"; |
|
53 | + } |
|
54 | + return "--{$this->boundary}\r\n" . \trim($str) . "\r\n\r\n"; |
|
55 | + } |
|
56 | + /** |
|
57 | + * Create the aggregate stream that will be used to upload the POST data |
|
58 | + */ |
|
59 | + protected function createStream(array $elements = []) : StreamInterface |
|
60 | + { |
|
61 | + $stream = new AppendStream(); |
|
62 | + foreach ($elements as $element) { |
|
63 | + if (!\is_array($element)) { |
|
64 | + throw new \UnexpectedValueException('An array is expected'); |
|
65 | + } |
|
66 | + $this->addElement($stream, $element); |
|
67 | + } |
|
68 | + // Add the trailing boundary with CRLF |
|
69 | + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); |
|
70 | + return $stream; |
|
71 | + } |
|
72 | + private function addElement(AppendStream $stream, array $element) : void |
|
73 | + { |
|
74 | + foreach (['contents', 'name'] as $key) { |
|
75 | + if (!\array_key_exists($key, $element)) { |
|
76 | + throw new \InvalidArgumentException("A '{$key}' key is required"); |
|
77 | + } |
|
78 | + } |
|
79 | + $element['contents'] = Utils::streamFor($element['contents']); |
|
80 | + if (empty($element['filename'])) { |
|
81 | + $uri = $element['contents']->getMetadata('uri'); |
|
82 | + if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { |
|
83 | + $element['filename'] = $uri; |
|
84 | + } |
|
85 | + } |
|
86 | + [$body, $headers] = $this->createElement($element['name'], $element['contents'], $element['filename'] ?? null, $element['headers'] ?? []); |
|
87 | + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); |
|
88 | + $stream->addStream($body); |
|
89 | + $stream->addStream(Utils::streamFor("\r\n")); |
|
90 | + } |
|
91 | + /** |
|
92 | + * @param string[] $headers |
|
93 | + * |
|
94 | + * @return array{0: StreamInterface, 1: string[]} |
|
95 | + */ |
|
96 | + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers) : array |
|
97 | + { |
|
98 | + // Set a default content-disposition header if one was no provided |
|
99 | + $disposition = self::getHeader($headers, 'content-disposition'); |
|
100 | + if (!$disposition) { |
|
101 | + $headers['Content-Disposition'] = $filename === '0' || $filename ? \sprintf('form-data; name="%s"; filename="%s"', $name, \basename($filename)) : "form-data; name=\"{$name}\""; |
|
102 | + } |
|
103 | + // Set a default content-length header if one was no provided |
|
104 | + $length = self::getHeader($headers, 'content-length'); |
|
105 | + if (!$length) { |
|
106 | + if ($length = $stream->getSize()) { |
|
107 | + $headers['Content-Length'] = (string) $length; |
|
108 | + } |
|
109 | + } |
|
110 | + // Set a default Content-Type if one was not supplied |
|
111 | + $type = self::getHeader($headers, 'content-type'); |
|
112 | + if (!$type && ($filename === '0' || $filename)) { |
|
113 | + $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; |
|
114 | + } |
|
115 | + return [$stream, $headers]; |
|
116 | + } |
|
117 | + /** |
|
118 | + * @param string[] $headers |
|
119 | + */ |
|
120 | + private static function getHeader(array $headers, string $key) : ?string |
|
121 | + { |
|
122 | + $lowercaseHeader = \strtolower($key); |
|
123 | + foreach ($headers as $k => $v) { |
|
124 | + if (\strtolower((string) $k) === $lowercaseHeader) { |
|
125 | + return $v; |
|
126 | + } |
|
127 | + } |
|
128 | + return null; |
|
129 | + } |
|
130 | 130 | } |
@@ -23,54 +23,54 @@ |
||
23 | 23 | */ |
24 | 24 | final class HttpFactory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface |
25 | 25 | { |
26 | - public function createUploadedFile(StreamInterface $stream, ?int $size = null, int $error = \UPLOAD_ERR_OK, ?string $clientFilename = null, ?string $clientMediaType = null) : UploadedFileInterface |
|
27 | - { |
|
28 | - if ($size === null) { |
|
29 | - $size = $stream->getSize(); |
|
30 | - } |
|
31 | - return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); |
|
32 | - } |
|
33 | - public function createStream(string $content = '') : StreamInterface |
|
34 | - { |
|
35 | - return Utils::streamFor($content); |
|
36 | - } |
|
37 | - public function createStreamFromFile(string $file, string $mode = 'r') : StreamInterface |
|
38 | - { |
|
39 | - try { |
|
40 | - $resource = Utils::tryFopen($file, $mode); |
|
41 | - } catch (\RuntimeException $e) { |
|
42 | - if ('' === $mode || \false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], \true)) { |
|
43 | - throw new \InvalidArgumentException(\sprintf('Invalid file opening mode "%s"', $mode), 0, $e); |
|
44 | - } |
|
45 | - throw $e; |
|
46 | - } |
|
47 | - return Utils::streamFor($resource); |
|
48 | - } |
|
49 | - public function createStreamFromResource($resource) : StreamInterface |
|
50 | - { |
|
51 | - return Utils::streamFor($resource); |
|
52 | - } |
|
53 | - public function createServerRequest(string $method, $uri, array $serverParams = []) : ServerRequestInterface |
|
54 | - { |
|
55 | - if (empty($method)) { |
|
56 | - if (!empty($serverParams['REQUEST_METHOD'])) { |
|
57 | - $method = $serverParams['REQUEST_METHOD']; |
|
58 | - } else { |
|
59 | - throw new \InvalidArgumentException('Cannot determine HTTP method'); |
|
60 | - } |
|
61 | - } |
|
62 | - return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); |
|
63 | - } |
|
64 | - public function createResponse(int $code = 200, string $reasonPhrase = '') : ResponseInterface |
|
65 | - { |
|
66 | - return new Response($code, [], null, '1.1', $reasonPhrase); |
|
67 | - } |
|
68 | - public function createRequest(string $method, $uri) : RequestInterface |
|
69 | - { |
|
70 | - return new Request($method, $uri); |
|
71 | - } |
|
72 | - public function createUri(string $uri = '') : UriInterface |
|
73 | - { |
|
74 | - return new Uri($uri); |
|
75 | - } |
|
26 | + public function createUploadedFile(StreamInterface $stream, ?int $size = null, int $error = \UPLOAD_ERR_OK, ?string $clientFilename = null, ?string $clientMediaType = null) : UploadedFileInterface |
|
27 | + { |
|
28 | + if ($size === null) { |
|
29 | + $size = $stream->getSize(); |
|
30 | + } |
|
31 | + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); |
|
32 | + } |
|
33 | + public function createStream(string $content = '') : StreamInterface |
|
34 | + { |
|
35 | + return Utils::streamFor($content); |
|
36 | + } |
|
37 | + public function createStreamFromFile(string $file, string $mode = 'r') : StreamInterface |
|
38 | + { |
|
39 | + try { |
|
40 | + $resource = Utils::tryFopen($file, $mode); |
|
41 | + } catch (\RuntimeException $e) { |
|
42 | + if ('' === $mode || \false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], \true)) { |
|
43 | + throw new \InvalidArgumentException(\sprintf('Invalid file opening mode "%s"', $mode), 0, $e); |
|
44 | + } |
|
45 | + throw $e; |
|
46 | + } |
|
47 | + return Utils::streamFor($resource); |
|
48 | + } |
|
49 | + public function createStreamFromResource($resource) : StreamInterface |
|
50 | + { |
|
51 | + return Utils::streamFor($resource); |
|
52 | + } |
|
53 | + public function createServerRequest(string $method, $uri, array $serverParams = []) : ServerRequestInterface |
|
54 | + { |
|
55 | + if (empty($method)) { |
|
56 | + if (!empty($serverParams['REQUEST_METHOD'])) { |
|
57 | + $method = $serverParams['REQUEST_METHOD']; |
|
58 | + } else { |
|
59 | + throw new \InvalidArgumentException('Cannot determine HTTP method'); |
|
60 | + } |
|
61 | + } |
|
62 | + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); |
|
63 | + } |
|
64 | + public function createResponse(int $code = 200, string $reasonPhrase = '') : ResponseInterface |
|
65 | + { |
|
66 | + return new Response($code, [], null, '1.1', $reasonPhrase); |
|
67 | + } |
|
68 | + public function createRequest(string $method, $uri) : RequestInterface |
|
69 | + { |
|
70 | + return new Request($method, $uri); |
|
71 | + } |
|
72 | + public function createUri(string $uri = '') : UriInterface |
|
73 | + { |
|
74 | + return new Uri($uri); |
|
75 | + } |
|
76 | 76 | } |
@@ -14,559 +14,559 @@ |
||
14 | 14 | */ |
15 | 15 | class Uri implements UriInterface, \JsonSerializable |
16 | 16 | { |
17 | - /** |
|
18 | - * Absolute http and https URIs require a host per RFC 7230 Section 2.7 |
|
19 | - * but in generic URIs the host can be empty. So for http(s) URIs |
|
20 | - * we apply this default host when no host is given yet to form a |
|
21 | - * valid URI. |
|
22 | - */ |
|
23 | - private const HTTP_DEFAULT_HOST = 'localhost'; |
|
24 | - private const DEFAULT_PORTS = ['http' => 80, 'https' => 443, 'ftp' => 21, 'gopher' => 70, 'nntp' => 119, 'news' => 119, 'telnet' => 23, 'tn3270' => 23, 'imap' => 143, 'pop' => 110, 'ldap' => 389]; |
|
25 | - /** |
|
26 | - * Unreserved characters for use in a regex. |
|
27 | - * |
|
28 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.3 |
|
29 | - */ |
|
30 | - private const CHAR_UNRESERVED = 'a-zA-Z0-9_\\-\\.~'; |
|
31 | - /** |
|
32 | - * Sub-delims for use in a regex. |
|
33 | - * |
|
34 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 |
|
35 | - */ |
|
36 | - private const CHAR_SUB_DELIMS = '!\\$&\'\\(\\)\\*\\+,;='; |
|
37 | - private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; |
|
38 | - /** @var string Uri scheme. */ |
|
39 | - private $scheme = ''; |
|
40 | - /** @var string Uri user info. */ |
|
41 | - private $userInfo = ''; |
|
42 | - /** @var string Uri host. */ |
|
43 | - private $host = ''; |
|
44 | - /** @var int|null Uri port. */ |
|
45 | - private $port; |
|
46 | - /** @var string Uri path. */ |
|
47 | - private $path = ''; |
|
48 | - /** @var string Uri query string. */ |
|
49 | - private $query = ''; |
|
50 | - /** @var string Uri fragment. */ |
|
51 | - private $fragment = ''; |
|
52 | - /** @var string|null String representation */ |
|
53 | - private $composedComponents; |
|
54 | - public function __construct(string $uri = '') |
|
55 | - { |
|
56 | - if ($uri !== '') { |
|
57 | - $parts = self::parse($uri); |
|
58 | - if ($parts === \false) { |
|
59 | - throw new MalformedUriException("Unable to parse URI: {$uri}"); |
|
60 | - } |
|
61 | - $this->applyParts($parts); |
|
62 | - } |
|
63 | - } |
|
64 | - /** |
|
65 | - * UTF-8 aware \parse_url() replacement. |
|
66 | - * |
|
67 | - * The internal function produces broken output for non ASCII domain names |
|
68 | - * (IDN) when used with locales other than "C". |
|
69 | - * |
|
70 | - * On the other hand, cURL understands IDN correctly only when UTF-8 locale |
|
71 | - * is configured ("C.UTF-8", "en_US.UTF-8", etc.). |
|
72 | - * |
|
73 | - * @see https://bugs.php.net/bug.php?id=52923 |
|
74 | - * @see https://www.php.net/manual/en/function.parse-url.php#114817 |
|
75 | - * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING |
|
76 | - * |
|
77 | - * @return array|false |
|
78 | - */ |
|
79 | - private static function parse(string $url) |
|
80 | - { |
|
81 | - // If IPv6 |
|
82 | - $prefix = ''; |
|
83 | - if (\preg_match('%^(.*://\\[[0-9:a-f]+\\])(.*?)$%', $url, $matches)) { |
|
84 | - /** @var array{0:string, 1:string, 2:string} $matches */ |
|
85 | - $prefix = $matches[1]; |
|
86 | - $url = $matches[2]; |
|
87 | - } |
|
88 | - /** @var string */ |
|
89 | - $encodedUrl = \preg_replace_callback('%[^:/@?&=#]+%usD', static function ($matches) { |
|
90 | - return \urlencode($matches[0]); |
|
91 | - }, $url); |
|
92 | - $result = \parse_url($prefix . $encodedUrl); |
|
93 | - if ($result === \false) { |
|
94 | - return \false; |
|
95 | - } |
|
96 | - return \array_map('urldecode', $result); |
|
97 | - } |
|
98 | - public function __toString() : string |
|
99 | - { |
|
100 | - if ($this->composedComponents === null) { |
|
101 | - $this->composedComponents = self::composeComponents($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment); |
|
102 | - } |
|
103 | - return $this->composedComponents; |
|
104 | - } |
|
105 | - /** |
|
106 | - * Composes a URI reference string from its various components. |
|
107 | - * |
|
108 | - * Usually this method does not need to be called manually but instead is used indirectly via |
|
109 | - * `Psr\Http\Message\UriInterface::__toString`. |
|
110 | - * |
|
111 | - * PSR-7 UriInterface treats an empty component the same as a missing component as |
|
112 | - * getQuery(), getFragment() etc. always return a string. This explains the slight |
|
113 | - * difference to RFC 3986 Section 5.3. |
|
114 | - * |
|
115 | - * Another adjustment is that the authority separator is added even when the authority is missing/empty |
|
116 | - * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with |
|
117 | - * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But |
|
118 | - * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to |
|
119 | - * that format). |
|
120 | - * |
|
121 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3 |
|
122 | - */ |
|
123 | - public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment) : string |
|
124 | - { |
|
125 | - $uri = ''; |
|
126 | - // weak type checks to also accept null until we can add scalar type hints |
|
127 | - if ($scheme != '') { |
|
128 | - $uri .= $scheme . ':'; |
|
129 | - } |
|
130 | - if ($authority != '' || $scheme === 'file') { |
|
131 | - $uri .= '//' . $authority; |
|
132 | - } |
|
133 | - if ($authority != '' && $path != '' && $path[0] != '/') { |
|
134 | - $path = '/' . $path; |
|
135 | - } |
|
136 | - $uri .= $path; |
|
137 | - if ($query != '') { |
|
138 | - $uri .= '?' . $query; |
|
139 | - } |
|
140 | - if ($fragment != '') { |
|
141 | - $uri .= '#' . $fragment; |
|
142 | - } |
|
143 | - return $uri; |
|
144 | - } |
|
145 | - /** |
|
146 | - * Whether the URI has the default port of the current scheme. |
|
147 | - * |
|
148 | - * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used |
|
149 | - * independently of the implementation. |
|
150 | - */ |
|
151 | - public static function isDefaultPort(UriInterface $uri) : bool |
|
152 | - { |
|
153 | - return $uri->getPort() === null || isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]; |
|
154 | - } |
|
155 | - /** |
|
156 | - * Whether the URI is absolute, i.e. it has a scheme. |
|
157 | - * |
|
158 | - * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true |
|
159 | - * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative |
|
160 | - * to another URI, the base URI. Relative references can be divided into several forms: |
|
161 | - * - network-path references, e.g. '//example.com/path' |
|
162 | - * - absolute-path references, e.g. '/path' |
|
163 | - * - relative-path references, e.g. 'subpath' |
|
164 | - * |
|
165 | - * @see Uri::isNetworkPathReference |
|
166 | - * @see Uri::isAbsolutePathReference |
|
167 | - * @see Uri::isRelativePathReference |
|
168 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4 |
|
169 | - */ |
|
170 | - public static function isAbsolute(UriInterface $uri) : bool |
|
171 | - { |
|
172 | - return $uri->getScheme() !== ''; |
|
173 | - } |
|
174 | - /** |
|
175 | - * Whether the URI is a network-path reference. |
|
176 | - * |
|
177 | - * A relative reference that begins with two slash characters is termed an network-path reference. |
|
178 | - * |
|
179 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
180 | - */ |
|
181 | - public static function isNetworkPathReference(UriInterface $uri) : bool |
|
182 | - { |
|
183 | - return $uri->getScheme() === '' && $uri->getAuthority() !== ''; |
|
184 | - } |
|
185 | - /** |
|
186 | - * Whether the URI is a absolute-path reference. |
|
187 | - * |
|
188 | - * A relative reference that begins with a single slash character is termed an absolute-path reference. |
|
189 | - * |
|
190 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
191 | - */ |
|
192 | - public static function isAbsolutePathReference(UriInterface $uri) : bool |
|
193 | - { |
|
194 | - return $uri->getScheme() === '' && $uri->getAuthority() === '' && isset($uri->getPath()[0]) && $uri->getPath()[0] === '/'; |
|
195 | - } |
|
196 | - /** |
|
197 | - * Whether the URI is a relative-path reference. |
|
198 | - * |
|
199 | - * A relative reference that does not begin with a slash character is termed a relative-path reference. |
|
200 | - * |
|
201 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
202 | - */ |
|
203 | - public static function isRelativePathReference(UriInterface $uri) : bool |
|
204 | - { |
|
205 | - return $uri->getScheme() === '' && $uri->getAuthority() === '' && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); |
|
206 | - } |
|
207 | - /** |
|
208 | - * Whether the URI is a same-document reference. |
|
209 | - * |
|
210 | - * A same-document reference refers to a URI that is, aside from its fragment |
|
211 | - * component, identical to the base URI. When no base URI is given, only an empty |
|
212 | - * URI reference (apart from its fragment) is considered a same-document reference. |
|
213 | - * |
|
214 | - * @param UriInterface $uri The URI to check |
|
215 | - * @param UriInterface|null $base An optional base URI to compare against |
|
216 | - * |
|
217 | - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4 |
|
218 | - */ |
|
219 | - public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null) : bool |
|
220 | - { |
|
221 | - if ($base !== null) { |
|
222 | - $uri = UriResolver::resolve($base, $uri); |
|
223 | - return $uri->getScheme() === $base->getScheme() && $uri->getAuthority() === $base->getAuthority() && $uri->getPath() === $base->getPath() && $uri->getQuery() === $base->getQuery(); |
|
224 | - } |
|
225 | - return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; |
|
226 | - } |
|
227 | - /** |
|
228 | - * Creates a new URI with a specific query string value removed. |
|
229 | - * |
|
230 | - * Any existing query string values that exactly match the provided key are |
|
231 | - * removed. |
|
232 | - * |
|
233 | - * @param UriInterface $uri URI to use as a base. |
|
234 | - * @param string $key Query string key to remove. |
|
235 | - */ |
|
236 | - public static function withoutQueryValue(UriInterface $uri, string $key) : UriInterface |
|
237 | - { |
|
238 | - $result = self::getFilteredQueryString($uri, [$key]); |
|
239 | - return $uri->withQuery(\implode('&', $result)); |
|
240 | - } |
|
241 | - /** |
|
242 | - * Creates a new URI with a specific query string value. |
|
243 | - * |
|
244 | - * Any existing query string values that exactly match the provided key are |
|
245 | - * removed and replaced with the given key value pair. |
|
246 | - * |
|
247 | - * A value of null will set the query string key without a value, e.g. "key" |
|
248 | - * instead of "key=value". |
|
249 | - * |
|
250 | - * @param UriInterface $uri URI to use as a base. |
|
251 | - * @param string $key Key to set. |
|
252 | - * @param string|null $value Value to set |
|
253 | - */ |
|
254 | - public static function withQueryValue(UriInterface $uri, string $key, ?string $value) : UriInterface |
|
255 | - { |
|
256 | - $result = self::getFilteredQueryString($uri, [$key]); |
|
257 | - $result[] = self::generateQueryString($key, $value); |
|
258 | - return $uri->withQuery(\implode('&', $result)); |
|
259 | - } |
|
260 | - /** |
|
261 | - * Creates a new URI with multiple specific query string values. |
|
262 | - * |
|
263 | - * It has the same behavior as withQueryValue() but for an associative array of key => value. |
|
264 | - * |
|
265 | - * @param UriInterface $uri URI to use as a base. |
|
266 | - * @param (string|null)[] $keyValueArray Associative array of key and values |
|
267 | - */ |
|
268 | - public static function withQueryValues(UriInterface $uri, array $keyValueArray) : UriInterface |
|
269 | - { |
|
270 | - $result = self::getFilteredQueryString($uri, \array_keys($keyValueArray)); |
|
271 | - foreach ($keyValueArray as $key => $value) { |
|
272 | - $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); |
|
273 | - } |
|
274 | - return $uri->withQuery(\implode('&', $result)); |
|
275 | - } |
|
276 | - /** |
|
277 | - * Creates a URI from a hash of `parse_url` components. |
|
278 | - * |
|
279 | - * @see https://www.php.net/manual/en/function.parse-url.php |
|
280 | - * |
|
281 | - * @throws MalformedUriException If the components do not form a valid URI. |
|
282 | - */ |
|
283 | - public static function fromParts(array $parts) : UriInterface |
|
284 | - { |
|
285 | - $uri = new self(); |
|
286 | - $uri->applyParts($parts); |
|
287 | - $uri->validateState(); |
|
288 | - return $uri; |
|
289 | - } |
|
290 | - public function getScheme() : string |
|
291 | - { |
|
292 | - return $this->scheme; |
|
293 | - } |
|
294 | - public function getAuthority() : string |
|
295 | - { |
|
296 | - $authority = $this->host; |
|
297 | - if ($this->userInfo !== '') { |
|
298 | - $authority = $this->userInfo . '@' . $authority; |
|
299 | - } |
|
300 | - if ($this->port !== null) { |
|
301 | - $authority .= ':' . $this->port; |
|
302 | - } |
|
303 | - return $authority; |
|
304 | - } |
|
305 | - public function getUserInfo() : string |
|
306 | - { |
|
307 | - return $this->userInfo; |
|
308 | - } |
|
309 | - public function getHost() : string |
|
310 | - { |
|
311 | - return $this->host; |
|
312 | - } |
|
313 | - public function getPort() : ?int |
|
314 | - { |
|
315 | - return $this->port; |
|
316 | - } |
|
317 | - public function getPath() : string |
|
318 | - { |
|
319 | - return $this->path; |
|
320 | - } |
|
321 | - public function getQuery() : string |
|
322 | - { |
|
323 | - return $this->query; |
|
324 | - } |
|
325 | - public function getFragment() : string |
|
326 | - { |
|
327 | - return $this->fragment; |
|
328 | - } |
|
329 | - public function withScheme($scheme) : UriInterface |
|
330 | - { |
|
331 | - $scheme = $this->filterScheme($scheme); |
|
332 | - if ($this->scheme === $scheme) { |
|
333 | - return $this; |
|
334 | - } |
|
335 | - $new = clone $this; |
|
336 | - $new->scheme = $scheme; |
|
337 | - $new->composedComponents = null; |
|
338 | - $new->removeDefaultPort(); |
|
339 | - $new->validateState(); |
|
340 | - return $new; |
|
341 | - } |
|
342 | - public function withUserInfo($user, $password = null) : UriInterface |
|
343 | - { |
|
344 | - $info = $this->filterUserInfoComponent($user); |
|
345 | - if ($password !== null) { |
|
346 | - $info .= ':' . $this->filterUserInfoComponent($password); |
|
347 | - } |
|
348 | - if ($this->userInfo === $info) { |
|
349 | - return $this; |
|
350 | - } |
|
351 | - $new = clone $this; |
|
352 | - $new->userInfo = $info; |
|
353 | - $new->composedComponents = null; |
|
354 | - $new->validateState(); |
|
355 | - return $new; |
|
356 | - } |
|
357 | - public function withHost($host) : UriInterface |
|
358 | - { |
|
359 | - $host = $this->filterHost($host); |
|
360 | - if ($this->host === $host) { |
|
361 | - return $this; |
|
362 | - } |
|
363 | - $new = clone $this; |
|
364 | - $new->host = $host; |
|
365 | - $new->composedComponents = null; |
|
366 | - $new->validateState(); |
|
367 | - return $new; |
|
368 | - } |
|
369 | - public function withPort($port) : UriInterface |
|
370 | - { |
|
371 | - $port = $this->filterPort($port); |
|
372 | - if ($this->port === $port) { |
|
373 | - return $this; |
|
374 | - } |
|
375 | - $new = clone $this; |
|
376 | - $new->port = $port; |
|
377 | - $new->composedComponents = null; |
|
378 | - $new->removeDefaultPort(); |
|
379 | - $new->validateState(); |
|
380 | - return $new; |
|
381 | - } |
|
382 | - public function withPath($path) : UriInterface |
|
383 | - { |
|
384 | - $path = $this->filterPath($path); |
|
385 | - if ($this->path === $path) { |
|
386 | - return $this; |
|
387 | - } |
|
388 | - $new = clone $this; |
|
389 | - $new->path = $path; |
|
390 | - $new->composedComponents = null; |
|
391 | - $new->validateState(); |
|
392 | - return $new; |
|
393 | - } |
|
394 | - public function withQuery($query) : UriInterface |
|
395 | - { |
|
396 | - $query = $this->filterQueryAndFragment($query); |
|
397 | - if ($this->query === $query) { |
|
398 | - return $this; |
|
399 | - } |
|
400 | - $new = clone $this; |
|
401 | - $new->query = $query; |
|
402 | - $new->composedComponents = null; |
|
403 | - return $new; |
|
404 | - } |
|
405 | - public function withFragment($fragment) : UriInterface |
|
406 | - { |
|
407 | - $fragment = $this->filterQueryAndFragment($fragment); |
|
408 | - if ($this->fragment === $fragment) { |
|
409 | - return $this; |
|
410 | - } |
|
411 | - $new = clone $this; |
|
412 | - $new->fragment = $fragment; |
|
413 | - $new->composedComponents = null; |
|
414 | - return $new; |
|
415 | - } |
|
416 | - public function jsonSerialize() : string |
|
417 | - { |
|
418 | - return $this->__toString(); |
|
419 | - } |
|
420 | - /** |
|
421 | - * Apply parse_url parts to a URI. |
|
422 | - * |
|
423 | - * @param array $parts Array of parse_url parts to apply. |
|
424 | - */ |
|
425 | - private function applyParts(array $parts) : void |
|
426 | - { |
|
427 | - $this->scheme = isset($parts['scheme']) ? $this->filterScheme($parts['scheme']) : ''; |
|
428 | - $this->userInfo = isset($parts['user']) ? $this->filterUserInfoComponent($parts['user']) : ''; |
|
429 | - $this->host = isset($parts['host']) ? $this->filterHost($parts['host']) : ''; |
|
430 | - $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null; |
|
431 | - $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : ''; |
|
432 | - $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : ''; |
|
433 | - $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : ''; |
|
434 | - if (isset($parts['pass'])) { |
|
435 | - $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); |
|
436 | - } |
|
437 | - $this->removeDefaultPort(); |
|
438 | - } |
|
439 | - /** |
|
440 | - * @param mixed $scheme |
|
441 | - * |
|
442 | - * @throws \InvalidArgumentException If the scheme is invalid. |
|
443 | - */ |
|
444 | - private function filterScheme($scheme) : string |
|
445 | - { |
|
446 | - if (!\is_string($scheme)) { |
|
447 | - throw new \InvalidArgumentException('Scheme must be a string'); |
|
448 | - } |
|
449 | - return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); |
|
450 | - } |
|
451 | - /** |
|
452 | - * @param mixed $component |
|
453 | - * |
|
454 | - * @throws \InvalidArgumentException If the user info is invalid. |
|
455 | - */ |
|
456 | - private function filterUserInfoComponent($component) : string |
|
457 | - { |
|
458 | - if (!\is_string($component)) { |
|
459 | - throw new \InvalidArgumentException('User info must be a string'); |
|
460 | - } |
|
461 | - return \preg_replace_callback('/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $component); |
|
462 | - } |
|
463 | - /** |
|
464 | - * @param mixed $host |
|
465 | - * |
|
466 | - * @throws \InvalidArgumentException If the host is invalid. |
|
467 | - */ |
|
468 | - private function filterHost($host) : string |
|
469 | - { |
|
470 | - if (!\is_string($host)) { |
|
471 | - throw new \InvalidArgumentException('Host must be a string'); |
|
472 | - } |
|
473 | - return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); |
|
474 | - } |
|
475 | - /** |
|
476 | - * @param mixed $port |
|
477 | - * |
|
478 | - * @throws \InvalidArgumentException If the port is invalid. |
|
479 | - */ |
|
480 | - private function filterPort($port) : ?int |
|
481 | - { |
|
482 | - if ($port === null) { |
|
483 | - return null; |
|
484 | - } |
|
485 | - $port = (int) $port; |
|
486 | - if (0 > $port || 0xffff < $port) { |
|
487 | - throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port)); |
|
488 | - } |
|
489 | - return $port; |
|
490 | - } |
|
491 | - /** |
|
492 | - * @param (string|int)[] $keys |
|
493 | - * |
|
494 | - * @return string[] |
|
495 | - */ |
|
496 | - private static function getFilteredQueryString(UriInterface $uri, array $keys) : array |
|
497 | - { |
|
498 | - $current = $uri->getQuery(); |
|
499 | - if ($current === '') { |
|
500 | - return []; |
|
501 | - } |
|
502 | - $decodedKeys = \array_map(function ($k) : string { |
|
503 | - return \rawurldecode((string) $k); |
|
504 | - }, $keys); |
|
505 | - return \array_filter(\explode('&', $current), function ($part) use($decodedKeys) { |
|
506 | - return !\in_array(\rawurldecode(\explode('=', $part)[0]), $decodedKeys, \true); |
|
507 | - }); |
|
508 | - } |
|
509 | - private static function generateQueryString(string $key, ?string $value) : string |
|
510 | - { |
|
511 | - // Query string separators ("=", "&") within the key or value need to be encoded |
|
512 | - // (while preventing double-encoding) before setting the query string. All other |
|
513 | - // chars that need percent-encoding will be encoded by withQuery(). |
|
514 | - $queryString = \strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); |
|
515 | - if ($value !== null) { |
|
516 | - $queryString .= '=' . \strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); |
|
517 | - } |
|
518 | - return $queryString; |
|
519 | - } |
|
520 | - private function removeDefaultPort() : void |
|
521 | - { |
|
522 | - if ($this->port !== null && self::isDefaultPort($this)) { |
|
523 | - $this->port = null; |
|
524 | - } |
|
525 | - } |
|
526 | - /** |
|
527 | - * Filters the path of a URI |
|
528 | - * |
|
529 | - * @param mixed $path |
|
530 | - * |
|
531 | - * @throws \InvalidArgumentException If the path is invalid. |
|
532 | - */ |
|
533 | - private function filterPath($path) : string |
|
534 | - { |
|
535 | - if (!\is_string($path)) { |
|
536 | - throw new \InvalidArgumentException('Path must be a string'); |
|
537 | - } |
|
538 | - return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\\/]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $path); |
|
539 | - } |
|
540 | - /** |
|
541 | - * Filters the query string or fragment of a URI. |
|
542 | - * |
|
543 | - * @param mixed $str |
|
544 | - * |
|
545 | - * @throws \InvalidArgumentException If the query or fragment is invalid. |
|
546 | - */ |
|
547 | - private function filterQueryAndFragment($str) : string |
|
548 | - { |
|
549 | - if (!\is_string($str)) { |
|
550 | - throw new \InvalidArgumentException('Query and fragment must be a string'); |
|
551 | - } |
|
552 | - return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\\/\\?]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $str); |
|
553 | - } |
|
554 | - private function rawurlencodeMatchZero(array $match) : string |
|
555 | - { |
|
556 | - return \rawurlencode($match[0]); |
|
557 | - } |
|
558 | - private function validateState() : void |
|
559 | - { |
|
560 | - if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { |
|
561 | - $this->host = self::HTTP_DEFAULT_HOST; |
|
562 | - } |
|
563 | - if ($this->getAuthority() === '') { |
|
564 | - if (0 === \strpos($this->path, '//')) { |
|
565 | - throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); |
|
566 | - } |
|
567 | - if ($this->scheme === '' && \false !== \strpos(\explode('/', $this->path, 2)[0], ':')) { |
|
568 | - throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); |
|
569 | - } |
|
570 | - } |
|
571 | - } |
|
17 | + /** |
|
18 | + * Absolute http and https URIs require a host per RFC 7230 Section 2.7 |
|
19 | + * but in generic URIs the host can be empty. So for http(s) URIs |
|
20 | + * we apply this default host when no host is given yet to form a |
|
21 | + * valid URI. |
|
22 | + */ |
|
23 | + private const HTTP_DEFAULT_HOST = 'localhost'; |
|
24 | + private const DEFAULT_PORTS = ['http' => 80, 'https' => 443, 'ftp' => 21, 'gopher' => 70, 'nntp' => 119, 'news' => 119, 'telnet' => 23, 'tn3270' => 23, 'imap' => 143, 'pop' => 110, 'ldap' => 389]; |
|
25 | + /** |
|
26 | + * Unreserved characters for use in a regex. |
|
27 | + * |
|
28 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.3 |
|
29 | + */ |
|
30 | + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\\-\\.~'; |
|
31 | + /** |
|
32 | + * Sub-delims for use in a regex. |
|
33 | + * |
|
34 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 |
|
35 | + */ |
|
36 | + private const CHAR_SUB_DELIMS = '!\\$&\'\\(\\)\\*\\+,;='; |
|
37 | + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; |
|
38 | + /** @var string Uri scheme. */ |
|
39 | + private $scheme = ''; |
|
40 | + /** @var string Uri user info. */ |
|
41 | + private $userInfo = ''; |
|
42 | + /** @var string Uri host. */ |
|
43 | + private $host = ''; |
|
44 | + /** @var int|null Uri port. */ |
|
45 | + private $port; |
|
46 | + /** @var string Uri path. */ |
|
47 | + private $path = ''; |
|
48 | + /** @var string Uri query string. */ |
|
49 | + private $query = ''; |
|
50 | + /** @var string Uri fragment. */ |
|
51 | + private $fragment = ''; |
|
52 | + /** @var string|null String representation */ |
|
53 | + private $composedComponents; |
|
54 | + public function __construct(string $uri = '') |
|
55 | + { |
|
56 | + if ($uri !== '') { |
|
57 | + $parts = self::parse($uri); |
|
58 | + if ($parts === \false) { |
|
59 | + throw new MalformedUriException("Unable to parse URI: {$uri}"); |
|
60 | + } |
|
61 | + $this->applyParts($parts); |
|
62 | + } |
|
63 | + } |
|
64 | + /** |
|
65 | + * UTF-8 aware \parse_url() replacement. |
|
66 | + * |
|
67 | + * The internal function produces broken output for non ASCII domain names |
|
68 | + * (IDN) when used with locales other than "C". |
|
69 | + * |
|
70 | + * On the other hand, cURL understands IDN correctly only when UTF-8 locale |
|
71 | + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). |
|
72 | + * |
|
73 | + * @see https://bugs.php.net/bug.php?id=52923 |
|
74 | + * @see https://www.php.net/manual/en/function.parse-url.php#114817 |
|
75 | + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING |
|
76 | + * |
|
77 | + * @return array|false |
|
78 | + */ |
|
79 | + private static function parse(string $url) |
|
80 | + { |
|
81 | + // If IPv6 |
|
82 | + $prefix = ''; |
|
83 | + if (\preg_match('%^(.*://\\[[0-9:a-f]+\\])(.*?)$%', $url, $matches)) { |
|
84 | + /** @var array{0:string, 1:string, 2:string} $matches */ |
|
85 | + $prefix = $matches[1]; |
|
86 | + $url = $matches[2]; |
|
87 | + } |
|
88 | + /** @var string */ |
|
89 | + $encodedUrl = \preg_replace_callback('%[^:/@?&=#]+%usD', static function ($matches) { |
|
90 | + return \urlencode($matches[0]); |
|
91 | + }, $url); |
|
92 | + $result = \parse_url($prefix . $encodedUrl); |
|
93 | + if ($result === \false) { |
|
94 | + return \false; |
|
95 | + } |
|
96 | + return \array_map('urldecode', $result); |
|
97 | + } |
|
98 | + public function __toString() : string |
|
99 | + { |
|
100 | + if ($this->composedComponents === null) { |
|
101 | + $this->composedComponents = self::composeComponents($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment); |
|
102 | + } |
|
103 | + return $this->composedComponents; |
|
104 | + } |
|
105 | + /** |
|
106 | + * Composes a URI reference string from its various components. |
|
107 | + * |
|
108 | + * Usually this method does not need to be called manually but instead is used indirectly via |
|
109 | + * `Psr\Http\Message\UriInterface::__toString`. |
|
110 | + * |
|
111 | + * PSR-7 UriInterface treats an empty component the same as a missing component as |
|
112 | + * getQuery(), getFragment() etc. always return a string. This explains the slight |
|
113 | + * difference to RFC 3986 Section 5.3. |
|
114 | + * |
|
115 | + * Another adjustment is that the authority separator is added even when the authority is missing/empty |
|
116 | + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with |
|
117 | + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But |
|
118 | + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to |
|
119 | + * that format). |
|
120 | + * |
|
121 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3 |
|
122 | + */ |
|
123 | + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment) : string |
|
124 | + { |
|
125 | + $uri = ''; |
|
126 | + // weak type checks to also accept null until we can add scalar type hints |
|
127 | + if ($scheme != '') { |
|
128 | + $uri .= $scheme . ':'; |
|
129 | + } |
|
130 | + if ($authority != '' || $scheme === 'file') { |
|
131 | + $uri .= '//' . $authority; |
|
132 | + } |
|
133 | + if ($authority != '' && $path != '' && $path[0] != '/') { |
|
134 | + $path = '/' . $path; |
|
135 | + } |
|
136 | + $uri .= $path; |
|
137 | + if ($query != '') { |
|
138 | + $uri .= '?' . $query; |
|
139 | + } |
|
140 | + if ($fragment != '') { |
|
141 | + $uri .= '#' . $fragment; |
|
142 | + } |
|
143 | + return $uri; |
|
144 | + } |
|
145 | + /** |
|
146 | + * Whether the URI has the default port of the current scheme. |
|
147 | + * |
|
148 | + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used |
|
149 | + * independently of the implementation. |
|
150 | + */ |
|
151 | + public static function isDefaultPort(UriInterface $uri) : bool |
|
152 | + { |
|
153 | + return $uri->getPort() === null || isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]; |
|
154 | + } |
|
155 | + /** |
|
156 | + * Whether the URI is absolute, i.e. it has a scheme. |
|
157 | + * |
|
158 | + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true |
|
159 | + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative |
|
160 | + * to another URI, the base URI. Relative references can be divided into several forms: |
|
161 | + * - network-path references, e.g. '//example.com/path' |
|
162 | + * - absolute-path references, e.g. '/path' |
|
163 | + * - relative-path references, e.g. 'subpath' |
|
164 | + * |
|
165 | + * @see Uri::isNetworkPathReference |
|
166 | + * @see Uri::isAbsolutePathReference |
|
167 | + * @see Uri::isRelativePathReference |
|
168 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4 |
|
169 | + */ |
|
170 | + public static function isAbsolute(UriInterface $uri) : bool |
|
171 | + { |
|
172 | + return $uri->getScheme() !== ''; |
|
173 | + } |
|
174 | + /** |
|
175 | + * Whether the URI is a network-path reference. |
|
176 | + * |
|
177 | + * A relative reference that begins with two slash characters is termed an network-path reference. |
|
178 | + * |
|
179 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
180 | + */ |
|
181 | + public static function isNetworkPathReference(UriInterface $uri) : bool |
|
182 | + { |
|
183 | + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; |
|
184 | + } |
|
185 | + /** |
|
186 | + * Whether the URI is a absolute-path reference. |
|
187 | + * |
|
188 | + * A relative reference that begins with a single slash character is termed an absolute-path reference. |
|
189 | + * |
|
190 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
191 | + */ |
|
192 | + public static function isAbsolutePathReference(UriInterface $uri) : bool |
|
193 | + { |
|
194 | + return $uri->getScheme() === '' && $uri->getAuthority() === '' && isset($uri->getPath()[0]) && $uri->getPath()[0] === '/'; |
|
195 | + } |
|
196 | + /** |
|
197 | + * Whether the URI is a relative-path reference. |
|
198 | + * |
|
199 | + * A relative reference that does not begin with a slash character is termed a relative-path reference. |
|
200 | + * |
|
201 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 |
|
202 | + */ |
|
203 | + public static function isRelativePathReference(UriInterface $uri) : bool |
|
204 | + { |
|
205 | + return $uri->getScheme() === '' && $uri->getAuthority() === '' && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); |
|
206 | + } |
|
207 | + /** |
|
208 | + * Whether the URI is a same-document reference. |
|
209 | + * |
|
210 | + * A same-document reference refers to a URI that is, aside from its fragment |
|
211 | + * component, identical to the base URI. When no base URI is given, only an empty |
|
212 | + * URI reference (apart from its fragment) is considered a same-document reference. |
|
213 | + * |
|
214 | + * @param UriInterface $uri The URI to check |
|
215 | + * @param UriInterface|null $base An optional base URI to compare against |
|
216 | + * |
|
217 | + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4 |
|
218 | + */ |
|
219 | + public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null) : bool |
|
220 | + { |
|
221 | + if ($base !== null) { |
|
222 | + $uri = UriResolver::resolve($base, $uri); |
|
223 | + return $uri->getScheme() === $base->getScheme() && $uri->getAuthority() === $base->getAuthority() && $uri->getPath() === $base->getPath() && $uri->getQuery() === $base->getQuery(); |
|
224 | + } |
|
225 | + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; |
|
226 | + } |
|
227 | + /** |
|
228 | + * Creates a new URI with a specific query string value removed. |
|
229 | + * |
|
230 | + * Any existing query string values that exactly match the provided key are |
|
231 | + * removed. |
|
232 | + * |
|
233 | + * @param UriInterface $uri URI to use as a base. |
|
234 | + * @param string $key Query string key to remove. |
|
235 | + */ |
|
236 | + public static function withoutQueryValue(UriInterface $uri, string $key) : UriInterface |
|
237 | + { |
|
238 | + $result = self::getFilteredQueryString($uri, [$key]); |
|
239 | + return $uri->withQuery(\implode('&', $result)); |
|
240 | + } |
|
241 | + /** |
|
242 | + * Creates a new URI with a specific query string value. |
|
243 | + * |
|
244 | + * Any existing query string values that exactly match the provided key are |
|
245 | + * removed and replaced with the given key value pair. |
|
246 | + * |
|
247 | + * A value of null will set the query string key without a value, e.g. "key" |
|
248 | + * instead of "key=value". |
|
249 | + * |
|
250 | + * @param UriInterface $uri URI to use as a base. |
|
251 | + * @param string $key Key to set. |
|
252 | + * @param string|null $value Value to set |
|
253 | + */ |
|
254 | + public static function withQueryValue(UriInterface $uri, string $key, ?string $value) : UriInterface |
|
255 | + { |
|
256 | + $result = self::getFilteredQueryString($uri, [$key]); |
|
257 | + $result[] = self::generateQueryString($key, $value); |
|
258 | + return $uri->withQuery(\implode('&', $result)); |
|
259 | + } |
|
260 | + /** |
|
261 | + * Creates a new URI with multiple specific query string values. |
|
262 | + * |
|
263 | + * It has the same behavior as withQueryValue() but for an associative array of key => value. |
|
264 | + * |
|
265 | + * @param UriInterface $uri URI to use as a base. |
|
266 | + * @param (string|null)[] $keyValueArray Associative array of key and values |
|
267 | + */ |
|
268 | + public static function withQueryValues(UriInterface $uri, array $keyValueArray) : UriInterface |
|
269 | + { |
|
270 | + $result = self::getFilteredQueryString($uri, \array_keys($keyValueArray)); |
|
271 | + foreach ($keyValueArray as $key => $value) { |
|
272 | + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); |
|
273 | + } |
|
274 | + return $uri->withQuery(\implode('&', $result)); |
|
275 | + } |
|
276 | + /** |
|
277 | + * Creates a URI from a hash of `parse_url` components. |
|
278 | + * |
|
279 | + * @see https://www.php.net/manual/en/function.parse-url.php |
|
280 | + * |
|
281 | + * @throws MalformedUriException If the components do not form a valid URI. |
|
282 | + */ |
|
283 | + public static function fromParts(array $parts) : UriInterface |
|
284 | + { |
|
285 | + $uri = new self(); |
|
286 | + $uri->applyParts($parts); |
|
287 | + $uri->validateState(); |
|
288 | + return $uri; |
|
289 | + } |
|
290 | + public function getScheme() : string |
|
291 | + { |
|
292 | + return $this->scheme; |
|
293 | + } |
|
294 | + public function getAuthority() : string |
|
295 | + { |
|
296 | + $authority = $this->host; |
|
297 | + if ($this->userInfo !== '') { |
|
298 | + $authority = $this->userInfo . '@' . $authority; |
|
299 | + } |
|
300 | + if ($this->port !== null) { |
|
301 | + $authority .= ':' . $this->port; |
|
302 | + } |
|
303 | + return $authority; |
|
304 | + } |
|
305 | + public function getUserInfo() : string |
|
306 | + { |
|
307 | + return $this->userInfo; |
|
308 | + } |
|
309 | + public function getHost() : string |
|
310 | + { |
|
311 | + return $this->host; |
|
312 | + } |
|
313 | + public function getPort() : ?int |
|
314 | + { |
|
315 | + return $this->port; |
|
316 | + } |
|
317 | + public function getPath() : string |
|
318 | + { |
|
319 | + return $this->path; |
|
320 | + } |
|
321 | + public function getQuery() : string |
|
322 | + { |
|
323 | + return $this->query; |
|
324 | + } |
|
325 | + public function getFragment() : string |
|
326 | + { |
|
327 | + return $this->fragment; |
|
328 | + } |
|
329 | + public function withScheme($scheme) : UriInterface |
|
330 | + { |
|
331 | + $scheme = $this->filterScheme($scheme); |
|
332 | + if ($this->scheme === $scheme) { |
|
333 | + return $this; |
|
334 | + } |
|
335 | + $new = clone $this; |
|
336 | + $new->scheme = $scheme; |
|
337 | + $new->composedComponents = null; |
|
338 | + $new->removeDefaultPort(); |
|
339 | + $new->validateState(); |
|
340 | + return $new; |
|
341 | + } |
|
342 | + public function withUserInfo($user, $password = null) : UriInterface |
|
343 | + { |
|
344 | + $info = $this->filterUserInfoComponent($user); |
|
345 | + if ($password !== null) { |
|
346 | + $info .= ':' . $this->filterUserInfoComponent($password); |
|
347 | + } |
|
348 | + if ($this->userInfo === $info) { |
|
349 | + return $this; |
|
350 | + } |
|
351 | + $new = clone $this; |
|
352 | + $new->userInfo = $info; |
|
353 | + $new->composedComponents = null; |
|
354 | + $new->validateState(); |
|
355 | + return $new; |
|
356 | + } |
|
357 | + public function withHost($host) : UriInterface |
|
358 | + { |
|
359 | + $host = $this->filterHost($host); |
|
360 | + if ($this->host === $host) { |
|
361 | + return $this; |
|
362 | + } |
|
363 | + $new = clone $this; |
|
364 | + $new->host = $host; |
|
365 | + $new->composedComponents = null; |
|
366 | + $new->validateState(); |
|
367 | + return $new; |
|
368 | + } |
|
369 | + public function withPort($port) : UriInterface |
|
370 | + { |
|
371 | + $port = $this->filterPort($port); |
|
372 | + if ($this->port === $port) { |
|
373 | + return $this; |
|
374 | + } |
|
375 | + $new = clone $this; |
|
376 | + $new->port = $port; |
|
377 | + $new->composedComponents = null; |
|
378 | + $new->removeDefaultPort(); |
|
379 | + $new->validateState(); |
|
380 | + return $new; |
|
381 | + } |
|
382 | + public function withPath($path) : UriInterface |
|
383 | + { |
|
384 | + $path = $this->filterPath($path); |
|
385 | + if ($this->path === $path) { |
|
386 | + return $this; |
|
387 | + } |
|
388 | + $new = clone $this; |
|
389 | + $new->path = $path; |
|
390 | + $new->composedComponents = null; |
|
391 | + $new->validateState(); |
|
392 | + return $new; |
|
393 | + } |
|
394 | + public function withQuery($query) : UriInterface |
|
395 | + { |
|
396 | + $query = $this->filterQueryAndFragment($query); |
|
397 | + if ($this->query === $query) { |
|
398 | + return $this; |
|
399 | + } |
|
400 | + $new = clone $this; |
|
401 | + $new->query = $query; |
|
402 | + $new->composedComponents = null; |
|
403 | + return $new; |
|
404 | + } |
|
405 | + public function withFragment($fragment) : UriInterface |
|
406 | + { |
|
407 | + $fragment = $this->filterQueryAndFragment($fragment); |
|
408 | + if ($this->fragment === $fragment) { |
|
409 | + return $this; |
|
410 | + } |
|
411 | + $new = clone $this; |
|
412 | + $new->fragment = $fragment; |
|
413 | + $new->composedComponents = null; |
|
414 | + return $new; |
|
415 | + } |
|
416 | + public function jsonSerialize() : string |
|
417 | + { |
|
418 | + return $this->__toString(); |
|
419 | + } |
|
420 | + /** |
|
421 | + * Apply parse_url parts to a URI. |
|
422 | + * |
|
423 | + * @param array $parts Array of parse_url parts to apply. |
|
424 | + */ |
|
425 | + private function applyParts(array $parts) : void |
|
426 | + { |
|
427 | + $this->scheme = isset($parts['scheme']) ? $this->filterScheme($parts['scheme']) : ''; |
|
428 | + $this->userInfo = isset($parts['user']) ? $this->filterUserInfoComponent($parts['user']) : ''; |
|
429 | + $this->host = isset($parts['host']) ? $this->filterHost($parts['host']) : ''; |
|
430 | + $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null; |
|
431 | + $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : ''; |
|
432 | + $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : ''; |
|
433 | + $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : ''; |
|
434 | + if (isset($parts['pass'])) { |
|
435 | + $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); |
|
436 | + } |
|
437 | + $this->removeDefaultPort(); |
|
438 | + } |
|
439 | + /** |
|
440 | + * @param mixed $scheme |
|
441 | + * |
|
442 | + * @throws \InvalidArgumentException If the scheme is invalid. |
|
443 | + */ |
|
444 | + private function filterScheme($scheme) : string |
|
445 | + { |
|
446 | + if (!\is_string($scheme)) { |
|
447 | + throw new \InvalidArgumentException('Scheme must be a string'); |
|
448 | + } |
|
449 | + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); |
|
450 | + } |
|
451 | + /** |
|
452 | + * @param mixed $component |
|
453 | + * |
|
454 | + * @throws \InvalidArgumentException If the user info is invalid. |
|
455 | + */ |
|
456 | + private function filterUserInfoComponent($component) : string |
|
457 | + { |
|
458 | + if (!\is_string($component)) { |
|
459 | + throw new \InvalidArgumentException('User info must be a string'); |
|
460 | + } |
|
461 | + return \preg_replace_callback('/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $component); |
|
462 | + } |
|
463 | + /** |
|
464 | + * @param mixed $host |
|
465 | + * |
|
466 | + * @throws \InvalidArgumentException If the host is invalid. |
|
467 | + */ |
|
468 | + private function filterHost($host) : string |
|
469 | + { |
|
470 | + if (!\is_string($host)) { |
|
471 | + throw new \InvalidArgumentException('Host must be a string'); |
|
472 | + } |
|
473 | + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); |
|
474 | + } |
|
475 | + /** |
|
476 | + * @param mixed $port |
|
477 | + * |
|
478 | + * @throws \InvalidArgumentException If the port is invalid. |
|
479 | + */ |
|
480 | + private function filterPort($port) : ?int |
|
481 | + { |
|
482 | + if ($port === null) { |
|
483 | + return null; |
|
484 | + } |
|
485 | + $port = (int) $port; |
|
486 | + if (0 > $port || 0xffff < $port) { |
|
487 | + throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port)); |
|
488 | + } |
|
489 | + return $port; |
|
490 | + } |
|
491 | + /** |
|
492 | + * @param (string|int)[] $keys |
|
493 | + * |
|
494 | + * @return string[] |
|
495 | + */ |
|
496 | + private static function getFilteredQueryString(UriInterface $uri, array $keys) : array |
|
497 | + { |
|
498 | + $current = $uri->getQuery(); |
|
499 | + if ($current === '') { |
|
500 | + return []; |
|
501 | + } |
|
502 | + $decodedKeys = \array_map(function ($k) : string { |
|
503 | + return \rawurldecode((string) $k); |
|
504 | + }, $keys); |
|
505 | + return \array_filter(\explode('&', $current), function ($part) use($decodedKeys) { |
|
506 | + return !\in_array(\rawurldecode(\explode('=', $part)[0]), $decodedKeys, \true); |
|
507 | + }); |
|
508 | + } |
|
509 | + private static function generateQueryString(string $key, ?string $value) : string |
|
510 | + { |
|
511 | + // Query string separators ("=", "&") within the key or value need to be encoded |
|
512 | + // (while preventing double-encoding) before setting the query string. All other |
|
513 | + // chars that need percent-encoding will be encoded by withQuery(). |
|
514 | + $queryString = \strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); |
|
515 | + if ($value !== null) { |
|
516 | + $queryString .= '=' . \strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); |
|
517 | + } |
|
518 | + return $queryString; |
|
519 | + } |
|
520 | + private function removeDefaultPort() : void |
|
521 | + { |
|
522 | + if ($this->port !== null && self::isDefaultPort($this)) { |
|
523 | + $this->port = null; |
|
524 | + } |
|
525 | + } |
|
526 | + /** |
|
527 | + * Filters the path of a URI |
|
528 | + * |
|
529 | + * @param mixed $path |
|
530 | + * |
|
531 | + * @throws \InvalidArgumentException If the path is invalid. |
|
532 | + */ |
|
533 | + private function filterPath($path) : string |
|
534 | + { |
|
535 | + if (!\is_string($path)) { |
|
536 | + throw new \InvalidArgumentException('Path must be a string'); |
|
537 | + } |
|
538 | + return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\\/]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $path); |
|
539 | + } |
|
540 | + /** |
|
541 | + * Filters the query string or fragment of a URI. |
|
542 | + * |
|
543 | + * @param mixed $str |
|
544 | + * |
|
545 | + * @throws \InvalidArgumentException If the query or fragment is invalid. |
|
546 | + */ |
|
547 | + private function filterQueryAndFragment($str) : string |
|
548 | + { |
|
549 | + if (!\is_string($str)) { |
|
550 | + throw new \InvalidArgumentException('Query and fragment must be a string'); |
|
551 | + } |
|
552 | + return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\\/\\?]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $str); |
|
553 | + } |
|
554 | + private function rawurlencodeMatchZero(array $match) : string |
|
555 | + { |
|
556 | + return \rawurlencode($match[0]); |
|
557 | + } |
|
558 | + private function validateState() : void |
|
559 | + { |
|
560 | + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { |
|
561 | + $this->host = self::HTTP_DEFAULT_HOST; |
|
562 | + } |
|
563 | + if ($this->getAuthority() === '') { |
|
564 | + if (0 === \strpos($this->path, '//')) { |
|
565 | + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); |
|
566 | + } |
|
567 | + if ($this->scheme === '' && \false !== \strpos(\explode('/', $this->path, 2)[0], ':')) { |
|
568 | + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); |
|
569 | + } |
|
570 | + } |
|
571 | + } |
|
572 | 572 | } |
@@ -5,108 +5,108 @@ |
||
5 | 5 | |
6 | 6 | final class Query |
7 | 7 | { |
8 | - /** |
|
9 | - * Parse a query string into an associative array. |
|
10 | - * |
|
11 | - * If multiple values are found for the same key, the value of that key |
|
12 | - * value pair will become an array. This function does not parse nested |
|
13 | - * PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` |
|
14 | - * will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. |
|
15 | - * |
|
16 | - * @param string $str Query string to parse |
|
17 | - * @param int|bool $urlEncoding How the query string is encoded |
|
18 | - */ |
|
19 | - public static function parse(string $str, $urlEncoding = \true) : array |
|
20 | - { |
|
21 | - $result = []; |
|
22 | - if ($str === '') { |
|
23 | - return $result; |
|
24 | - } |
|
25 | - if ($urlEncoding === \true) { |
|
26 | - $decoder = function ($value) { |
|
27 | - return \rawurldecode(\str_replace('+', ' ', (string) $value)); |
|
28 | - }; |
|
29 | - } elseif ($urlEncoding === \PHP_QUERY_RFC3986) { |
|
30 | - $decoder = 'rawurldecode'; |
|
31 | - } elseif ($urlEncoding === \PHP_QUERY_RFC1738) { |
|
32 | - $decoder = 'urldecode'; |
|
33 | - } else { |
|
34 | - $decoder = function ($str) { |
|
35 | - return $str; |
|
36 | - }; |
|
37 | - } |
|
38 | - foreach (\explode('&', $str) as $kvp) { |
|
39 | - $parts = \explode('=', $kvp, 2); |
|
40 | - $key = $decoder($parts[0]); |
|
41 | - $value = isset($parts[1]) ? $decoder($parts[1]) : null; |
|
42 | - if (!\array_key_exists($key, $result)) { |
|
43 | - $result[$key] = $value; |
|
44 | - } else { |
|
45 | - if (!\is_array($result[$key])) { |
|
46 | - $result[$key] = [$result[$key]]; |
|
47 | - } |
|
48 | - $result[$key][] = $value; |
|
49 | - } |
|
50 | - } |
|
51 | - return $result; |
|
52 | - } |
|
53 | - /** |
|
54 | - * Build a query string from an array of key value pairs. |
|
55 | - * |
|
56 | - * This function can use the return value of `parse()` to build a query |
|
57 | - * string. This function does not modify the provided keys when an array is |
|
58 | - * encountered (like `http_build_query()` would). |
|
59 | - * |
|
60 | - * @param array $params Query string parameters. |
|
61 | - * @param int|false $encoding Set to false to not encode, |
|
62 | - * PHP_QUERY_RFC3986 to encode using |
|
63 | - * RFC3986, or PHP_QUERY_RFC1738 to |
|
64 | - * encode using RFC1738. |
|
65 | - * @param bool $treatBoolsAsInts Set to true to encode as 0/1, and |
|
66 | - * false as false/true. |
|
67 | - */ |
|
68 | - public static function build(array $params, $encoding = \PHP_QUERY_RFC3986, bool $treatBoolsAsInts = \true) : string |
|
69 | - { |
|
70 | - if (!$params) { |
|
71 | - return ''; |
|
72 | - } |
|
73 | - if ($encoding === \false) { |
|
74 | - $encoder = function (string $str) : string { |
|
75 | - return $str; |
|
76 | - }; |
|
77 | - } elseif ($encoding === \PHP_QUERY_RFC3986) { |
|
78 | - $encoder = 'rawurlencode'; |
|
79 | - } elseif ($encoding === \PHP_QUERY_RFC1738) { |
|
80 | - $encoder = 'urlencode'; |
|
81 | - } else { |
|
82 | - throw new \InvalidArgumentException('Invalid type'); |
|
83 | - } |
|
84 | - $castBool = $treatBoolsAsInts ? static function ($v) { |
|
85 | - return (int) $v; |
|
86 | - } : static function ($v) { |
|
87 | - return $v ? 'true' : 'false'; |
|
88 | - }; |
|
89 | - $qs = ''; |
|
90 | - foreach ($params as $k => $v) { |
|
91 | - $k = $encoder((string) $k); |
|
92 | - if (!\is_array($v)) { |
|
93 | - $qs .= $k; |
|
94 | - $v = \is_bool($v) ? $castBool($v) : $v; |
|
95 | - if ($v !== null) { |
|
96 | - $qs .= '=' . $encoder((string) $v); |
|
97 | - } |
|
98 | - $qs .= '&'; |
|
99 | - } else { |
|
100 | - foreach ($v as $vv) { |
|
101 | - $qs .= $k; |
|
102 | - $vv = \is_bool($vv) ? $castBool($vv) : $vv; |
|
103 | - if ($vv !== null) { |
|
104 | - $qs .= '=' . $encoder((string) $vv); |
|
105 | - } |
|
106 | - $qs .= '&'; |
|
107 | - } |
|
108 | - } |
|
109 | - } |
|
110 | - return $qs ? (string) \substr($qs, 0, -1) : ''; |
|
111 | - } |
|
8 | + /** |
|
9 | + * Parse a query string into an associative array. |
|
10 | + * |
|
11 | + * If multiple values are found for the same key, the value of that key |
|
12 | + * value pair will become an array. This function does not parse nested |
|
13 | + * PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` |
|
14 | + * will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. |
|
15 | + * |
|
16 | + * @param string $str Query string to parse |
|
17 | + * @param int|bool $urlEncoding How the query string is encoded |
|
18 | + */ |
|
19 | + public static function parse(string $str, $urlEncoding = \true) : array |
|
20 | + { |
|
21 | + $result = []; |
|
22 | + if ($str === '') { |
|
23 | + return $result; |
|
24 | + } |
|
25 | + if ($urlEncoding === \true) { |
|
26 | + $decoder = function ($value) { |
|
27 | + return \rawurldecode(\str_replace('+', ' ', (string) $value)); |
|
28 | + }; |
|
29 | + } elseif ($urlEncoding === \PHP_QUERY_RFC3986) { |
|
30 | + $decoder = 'rawurldecode'; |
|
31 | + } elseif ($urlEncoding === \PHP_QUERY_RFC1738) { |
|
32 | + $decoder = 'urldecode'; |
|
33 | + } else { |
|
34 | + $decoder = function ($str) { |
|
35 | + return $str; |
|
36 | + }; |
|
37 | + } |
|
38 | + foreach (\explode('&', $str) as $kvp) { |
|
39 | + $parts = \explode('=', $kvp, 2); |
|
40 | + $key = $decoder($parts[0]); |
|
41 | + $value = isset($parts[1]) ? $decoder($parts[1]) : null; |
|
42 | + if (!\array_key_exists($key, $result)) { |
|
43 | + $result[$key] = $value; |
|
44 | + } else { |
|
45 | + if (!\is_array($result[$key])) { |
|
46 | + $result[$key] = [$result[$key]]; |
|
47 | + } |
|
48 | + $result[$key][] = $value; |
|
49 | + } |
|
50 | + } |
|
51 | + return $result; |
|
52 | + } |
|
53 | + /** |
|
54 | + * Build a query string from an array of key value pairs. |
|
55 | + * |
|
56 | + * This function can use the return value of `parse()` to build a query |
|
57 | + * string. This function does not modify the provided keys when an array is |
|
58 | + * encountered (like `http_build_query()` would). |
|
59 | + * |
|
60 | + * @param array $params Query string parameters. |
|
61 | + * @param int|false $encoding Set to false to not encode, |
|
62 | + * PHP_QUERY_RFC3986 to encode using |
|
63 | + * RFC3986, or PHP_QUERY_RFC1738 to |
|
64 | + * encode using RFC1738. |
|
65 | + * @param bool $treatBoolsAsInts Set to true to encode as 0/1, and |
|
66 | + * false as false/true. |
|
67 | + */ |
|
68 | + public static function build(array $params, $encoding = \PHP_QUERY_RFC3986, bool $treatBoolsAsInts = \true) : string |
|
69 | + { |
|
70 | + if (!$params) { |
|
71 | + return ''; |
|
72 | + } |
|
73 | + if ($encoding === \false) { |
|
74 | + $encoder = function (string $str) : string { |
|
75 | + return $str; |
|
76 | + }; |
|
77 | + } elseif ($encoding === \PHP_QUERY_RFC3986) { |
|
78 | + $encoder = 'rawurlencode'; |
|
79 | + } elseif ($encoding === \PHP_QUERY_RFC1738) { |
|
80 | + $encoder = 'urlencode'; |
|
81 | + } else { |
|
82 | + throw new \InvalidArgumentException('Invalid type'); |
|
83 | + } |
|
84 | + $castBool = $treatBoolsAsInts ? static function ($v) { |
|
85 | + return (int) $v; |
|
86 | + } : static function ($v) { |
|
87 | + return $v ? 'true' : 'false'; |
|
88 | + }; |
|
89 | + $qs = ''; |
|
90 | + foreach ($params as $k => $v) { |
|
91 | + $k = $encoder((string) $k); |
|
92 | + if (!\is_array($v)) { |
|
93 | + $qs .= $k; |
|
94 | + $v = \is_bool($v) ? $castBool($v) : $v; |
|
95 | + if ($v !== null) { |
|
96 | + $qs .= '=' . $encoder((string) $v); |
|
97 | + } |
|
98 | + $qs .= '&'; |
|
99 | + } else { |
|
100 | + foreach ($v as $vv) { |
|
101 | + $qs .= $k; |
|
102 | + $vv = \is_bool($vv) ? $castBool($vv) : $vv; |
|
103 | + if ($vv !== null) { |
|
104 | + $qs .= '=' . $encoder((string) $vv); |
|
105 | + } |
|
106 | + $qs .= '&'; |
|
107 | + } |
|
108 | + } |
|
109 | + } |
|
110 | + return $qs ? (string) \substr($qs, 0, -1) : ''; |
|
111 | + } |
|
112 | 112 | } |
@@ -1,6 +1,6 @@ discard block |
||
1 | 1 | <?php |
2 | 2 | |
3 | -declare (strict_types=1); |
|
3 | +declare(strict_types=1); |
|
4 | 4 | namespace OCA\FullTextSearch_Elasticsearch\Vendor\GuzzleHttp\Psr7; |
5 | 5 | |
6 | 6 | final class Query |
@@ -23,15 +23,15 @@ discard block |
||
23 | 23 | return $result; |
24 | 24 | } |
25 | 25 | if ($urlEncoding === \true) { |
26 | - $decoder = function ($value) { |
|
27 | - return \rawurldecode(\str_replace('+', ' ', (string) $value)); |
|
26 | + $decoder = function($value) { |
|
27 | + return \rawurldecode(\str_replace('+', ' ', (string)$value)); |
|
28 | 28 | }; |
29 | 29 | } elseif ($urlEncoding === \PHP_QUERY_RFC3986) { |
30 | 30 | $decoder = 'rawurldecode'; |
31 | 31 | } elseif ($urlEncoding === \PHP_QUERY_RFC1738) { |
32 | 32 | $decoder = 'urldecode'; |
33 | 33 | } else { |
34 | - $decoder = function ($str) { |
|
34 | + $decoder = function($str) { |
|
35 | 35 | return $str; |
36 | 36 | }; |
37 | 37 | } |
@@ -71,7 +71,7 @@ discard block |
||
71 | 71 | return ''; |
72 | 72 | } |
73 | 73 | if ($encoding === \false) { |
74 | - $encoder = function (string $str) : string { |
|
74 | + $encoder = function(string $str) : string { |
|
75 | 75 | return $str; |
76 | 76 | }; |
77 | 77 | } elseif ($encoding === \PHP_QUERY_RFC3986) { |
@@ -81,19 +81,19 @@ discard block |
||
81 | 81 | } else { |
82 | 82 | throw new \InvalidArgumentException('Invalid type'); |
83 | 83 | } |
84 | - $castBool = $treatBoolsAsInts ? static function ($v) { |
|
85 | - return (int) $v; |
|
86 | - } : static function ($v) { |
|
84 | + $castBool = $treatBoolsAsInts ? static function($v) { |
|
85 | + return (int)$v; |
|
86 | + } : static function($v) { |
|
87 | 87 | return $v ? 'true' : 'false'; |
88 | 88 | }; |
89 | 89 | $qs = ''; |
90 | 90 | foreach ($params as $k => $v) { |
91 | - $k = $encoder((string) $k); |
|
91 | + $k = $encoder((string)$k); |
|
92 | 92 | if (!\is_array($v)) { |
93 | 93 | $qs .= $k; |
94 | 94 | $v = \is_bool($v) ? $castBool($v) : $v; |
95 | 95 | if ($v !== null) { |
96 | - $qs .= '=' . $encoder((string) $v); |
|
96 | + $qs .= '='.$encoder((string)$v); |
|
97 | 97 | } |
98 | 98 | $qs .= '&'; |
99 | 99 | } else { |
@@ -101,12 +101,12 @@ discard block |
||
101 | 101 | $qs .= $k; |
102 | 102 | $vv = \is_bool($vv) ? $castBool($vv) : $vv; |
103 | 103 | if ($vv !== null) { |
104 | - $qs .= '=' . $encoder((string) $vv); |
|
104 | + $qs .= '='.$encoder((string)$vv); |
|
105 | 105 | } |
106 | 106 | $qs .= '&'; |
107 | 107 | } |
108 | 108 | } |
109 | 109 | } |
110 | - return $qs ? (string) \substr($qs, 0, -1) : ''; |
|
110 | + return $qs ? (string)\substr($qs, 0, -1) : ''; |
|
111 | 111 | } |
112 | 112 | } |
@@ -9,378 +9,378 @@ |
||
9 | 9 | use OCA\FullTextSearch_Elasticsearch\Vendor\Psr\Http\Message\UriInterface; |
10 | 10 | final class Utils |
11 | 11 | { |
12 | - /** |
|
13 | - * Remove the items given by the keys, case insensitively from the data. |
|
14 | - * |
|
15 | - * @param (string|int)[] $keys |
|
16 | - */ |
|
17 | - public static function caselessRemove(array $keys, array $data) : array |
|
18 | - { |
|
19 | - $result = []; |
|
20 | - foreach ($keys as &$key) { |
|
21 | - $key = \strtolower((string) $key); |
|
22 | - } |
|
23 | - foreach ($data as $k => $v) { |
|
24 | - if (!\in_array(\strtolower((string) $k), $keys)) { |
|
25 | - $result[$k] = $v; |
|
26 | - } |
|
27 | - } |
|
28 | - return $result; |
|
29 | - } |
|
30 | - /** |
|
31 | - * Copy the contents of a stream into another stream until the given number |
|
32 | - * of bytes have been read. |
|
33 | - * |
|
34 | - * @param StreamInterface $source Stream to read from |
|
35 | - * @param StreamInterface $dest Stream to write to |
|
36 | - * @param int $maxLen Maximum number of bytes to read. Pass -1 |
|
37 | - * to read the entire stream. |
|
38 | - * |
|
39 | - * @throws \RuntimeException on error. |
|
40 | - */ |
|
41 | - public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1) : void |
|
42 | - { |
|
43 | - $bufferSize = 8192; |
|
44 | - if ($maxLen === -1) { |
|
45 | - while (!$source->eof()) { |
|
46 | - if (!$dest->write($source->read($bufferSize))) { |
|
47 | - break; |
|
48 | - } |
|
49 | - } |
|
50 | - } else { |
|
51 | - $remaining = $maxLen; |
|
52 | - while ($remaining > 0 && !$source->eof()) { |
|
53 | - $buf = $source->read(\min($bufferSize, $remaining)); |
|
54 | - $len = \strlen($buf); |
|
55 | - if (!$len) { |
|
56 | - break; |
|
57 | - } |
|
58 | - $remaining -= $len; |
|
59 | - $dest->write($buf); |
|
60 | - } |
|
61 | - } |
|
62 | - } |
|
63 | - /** |
|
64 | - * Copy the contents of a stream into a string until the given number of |
|
65 | - * bytes have been read. |
|
66 | - * |
|
67 | - * @param StreamInterface $stream Stream to read |
|
68 | - * @param int $maxLen Maximum number of bytes to read. Pass -1 |
|
69 | - * to read the entire stream. |
|
70 | - * |
|
71 | - * @throws \RuntimeException on error. |
|
72 | - */ |
|
73 | - public static function copyToString(StreamInterface $stream, int $maxLen = -1) : string |
|
74 | - { |
|
75 | - $buffer = ''; |
|
76 | - if ($maxLen === -1) { |
|
77 | - while (!$stream->eof()) { |
|
78 | - $buf = $stream->read(1048576); |
|
79 | - if ($buf === '') { |
|
80 | - break; |
|
81 | - } |
|
82 | - $buffer .= $buf; |
|
83 | - } |
|
84 | - return $buffer; |
|
85 | - } |
|
86 | - $len = 0; |
|
87 | - while (!$stream->eof() && $len < $maxLen) { |
|
88 | - $buf = $stream->read($maxLen - $len); |
|
89 | - if ($buf === '') { |
|
90 | - break; |
|
91 | - } |
|
92 | - $buffer .= $buf; |
|
93 | - $len = \strlen($buffer); |
|
94 | - } |
|
95 | - return $buffer; |
|
96 | - } |
|
97 | - /** |
|
98 | - * Calculate a hash of a stream. |
|
99 | - * |
|
100 | - * This method reads the entire stream to calculate a rolling hash, based |
|
101 | - * on PHP's `hash_init` functions. |
|
102 | - * |
|
103 | - * @param StreamInterface $stream Stream to calculate the hash for |
|
104 | - * @param string $algo Hash algorithm (e.g. md5, crc32, etc) |
|
105 | - * @param bool $rawOutput Whether or not to use raw output |
|
106 | - * |
|
107 | - * @throws \RuntimeException on error. |
|
108 | - */ |
|
109 | - public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = \false) : string |
|
110 | - { |
|
111 | - $pos = $stream->tell(); |
|
112 | - if ($pos > 0) { |
|
113 | - $stream->rewind(); |
|
114 | - } |
|
115 | - $ctx = \hash_init($algo); |
|
116 | - while (!$stream->eof()) { |
|
117 | - \hash_update($ctx, $stream->read(1048576)); |
|
118 | - } |
|
119 | - $out = \hash_final($ctx, $rawOutput); |
|
120 | - $stream->seek($pos); |
|
121 | - return $out; |
|
122 | - } |
|
123 | - /** |
|
124 | - * Clone and modify a request with the given changes. |
|
125 | - * |
|
126 | - * This method is useful for reducing the number of clones needed to mutate |
|
127 | - * a message. |
|
128 | - * |
|
129 | - * The changes can be one of: |
|
130 | - * - method: (string) Changes the HTTP method. |
|
131 | - * - set_headers: (array) Sets the given headers. |
|
132 | - * - remove_headers: (array) Remove the given headers. |
|
133 | - * - body: (mixed) Sets the given body. |
|
134 | - * - uri: (UriInterface) Set the URI. |
|
135 | - * - query: (string) Set the query string value of the URI. |
|
136 | - * - version: (string) Set the protocol version. |
|
137 | - * |
|
138 | - * @param RequestInterface $request Request to clone and modify. |
|
139 | - * @param array $changes Changes to apply. |
|
140 | - */ |
|
141 | - public static function modifyRequest(RequestInterface $request, array $changes) : RequestInterface |
|
142 | - { |
|
143 | - if (!$changes) { |
|
144 | - return $request; |
|
145 | - } |
|
146 | - $headers = $request->getHeaders(); |
|
147 | - if (!isset($changes['uri'])) { |
|
148 | - $uri = $request->getUri(); |
|
149 | - } else { |
|
150 | - // Remove the host header if one is on the URI |
|
151 | - if ($host = $changes['uri']->getHost()) { |
|
152 | - $changes['set_headers']['Host'] = $host; |
|
153 | - if ($port = $changes['uri']->getPort()) { |
|
154 | - $standardPorts = ['http' => 80, 'https' => 443]; |
|
155 | - $scheme = $changes['uri']->getScheme(); |
|
156 | - if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { |
|
157 | - $changes['set_headers']['Host'] .= ':' . $port; |
|
158 | - } |
|
159 | - } |
|
160 | - } |
|
161 | - $uri = $changes['uri']; |
|
162 | - } |
|
163 | - if (!empty($changes['remove_headers'])) { |
|
164 | - $headers = self::caselessRemove($changes['remove_headers'], $headers); |
|
165 | - } |
|
166 | - if (!empty($changes['set_headers'])) { |
|
167 | - $headers = self::caselessRemove(\array_keys($changes['set_headers']), $headers); |
|
168 | - $headers = $changes['set_headers'] + $headers; |
|
169 | - } |
|
170 | - if (isset($changes['query'])) { |
|
171 | - $uri = $uri->withQuery($changes['query']); |
|
172 | - } |
|
173 | - if ($request instanceof ServerRequestInterface) { |
|
174 | - $new = (new ServerRequest($changes['method'] ?? $request->getMethod(), $uri, $headers, $changes['body'] ?? $request->getBody(), $changes['version'] ?? $request->getProtocolVersion(), $request->getServerParams()))->withParsedBody($request->getParsedBody())->withQueryParams($request->getQueryParams())->withCookieParams($request->getCookieParams())->withUploadedFiles($request->getUploadedFiles()); |
|
175 | - foreach ($request->getAttributes() as $key => $value) { |
|
176 | - $new = $new->withAttribute($key, $value); |
|
177 | - } |
|
178 | - return $new; |
|
179 | - } |
|
180 | - return new Request($changes['method'] ?? $request->getMethod(), $uri, $headers, $changes['body'] ?? $request->getBody(), $changes['version'] ?? $request->getProtocolVersion()); |
|
181 | - } |
|
182 | - /** |
|
183 | - * Read a line from the stream up to the maximum allowed buffer length. |
|
184 | - * |
|
185 | - * @param StreamInterface $stream Stream to read from |
|
186 | - * @param int|null $maxLength Maximum buffer length |
|
187 | - */ |
|
188 | - public static function readLine(StreamInterface $stream, ?int $maxLength = null) : string |
|
189 | - { |
|
190 | - $buffer = ''; |
|
191 | - $size = 0; |
|
192 | - while (!$stream->eof()) { |
|
193 | - if ('' === ($byte = $stream->read(1))) { |
|
194 | - return $buffer; |
|
195 | - } |
|
196 | - $buffer .= $byte; |
|
197 | - // Break when a new line is found or the max length - 1 is reached |
|
198 | - if ($byte === "\n" || ++$size === $maxLength - 1) { |
|
199 | - break; |
|
200 | - } |
|
201 | - } |
|
202 | - return $buffer; |
|
203 | - } |
|
204 | - /** |
|
205 | - * Redact the password in the user info part of a URI. |
|
206 | - */ |
|
207 | - public static function redactUserInfo(UriInterface $uri) : UriInterface |
|
208 | - { |
|
209 | - $userInfo = $uri->getUserInfo(); |
|
210 | - if (\false !== ($pos = \strpos($userInfo, ':'))) { |
|
211 | - return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); |
|
212 | - } |
|
213 | - return $uri; |
|
214 | - } |
|
215 | - /** |
|
216 | - * Create a new stream based on the input type. |
|
217 | - * |
|
218 | - * Options is an associative array that can contain the following keys: |
|
219 | - * - metadata: Array of custom metadata. |
|
220 | - * - size: Size of the stream. |
|
221 | - * |
|
222 | - * This method accepts the following `$resource` types: |
|
223 | - * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. |
|
224 | - * - `string`: Creates a stream object that uses the given string as the contents. |
|
225 | - * - `resource`: Creates a stream object that wraps the given PHP stream resource. |
|
226 | - * - `Iterator`: If the provided value implements `Iterator`, then a read-only |
|
227 | - * stream object will be created that wraps the given iterable. Each time the |
|
228 | - * stream is read from, data from the iterator will fill a buffer and will be |
|
229 | - * continuously called until the buffer is equal to the requested read size. |
|
230 | - * Subsequent read calls will first read from the buffer and then call `next` |
|
231 | - * on the underlying iterator until it is exhausted. |
|
232 | - * - `object` with `__toString()`: If the object has the `__toString()` method, |
|
233 | - * the object will be cast to a string and then a stream will be returned that |
|
234 | - * uses the string value. |
|
235 | - * - `NULL`: When `null` is passed, an empty stream object is returned. |
|
236 | - * - `callable` When a callable is passed, a read-only stream object will be |
|
237 | - * created that invokes the given callable. The callable is invoked with the |
|
238 | - * number of suggested bytes to read. The callable can return any number of |
|
239 | - * bytes, but MUST return `false` when there is no more data to return. The |
|
240 | - * stream object that wraps the callable will invoke the callable until the |
|
241 | - * number of requested bytes are available. Any additional bytes will be |
|
242 | - * buffered and used in subsequent reads. |
|
243 | - * |
|
244 | - * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data |
|
245 | - * @param array{size?: int, metadata?: array} $options Additional options |
|
246 | - * |
|
247 | - * @throws \InvalidArgumentException if the $resource arg is not valid. |
|
248 | - */ |
|
249 | - public static function streamFor($resource = '', array $options = []) : StreamInterface |
|
250 | - { |
|
251 | - if (\is_scalar($resource)) { |
|
252 | - $stream = self::tryFopen('php://temp', 'r+'); |
|
253 | - if ($resource !== '') { |
|
254 | - \fwrite($stream, (string) $resource); |
|
255 | - \fseek($stream, 0); |
|
256 | - } |
|
257 | - return new Stream($stream, $options); |
|
258 | - } |
|
259 | - switch (\gettype($resource)) { |
|
260 | - case 'resource': |
|
261 | - /* |
|
12 | + /** |
|
13 | + * Remove the items given by the keys, case insensitively from the data. |
|
14 | + * |
|
15 | + * @param (string|int)[] $keys |
|
16 | + */ |
|
17 | + public static function caselessRemove(array $keys, array $data) : array |
|
18 | + { |
|
19 | + $result = []; |
|
20 | + foreach ($keys as &$key) { |
|
21 | + $key = \strtolower((string) $key); |
|
22 | + } |
|
23 | + foreach ($data as $k => $v) { |
|
24 | + if (!\in_array(\strtolower((string) $k), $keys)) { |
|
25 | + $result[$k] = $v; |
|
26 | + } |
|
27 | + } |
|
28 | + return $result; |
|
29 | + } |
|
30 | + /** |
|
31 | + * Copy the contents of a stream into another stream until the given number |
|
32 | + * of bytes have been read. |
|
33 | + * |
|
34 | + * @param StreamInterface $source Stream to read from |
|
35 | + * @param StreamInterface $dest Stream to write to |
|
36 | + * @param int $maxLen Maximum number of bytes to read. Pass -1 |
|
37 | + * to read the entire stream. |
|
38 | + * |
|
39 | + * @throws \RuntimeException on error. |
|
40 | + */ |
|
41 | + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1) : void |
|
42 | + { |
|
43 | + $bufferSize = 8192; |
|
44 | + if ($maxLen === -1) { |
|
45 | + while (!$source->eof()) { |
|
46 | + if (!$dest->write($source->read($bufferSize))) { |
|
47 | + break; |
|
48 | + } |
|
49 | + } |
|
50 | + } else { |
|
51 | + $remaining = $maxLen; |
|
52 | + while ($remaining > 0 && !$source->eof()) { |
|
53 | + $buf = $source->read(\min($bufferSize, $remaining)); |
|
54 | + $len = \strlen($buf); |
|
55 | + if (!$len) { |
|
56 | + break; |
|
57 | + } |
|
58 | + $remaining -= $len; |
|
59 | + $dest->write($buf); |
|
60 | + } |
|
61 | + } |
|
62 | + } |
|
63 | + /** |
|
64 | + * Copy the contents of a stream into a string until the given number of |
|
65 | + * bytes have been read. |
|
66 | + * |
|
67 | + * @param StreamInterface $stream Stream to read |
|
68 | + * @param int $maxLen Maximum number of bytes to read. Pass -1 |
|
69 | + * to read the entire stream. |
|
70 | + * |
|
71 | + * @throws \RuntimeException on error. |
|
72 | + */ |
|
73 | + public static function copyToString(StreamInterface $stream, int $maxLen = -1) : string |
|
74 | + { |
|
75 | + $buffer = ''; |
|
76 | + if ($maxLen === -1) { |
|
77 | + while (!$stream->eof()) { |
|
78 | + $buf = $stream->read(1048576); |
|
79 | + if ($buf === '') { |
|
80 | + break; |
|
81 | + } |
|
82 | + $buffer .= $buf; |
|
83 | + } |
|
84 | + return $buffer; |
|
85 | + } |
|
86 | + $len = 0; |
|
87 | + while (!$stream->eof() && $len < $maxLen) { |
|
88 | + $buf = $stream->read($maxLen - $len); |
|
89 | + if ($buf === '') { |
|
90 | + break; |
|
91 | + } |
|
92 | + $buffer .= $buf; |
|
93 | + $len = \strlen($buffer); |
|
94 | + } |
|
95 | + return $buffer; |
|
96 | + } |
|
97 | + /** |
|
98 | + * Calculate a hash of a stream. |
|
99 | + * |
|
100 | + * This method reads the entire stream to calculate a rolling hash, based |
|
101 | + * on PHP's `hash_init` functions. |
|
102 | + * |
|
103 | + * @param StreamInterface $stream Stream to calculate the hash for |
|
104 | + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) |
|
105 | + * @param bool $rawOutput Whether or not to use raw output |
|
106 | + * |
|
107 | + * @throws \RuntimeException on error. |
|
108 | + */ |
|
109 | + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = \false) : string |
|
110 | + { |
|
111 | + $pos = $stream->tell(); |
|
112 | + if ($pos > 0) { |
|
113 | + $stream->rewind(); |
|
114 | + } |
|
115 | + $ctx = \hash_init($algo); |
|
116 | + while (!$stream->eof()) { |
|
117 | + \hash_update($ctx, $stream->read(1048576)); |
|
118 | + } |
|
119 | + $out = \hash_final($ctx, $rawOutput); |
|
120 | + $stream->seek($pos); |
|
121 | + return $out; |
|
122 | + } |
|
123 | + /** |
|
124 | + * Clone and modify a request with the given changes. |
|
125 | + * |
|
126 | + * This method is useful for reducing the number of clones needed to mutate |
|
127 | + * a message. |
|
128 | + * |
|
129 | + * The changes can be one of: |
|
130 | + * - method: (string) Changes the HTTP method. |
|
131 | + * - set_headers: (array) Sets the given headers. |
|
132 | + * - remove_headers: (array) Remove the given headers. |
|
133 | + * - body: (mixed) Sets the given body. |
|
134 | + * - uri: (UriInterface) Set the URI. |
|
135 | + * - query: (string) Set the query string value of the URI. |
|
136 | + * - version: (string) Set the protocol version. |
|
137 | + * |
|
138 | + * @param RequestInterface $request Request to clone and modify. |
|
139 | + * @param array $changes Changes to apply. |
|
140 | + */ |
|
141 | + public static function modifyRequest(RequestInterface $request, array $changes) : RequestInterface |
|
142 | + { |
|
143 | + if (!$changes) { |
|
144 | + return $request; |
|
145 | + } |
|
146 | + $headers = $request->getHeaders(); |
|
147 | + if (!isset($changes['uri'])) { |
|
148 | + $uri = $request->getUri(); |
|
149 | + } else { |
|
150 | + // Remove the host header if one is on the URI |
|
151 | + if ($host = $changes['uri']->getHost()) { |
|
152 | + $changes['set_headers']['Host'] = $host; |
|
153 | + if ($port = $changes['uri']->getPort()) { |
|
154 | + $standardPorts = ['http' => 80, 'https' => 443]; |
|
155 | + $scheme = $changes['uri']->getScheme(); |
|
156 | + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { |
|
157 | + $changes['set_headers']['Host'] .= ':' . $port; |
|
158 | + } |
|
159 | + } |
|
160 | + } |
|
161 | + $uri = $changes['uri']; |
|
162 | + } |
|
163 | + if (!empty($changes['remove_headers'])) { |
|
164 | + $headers = self::caselessRemove($changes['remove_headers'], $headers); |
|
165 | + } |
|
166 | + if (!empty($changes['set_headers'])) { |
|
167 | + $headers = self::caselessRemove(\array_keys($changes['set_headers']), $headers); |
|
168 | + $headers = $changes['set_headers'] + $headers; |
|
169 | + } |
|
170 | + if (isset($changes['query'])) { |
|
171 | + $uri = $uri->withQuery($changes['query']); |
|
172 | + } |
|
173 | + if ($request instanceof ServerRequestInterface) { |
|
174 | + $new = (new ServerRequest($changes['method'] ?? $request->getMethod(), $uri, $headers, $changes['body'] ?? $request->getBody(), $changes['version'] ?? $request->getProtocolVersion(), $request->getServerParams()))->withParsedBody($request->getParsedBody())->withQueryParams($request->getQueryParams())->withCookieParams($request->getCookieParams())->withUploadedFiles($request->getUploadedFiles()); |
|
175 | + foreach ($request->getAttributes() as $key => $value) { |
|
176 | + $new = $new->withAttribute($key, $value); |
|
177 | + } |
|
178 | + return $new; |
|
179 | + } |
|
180 | + return new Request($changes['method'] ?? $request->getMethod(), $uri, $headers, $changes['body'] ?? $request->getBody(), $changes['version'] ?? $request->getProtocolVersion()); |
|
181 | + } |
|
182 | + /** |
|
183 | + * Read a line from the stream up to the maximum allowed buffer length. |
|
184 | + * |
|
185 | + * @param StreamInterface $stream Stream to read from |
|
186 | + * @param int|null $maxLength Maximum buffer length |
|
187 | + */ |
|
188 | + public static function readLine(StreamInterface $stream, ?int $maxLength = null) : string |
|
189 | + { |
|
190 | + $buffer = ''; |
|
191 | + $size = 0; |
|
192 | + while (!$stream->eof()) { |
|
193 | + if ('' === ($byte = $stream->read(1))) { |
|
194 | + return $buffer; |
|
195 | + } |
|
196 | + $buffer .= $byte; |
|
197 | + // Break when a new line is found or the max length - 1 is reached |
|
198 | + if ($byte === "\n" || ++$size === $maxLength - 1) { |
|
199 | + break; |
|
200 | + } |
|
201 | + } |
|
202 | + return $buffer; |
|
203 | + } |
|
204 | + /** |
|
205 | + * Redact the password in the user info part of a URI. |
|
206 | + */ |
|
207 | + public static function redactUserInfo(UriInterface $uri) : UriInterface |
|
208 | + { |
|
209 | + $userInfo = $uri->getUserInfo(); |
|
210 | + if (\false !== ($pos = \strpos($userInfo, ':'))) { |
|
211 | + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); |
|
212 | + } |
|
213 | + return $uri; |
|
214 | + } |
|
215 | + /** |
|
216 | + * Create a new stream based on the input type. |
|
217 | + * |
|
218 | + * Options is an associative array that can contain the following keys: |
|
219 | + * - metadata: Array of custom metadata. |
|
220 | + * - size: Size of the stream. |
|
221 | + * |
|
222 | + * This method accepts the following `$resource` types: |
|
223 | + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. |
|
224 | + * - `string`: Creates a stream object that uses the given string as the contents. |
|
225 | + * - `resource`: Creates a stream object that wraps the given PHP stream resource. |
|
226 | + * - `Iterator`: If the provided value implements `Iterator`, then a read-only |
|
227 | + * stream object will be created that wraps the given iterable. Each time the |
|
228 | + * stream is read from, data from the iterator will fill a buffer and will be |
|
229 | + * continuously called until the buffer is equal to the requested read size. |
|
230 | + * Subsequent read calls will first read from the buffer and then call `next` |
|
231 | + * on the underlying iterator until it is exhausted. |
|
232 | + * - `object` with `__toString()`: If the object has the `__toString()` method, |
|
233 | + * the object will be cast to a string and then a stream will be returned that |
|
234 | + * uses the string value. |
|
235 | + * - `NULL`: When `null` is passed, an empty stream object is returned. |
|
236 | + * - `callable` When a callable is passed, a read-only stream object will be |
|
237 | + * created that invokes the given callable. The callable is invoked with the |
|
238 | + * number of suggested bytes to read. The callable can return any number of |
|
239 | + * bytes, but MUST return `false` when there is no more data to return. The |
|
240 | + * stream object that wraps the callable will invoke the callable until the |
|
241 | + * number of requested bytes are available. Any additional bytes will be |
|
242 | + * buffered and used in subsequent reads. |
|
243 | + * |
|
244 | + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data |
|
245 | + * @param array{size?: int, metadata?: array} $options Additional options |
|
246 | + * |
|
247 | + * @throws \InvalidArgumentException if the $resource arg is not valid. |
|
248 | + */ |
|
249 | + public static function streamFor($resource = '', array $options = []) : StreamInterface |
|
250 | + { |
|
251 | + if (\is_scalar($resource)) { |
|
252 | + $stream = self::tryFopen('php://temp', 'r+'); |
|
253 | + if ($resource !== '') { |
|
254 | + \fwrite($stream, (string) $resource); |
|
255 | + \fseek($stream, 0); |
|
256 | + } |
|
257 | + return new Stream($stream, $options); |
|
258 | + } |
|
259 | + switch (\gettype($resource)) { |
|
260 | + case 'resource': |
|
261 | + /* |
|
262 | 262 | * The 'php://input' is a special stream with quirks and inconsistencies. |
263 | 263 | * We avoid using that stream by reading it into php://temp |
264 | 264 | */ |
265 | - /** @var resource $resource */ |
|
266 | - if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { |
|
267 | - $stream = self::tryFopen('php://temp', 'w+'); |
|
268 | - \stream_copy_to_stream($resource, $stream); |
|
269 | - \fseek($stream, 0); |
|
270 | - $resource = $stream; |
|
271 | - } |
|
272 | - return new Stream($resource, $options); |
|
273 | - case 'object': |
|
274 | - /** @var object $resource */ |
|
275 | - if ($resource instanceof StreamInterface) { |
|
276 | - return $resource; |
|
277 | - } elseif ($resource instanceof \Iterator) { |
|
278 | - return new PumpStream(function () use($resource) { |
|
279 | - if (!$resource->valid()) { |
|
280 | - return \false; |
|
281 | - } |
|
282 | - $result = $resource->current(); |
|
283 | - $resource->next(); |
|
284 | - return $result; |
|
285 | - }, $options); |
|
286 | - } elseif (\method_exists($resource, '__toString')) { |
|
287 | - return self::streamFor((string) $resource, $options); |
|
288 | - } |
|
289 | - break; |
|
290 | - case 'NULL': |
|
291 | - return new Stream(self::tryFopen('php://temp', 'r+'), $options); |
|
292 | - } |
|
293 | - if (\is_callable($resource)) { |
|
294 | - return new PumpStream($resource, $options); |
|
295 | - } |
|
296 | - throw new \InvalidArgumentException('Invalid resource type: ' . \gettype($resource)); |
|
297 | - } |
|
298 | - /** |
|
299 | - * Safely opens a PHP stream resource using a filename. |
|
300 | - * |
|
301 | - * When fopen fails, PHP normally raises a warning. This function adds an |
|
302 | - * error handler that checks for errors and throws an exception instead. |
|
303 | - * |
|
304 | - * @param string $filename File to open |
|
305 | - * @param string $mode Mode used to open the file |
|
306 | - * |
|
307 | - * @return resource |
|
308 | - * |
|
309 | - * @throws \RuntimeException if the file cannot be opened |
|
310 | - */ |
|
311 | - public static function tryFopen(string $filename, string $mode) |
|
312 | - { |
|
313 | - $ex = null; |
|
314 | - \set_error_handler(static function (int $errno, string $errstr) use($filename, $mode, &$ex) : bool { |
|
315 | - $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, $errstr)); |
|
316 | - return \true; |
|
317 | - }); |
|
318 | - try { |
|
319 | - /** @var resource $handle */ |
|
320 | - $handle = \fopen($filename, $mode); |
|
321 | - } catch (\Throwable $e) { |
|
322 | - $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, $e->getMessage()), 0, $e); |
|
323 | - } |
|
324 | - \restore_error_handler(); |
|
325 | - if ($ex) { |
|
326 | - /** @var $ex \RuntimeException */ |
|
327 | - throw $ex; |
|
328 | - } |
|
329 | - return $handle; |
|
330 | - } |
|
331 | - /** |
|
332 | - * Safely gets the contents of a given stream. |
|
333 | - * |
|
334 | - * When stream_get_contents fails, PHP normally raises a warning. This |
|
335 | - * function adds an error handler that checks for errors and throws an |
|
336 | - * exception instead. |
|
337 | - * |
|
338 | - * @param resource $stream |
|
339 | - * |
|
340 | - * @throws \RuntimeException if the stream cannot be read |
|
341 | - */ |
|
342 | - public static function tryGetContents($stream) : string |
|
343 | - { |
|
344 | - $ex = null; |
|
345 | - \set_error_handler(static function (int $errno, string $errstr) use(&$ex) : bool { |
|
346 | - $ex = new \RuntimeException(\sprintf('Unable to read stream contents: %s', $errstr)); |
|
347 | - return \true; |
|
348 | - }); |
|
349 | - try { |
|
350 | - /** @var string|false $contents */ |
|
351 | - $contents = \stream_get_contents($stream); |
|
352 | - if ($contents === \false) { |
|
353 | - $ex = new \RuntimeException('Unable to read stream contents'); |
|
354 | - } |
|
355 | - } catch (\Throwable $e) { |
|
356 | - $ex = new \RuntimeException(\sprintf('Unable to read stream contents: %s', $e->getMessage()), 0, $e); |
|
357 | - } |
|
358 | - \restore_error_handler(); |
|
359 | - if ($ex) { |
|
360 | - /** @var $ex \RuntimeException */ |
|
361 | - throw $ex; |
|
362 | - } |
|
363 | - return $contents; |
|
364 | - } |
|
365 | - /** |
|
366 | - * Returns a UriInterface for the given value. |
|
367 | - * |
|
368 | - * This function accepts a string or UriInterface and returns a |
|
369 | - * UriInterface for the given value. If the value is already a |
|
370 | - * UriInterface, it is returned as-is. |
|
371 | - * |
|
372 | - * @param string|UriInterface $uri |
|
373 | - * |
|
374 | - * @throws \InvalidArgumentException |
|
375 | - */ |
|
376 | - public static function uriFor($uri) : UriInterface |
|
377 | - { |
|
378 | - if ($uri instanceof UriInterface) { |
|
379 | - return $uri; |
|
380 | - } |
|
381 | - if (\is_string($uri)) { |
|
382 | - return new Uri($uri); |
|
383 | - } |
|
384 | - throw new \InvalidArgumentException('URI must be a string or UriInterface'); |
|
385 | - } |
|
265 | + /** @var resource $resource */ |
|
266 | + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { |
|
267 | + $stream = self::tryFopen('php://temp', 'w+'); |
|
268 | + \stream_copy_to_stream($resource, $stream); |
|
269 | + \fseek($stream, 0); |
|
270 | + $resource = $stream; |
|
271 | + } |
|
272 | + return new Stream($resource, $options); |
|
273 | + case 'object': |
|
274 | + /** @var object $resource */ |
|
275 | + if ($resource instanceof StreamInterface) { |
|
276 | + return $resource; |
|
277 | + } elseif ($resource instanceof \Iterator) { |
|
278 | + return new PumpStream(function () use($resource) { |
|
279 | + if (!$resource->valid()) { |
|
280 | + return \false; |
|
281 | + } |
|
282 | + $result = $resource->current(); |
|
283 | + $resource->next(); |
|
284 | + return $result; |
|
285 | + }, $options); |
|
286 | + } elseif (\method_exists($resource, '__toString')) { |
|
287 | + return self::streamFor((string) $resource, $options); |
|
288 | + } |
|
289 | + break; |
|
290 | + case 'NULL': |
|
291 | + return new Stream(self::tryFopen('php://temp', 'r+'), $options); |
|
292 | + } |
|
293 | + if (\is_callable($resource)) { |
|
294 | + return new PumpStream($resource, $options); |
|
295 | + } |
|
296 | + throw new \InvalidArgumentException('Invalid resource type: ' . \gettype($resource)); |
|
297 | + } |
|
298 | + /** |
|
299 | + * Safely opens a PHP stream resource using a filename. |
|
300 | + * |
|
301 | + * When fopen fails, PHP normally raises a warning. This function adds an |
|
302 | + * error handler that checks for errors and throws an exception instead. |
|
303 | + * |
|
304 | + * @param string $filename File to open |
|
305 | + * @param string $mode Mode used to open the file |
|
306 | + * |
|
307 | + * @return resource |
|
308 | + * |
|
309 | + * @throws \RuntimeException if the file cannot be opened |
|
310 | + */ |
|
311 | + public static function tryFopen(string $filename, string $mode) |
|
312 | + { |
|
313 | + $ex = null; |
|
314 | + \set_error_handler(static function (int $errno, string $errstr) use($filename, $mode, &$ex) : bool { |
|
315 | + $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, $errstr)); |
|
316 | + return \true; |
|
317 | + }); |
|
318 | + try { |
|
319 | + /** @var resource $handle */ |
|
320 | + $handle = \fopen($filename, $mode); |
|
321 | + } catch (\Throwable $e) { |
|
322 | + $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, $e->getMessage()), 0, $e); |
|
323 | + } |
|
324 | + \restore_error_handler(); |
|
325 | + if ($ex) { |
|
326 | + /** @var $ex \RuntimeException */ |
|
327 | + throw $ex; |
|
328 | + } |
|
329 | + return $handle; |
|
330 | + } |
|
331 | + /** |
|
332 | + * Safely gets the contents of a given stream. |
|
333 | + * |
|
334 | + * When stream_get_contents fails, PHP normally raises a warning. This |
|
335 | + * function adds an error handler that checks for errors and throws an |
|
336 | + * exception instead. |
|
337 | + * |
|
338 | + * @param resource $stream |
|
339 | + * |
|
340 | + * @throws \RuntimeException if the stream cannot be read |
|
341 | + */ |
|
342 | + public static function tryGetContents($stream) : string |
|
343 | + { |
|
344 | + $ex = null; |
|
345 | + \set_error_handler(static function (int $errno, string $errstr) use(&$ex) : bool { |
|
346 | + $ex = new \RuntimeException(\sprintf('Unable to read stream contents: %s', $errstr)); |
|
347 | + return \true; |
|
348 | + }); |
|
349 | + try { |
|
350 | + /** @var string|false $contents */ |
|
351 | + $contents = \stream_get_contents($stream); |
|
352 | + if ($contents === \false) { |
|
353 | + $ex = new \RuntimeException('Unable to read stream contents'); |
|
354 | + } |
|
355 | + } catch (\Throwable $e) { |
|
356 | + $ex = new \RuntimeException(\sprintf('Unable to read stream contents: %s', $e->getMessage()), 0, $e); |
|
357 | + } |
|
358 | + \restore_error_handler(); |
|
359 | + if ($ex) { |
|
360 | + /** @var $ex \RuntimeException */ |
|
361 | + throw $ex; |
|
362 | + } |
|
363 | + return $contents; |
|
364 | + } |
|
365 | + /** |
|
366 | + * Returns a UriInterface for the given value. |
|
367 | + * |
|
368 | + * This function accepts a string or UriInterface and returns a |
|
369 | + * UriInterface for the given value. If the value is already a |
|
370 | + * UriInterface, it is returned as-is. |
|
371 | + * |
|
372 | + * @param string|UriInterface $uri |
|
373 | + * |
|
374 | + * @throws \InvalidArgumentException |
|
375 | + */ |
|
376 | + public static function uriFor($uri) : UriInterface |
|
377 | + { |
|
378 | + if ($uri instanceof UriInterface) { |
|
379 | + return $uri; |
|
380 | + } |
|
381 | + if (\is_string($uri)) { |
|
382 | + return new Uri($uri); |
|
383 | + } |
|
384 | + throw new \InvalidArgumentException('URI must be a string or UriInterface'); |
|
385 | + } |
|
386 | 386 | } |
@@ -11,135 +11,135 @@ |
||
11 | 11 | */ |
12 | 12 | final class StreamWrapper |
13 | 13 | { |
14 | - /** @var resource */ |
|
15 | - public $context; |
|
16 | - /** @var StreamInterface */ |
|
17 | - private $stream; |
|
18 | - /** @var string r, r+, or w */ |
|
19 | - private $mode; |
|
20 | - /** |
|
21 | - * Returns a resource representing the stream. |
|
22 | - * |
|
23 | - * @param StreamInterface $stream The stream to get a resource for |
|
24 | - * |
|
25 | - * @return resource |
|
26 | - * |
|
27 | - * @throws \InvalidArgumentException if stream is not readable or writable |
|
28 | - */ |
|
29 | - public static function getResource(StreamInterface $stream) |
|
30 | - { |
|
31 | - self::register(); |
|
32 | - if ($stream->isReadable()) { |
|
33 | - $mode = $stream->isWritable() ? 'r+' : 'r'; |
|
34 | - } elseif ($stream->isWritable()) { |
|
35 | - $mode = 'w'; |
|
36 | - } else { |
|
37 | - throw new \InvalidArgumentException('The stream must be readable, ' . 'writable, or both.'); |
|
38 | - } |
|
39 | - return \fopen('guzzle://stream', $mode, \false, self::createStreamContext($stream)); |
|
40 | - } |
|
41 | - /** |
|
42 | - * Creates a stream context that can be used to open a stream as a php stream resource. |
|
43 | - * |
|
44 | - * @return resource |
|
45 | - */ |
|
46 | - public static function createStreamContext(StreamInterface $stream) |
|
47 | - { |
|
48 | - return \stream_context_create(['guzzle' => ['stream' => $stream]]); |
|
49 | - } |
|
50 | - /** |
|
51 | - * Registers the stream wrapper if needed |
|
52 | - */ |
|
53 | - public static function register() : void |
|
54 | - { |
|
55 | - if (!\in_array('guzzle', \stream_get_wrappers())) { |
|
56 | - \stream_wrapper_register('guzzle', __CLASS__); |
|
57 | - } |
|
58 | - } |
|
59 | - public function stream_open(string $path, string $mode, int $options, ?string &$opened_path = null) : bool |
|
60 | - { |
|
61 | - $options = \stream_context_get_options($this->context); |
|
62 | - if (!isset($options['guzzle']['stream'])) { |
|
63 | - return \false; |
|
64 | - } |
|
65 | - $this->mode = $mode; |
|
66 | - $this->stream = $options['guzzle']['stream']; |
|
67 | - return \true; |
|
68 | - } |
|
69 | - public function stream_read(int $count) : string |
|
70 | - { |
|
71 | - return $this->stream->read($count); |
|
72 | - } |
|
73 | - public function stream_write(string $data) : int |
|
74 | - { |
|
75 | - return $this->stream->write($data); |
|
76 | - } |
|
77 | - public function stream_tell() : int |
|
78 | - { |
|
79 | - return $this->stream->tell(); |
|
80 | - } |
|
81 | - public function stream_eof() : bool |
|
82 | - { |
|
83 | - return $this->stream->eof(); |
|
84 | - } |
|
85 | - public function stream_seek(int $offset, int $whence) : bool |
|
86 | - { |
|
87 | - $this->stream->seek($offset, $whence); |
|
88 | - return \true; |
|
89 | - } |
|
90 | - /** |
|
91 | - * @return resource|false |
|
92 | - */ |
|
93 | - public function stream_cast(int $cast_as) |
|
94 | - { |
|
95 | - $stream = clone $this->stream; |
|
96 | - $resource = $stream->detach(); |
|
97 | - return $resource ?? \false; |
|
98 | - } |
|
99 | - /** |
|
100 | - * @return array{ |
|
101 | - * dev: int, |
|
102 | - * ino: int, |
|
103 | - * mode: int, |
|
104 | - * nlink: int, |
|
105 | - * uid: int, |
|
106 | - * gid: int, |
|
107 | - * rdev: int, |
|
108 | - * size: int, |
|
109 | - * atime: int, |
|
110 | - * mtime: int, |
|
111 | - * ctime: int, |
|
112 | - * blksize: int, |
|
113 | - * blocks: int |
|
114 | - * }|false |
|
115 | - */ |
|
116 | - public function stream_stat() |
|
117 | - { |
|
118 | - if ($this->stream->getSize() === null) { |
|
119 | - return \false; |
|
120 | - } |
|
121 | - static $modeMap = ['r' => 33060, 'rb' => 33060, 'r+' => 33206, 'w' => 33188, 'wb' => 33188]; |
|
122 | - return ['dev' => 0, 'ino' => 0, 'mode' => $modeMap[$this->mode], 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => $this->stream->getSize() ?: 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; |
|
123 | - } |
|
124 | - /** |
|
125 | - * @return array{ |
|
126 | - * dev: int, |
|
127 | - * ino: int, |
|
128 | - * mode: int, |
|
129 | - * nlink: int, |
|
130 | - * uid: int, |
|
131 | - * gid: int, |
|
132 | - * rdev: int, |
|
133 | - * size: int, |
|
134 | - * atime: int, |
|
135 | - * mtime: int, |
|
136 | - * ctime: int, |
|
137 | - * blksize: int, |
|
138 | - * blocks: int |
|
139 | - * } |
|
140 | - */ |
|
141 | - public function url_stat(string $path, int $flags) : array |
|
142 | - { |
|
143 | - return ['dev' => 0, 'ino' => 0, 'mode' => 0, 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; |
|
144 | - } |
|
14 | + /** @var resource */ |
|
15 | + public $context; |
|
16 | + /** @var StreamInterface */ |
|
17 | + private $stream; |
|
18 | + /** @var string r, r+, or w */ |
|
19 | + private $mode; |
|
20 | + /** |
|
21 | + * Returns a resource representing the stream. |
|
22 | + * |
|
23 | + * @param StreamInterface $stream The stream to get a resource for |
|
24 | + * |
|
25 | + * @return resource |
|
26 | + * |
|
27 | + * @throws \InvalidArgumentException if stream is not readable or writable |
|
28 | + */ |
|
29 | + public static function getResource(StreamInterface $stream) |
|
30 | + { |
|
31 | + self::register(); |
|
32 | + if ($stream->isReadable()) { |
|
33 | + $mode = $stream->isWritable() ? 'r+' : 'r'; |
|
34 | + } elseif ($stream->isWritable()) { |
|
35 | + $mode = 'w'; |
|
36 | + } else { |
|
37 | + throw new \InvalidArgumentException('The stream must be readable, ' . 'writable, or both.'); |
|
38 | + } |
|
39 | + return \fopen('guzzle://stream', $mode, \false, self::createStreamContext($stream)); |
|
40 | + } |
|
41 | + /** |
|
42 | + * Creates a stream context that can be used to open a stream as a php stream resource. |
|
43 | + * |
|
44 | + * @return resource |
|
45 | + */ |
|
46 | + public static function createStreamContext(StreamInterface $stream) |
|
47 | + { |
|
48 | + return \stream_context_create(['guzzle' => ['stream' => $stream]]); |
|
49 | + } |
|
50 | + /** |
|
51 | + * Registers the stream wrapper if needed |
|
52 | + */ |
|
53 | + public static function register() : void |
|
54 | + { |
|
55 | + if (!\in_array('guzzle', \stream_get_wrappers())) { |
|
56 | + \stream_wrapper_register('guzzle', __CLASS__); |
|
57 | + } |
|
58 | + } |
|
59 | + public function stream_open(string $path, string $mode, int $options, ?string &$opened_path = null) : bool |
|
60 | + { |
|
61 | + $options = \stream_context_get_options($this->context); |
|
62 | + if (!isset($options['guzzle']['stream'])) { |
|
63 | + return \false; |
|
64 | + } |
|
65 | + $this->mode = $mode; |
|
66 | + $this->stream = $options['guzzle']['stream']; |
|
67 | + return \true; |
|
68 | + } |
|
69 | + public function stream_read(int $count) : string |
|
70 | + { |
|
71 | + return $this->stream->read($count); |
|
72 | + } |
|
73 | + public function stream_write(string $data) : int |
|
74 | + { |
|
75 | + return $this->stream->write($data); |
|
76 | + } |
|
77 | + public function stream_tell() : int |
|
78 | + { |
|
79 | + return $this->stream->tell(); |
|
80 | + } |
|
81 | + public function stream_eof() : bool |
|
82 | + { |
|
83 | + return $this->stream->eof(); |
|
84 | + } |
|
85 | + public function stream_seek(int $offset, int $whence) : bool |
|
86 | + { |
|
87 | + $this->stream->seek($offset, $whence); |
|
88 | + return \true; |
|
89 | + } |
|
90 | + /** |
|
91 | + * @return resource|false |
|
92 | + */ |
|
93 | + public function stream_cast(int $cast_as) |
|
94 | + { |
|
95 | + $stream = clone $this->stream; |
|
96 | + $resource = $stream->detach(); |
|
97 | + return $resource ?? \false; |
|
98 | + } |
|
99 | + /** |
|
100 | + * @return array{ |
|
101 | + * dev: int, |
|
102 | + * ino: int, |
|
103 | + * mode: int, |
|
104 | + * nlink: int, |
|
105 | + * uid: int, |
|
106 | + * gid: int, |
|
107 | + * rdev: int, |
|
108 | + * size: int, |
|
109 | + * atime: int, |
|
110 | + * mtime: int, |
|
111 | + * ctime: int, |
|
112 | + * blksize: int, |
|
113 | + * blocks: int |
|
114 | + * }|false |
|
115 | + */ |
|
116 | + public function stream_stat() |
|
117 | + { |
|
118 | + if ($this->stream->getSize() === null) { |
|
119 | + return \false; |
|
120 | + } |
|
121 | + static $modeMap = ['r' => 33060, 'rb' => 33060, 'r+' => 33206, 'w' => 33188, 'wb' => 33188]; |
|
122 | + return ['dev' => 0, 'ino' => 0, 'mode' => $modeMap[$this->mode], 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => $this->stream->getSize() ?: 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; |
|
123 | + } |
|
124 | + /** |
|
125 | + * @return array{ |
|
126 | + * dev: int, |
|
127 | + * ino: int, |
|
128 | + * mode: int, |
|
129 | + * nlink: int, |
|
130 | + * uid: int, |
|
131 | + * gid: int, |
|
132 | + * rdev: int, |
|
133 | + * size: int, |
|
134 | + * atime: int, |
|
135 | + * mtime: int, |
|
136 | + * ctime: int, |
|
137 | + * blksize: int, |
|
138 | + * blocks: int |
|
139 | + * } |
|
140 | + */ |
|
141 | + public function url_stat(string $path, int $flags) : array |
|
142 | + { |
|
143 | + return ['dev' => 0, 'ino' => 0, 'mode' => 0, 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; |
|
144 | + } |
|
145 | 145 | } |
@@ -10,69 +10,69 @@ |
||
10 | 10 | */ |
11 | 11 | class Response implements ResponseInterface |
12 | 12 | { |
13 | - use MessageTrait; |
|
14 | - /** Map of standard HTTP status code/reason phrases */ |
|
15 | - private const PHRASES = [100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required']; |
|
16 | - /** @var string */ |
|
17 | - private $reasonPhrase; |
|
18 | - /** @var int */ |
|
19 | - private $statusCode; |
|
20 | - /** |
|
21 | - * @param int $status Status code |
|
22 | - * @param (string|string[])[] $headers Response headers |
|
23 | - * @param string|resource|StreamInterface|null $body Response body |
|
24 | - * @param string $version Protocol version |
|
25 | - * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) |
|
26 | - */ |
|
27 | - public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', ?string $reason = null) |
|
28 | - { |
|
29 | - $this->assertStatusCodeRange($status); |
|
30 | - $this->statusCode = $status; |
|
31 | - if ($body !== '' && $body !== null) { |
|
32 | - $this->stream = Utils::streamFor($body); |
|
33 | - } |
|
34 | - $this->setHeaders($headers); |
|
35 | - if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { |
|
36 | - $this->reasonPhrase = self::PHRASES[$this->statusCode]; |
|
37 | - } else { |
|
38 | - $this->reasonPhrase = (string) $reason; |
|
39 | - } |
|
40 | - $this->protocol = $version; |
|
41 | - } |
|
42 | - public function getStatusCode() : int |
|
43 | - { |
|
44 | - return $this->statusCode; |
|
45 | - } |
|
46 | - public function getReasonPhrase() : string |
|
47 | - { |
|
48 | - return $this->reasonPhrase; |
|
49 | - } |
|
50 | - public function withStatus($code, $reasonPhrase = '') : ResponseInterface |
|
51 | - { |
|
52 | - $this->assertStatusCodeIsInteger($code); |
|
53 | - $code = (int) $code; |
|
54 | - $this->assertStatusCodeRange($code); |
|
55 | - $new = clone $this; |
|
56 | - $new->statusCode = $code; |
|
57 | - if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { |
|
58 | - $reasonPhrase = self::PHRASES[$new->statusCode]; |
|
59 | - } |
|
60 | - $new->reasonPhrase = (string) $reasonPhrase; |
|
61 | - return $new; |
|
62 | - } |
|
63 | - /** |
|
64 | - * @param mixed $statusCode |
|
65 | - */ |
|
66 | - private function assertStatusCodeIsInteger($statusCode) : void |
|
67 | - { |
|
68 | - if (\filter_var($statusCode, \FILTER_VALIDATE_INT) === \false) { |
|
69 | - throw new \InvalidArgumentException('Status code must be an integer value.'); |
|
70 | - } |
|
71 | - } |
|
72 | - private function assertStatusCodeRange(int $statusCode) : void |
|
73 | - { |
|
74 | - if ($statusCode < 100 || $statusCode >= 600) { |
|
75 | - throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); |
|
76 | - } |
|
77 | - } |
|
13 | + use MessageTrait; |
|
14 | + /** Map of standard HTTP status code/reason phrases */ |
|
15 | + private const PHRASES = [100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required']; |
|
16 | + /** @var string */ |
|
17 | + private $reasonPhrase; |
|
18 | + /** @var int */ |
|
19 | + private $statusCode; |
|
20 | + /** |
|
21 | + * @param int $status Status code |
|
22 | + * @param (string|string[])[] $headers Response headers |
|
23 | + * @param string|resource|StreamInterface|null $body Response body |
|
24 | + * @param string $version Protocol version |
|
25 | + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) |
|
26 | + */ |
|
27 | + public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', ?string $reason = null) |
|
28 | + { |
|
29 | + $this->assertStatusCodeRange($status); |
|
30 | + $this->statusCode = $status; |
|
31 | + if ($body !== '' && $body !== null) { |
|
32 | + $this->stream = Utils::streamFor($body); |
|
33 | + } |
|
34 | + $this->setHeaders($headers); |
|
35 | + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { |
|
36 | + $this->reasonPhrase = self::PHRASES[$this->statusCode]; |
|
37 | + } else { |
|
38 | + $this->reasonPhrase = (string) $reason; |
|
39 | + } |
|
40 | + $this->protocol = $version; |
|
41 | + } |
|
42 | + public function getStatusCode() : int |
|
43 | + { |
|
44 | + return $this->statusCode; |
|
45 | + } |
|
46 | + public function getReasonPhrase() : string |
|
47 | + { |
|
48 | + return $this->reasonPhrase; |
|
49 | + } |
|
50 | + public function withStatus($code, $reasonPhrase = '') : ResponseInterface |
|
51 | + { |
|
52 | + $this->assertStatusCodeIsInteger($code); |
|
53 | + $code = (int) $code; |
|
54 | + $this->assertStatusCodeRange($code); |
|
55 | + $new = clone $this; |
|
56 | + $new->statusCode = $code; |
|
57 | + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { |
|
58 | + $reasonPhrase = self::PHRASES[$new->statusCode]; |
|
59 | + } |
|
60 | + $new->reasonPhrase = (string) $reasonPhrase; |
|
61 | + return $new; |
|
62 | + } |
|
63 | + /** |
|
64 | + * @param mixed $statusCode |
|
65 | + */ |
|
66 | + private function assertStatusCodeIsInteger($statusCode) : void |
|
67 | + { |
|
68 | + if (\filter_var($statusCode, \FILTER_VALIDATE_INT) === \false) { |
|
69 | + throw new \InvalidArgumentException('Status code must be an integer value.'); |
|
70 | + } |
|
71 | + } |
|
72 | + private function assertStatusCodeRange(int $statusCode) : void |
|
73 | + { |
|
74 | + if ($statusCode < 100 || $statusCode >= 600) { |
|
75 | + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); |
|
76 | + } |
|
77 | + } |
|
78 | 78 | } |