-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientRequest.php
193 lines (170 loc) · 5.68 KB
/
ClientRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <[email protected]>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*
*/
namespace Koded\Http;
use Koded\Http\Interfaces\{HttpStatus, Request, Response};
use Psr\Http\Message\{RequestInterface, UriInterface};
use function Koded\Stdlib\json_serialize;
class ClientRequest implements RequestInterface, \JsonSerializable
{
use HeaderTrait, MessageTrait, JsonSerializeTrait;
const E_INVALID_REQUEST_TARGET = 'The request target is invalid, it contains whitespaces';
const E_SAFE_METHODS_WITH_BODY = 'failed to open stream: you should not set the message body with safe HTTP methods';
protected UriInterface $uri;
protected string $method = Request::GET;
protected string $requestTarget = '';
/**
* ClientRequest constructor.
*
* If body is provided, the content internally is encoded in JSON
* and stored in body Stream object.
*
* @param string $method
* @param UriInterface|string $uri
* @param mixed $body [optional] \Psr\Http\Message\StreamInterface|iterable|resource|callable|string|null
* @param array $headers [optional]
*/
public function __construct(
string $method,
string|UriInterface $uri,
string|iterable $body = null,
array $headers = [])
{
$this->uri = $uri instanceof UriInterface ? $uri : new Uri($uri);
$this->stream = create_stream($this->prepareBody($body));
$this->setHost();
$this->setMethod($method, $this);
$this->setHeaders($headers);
}
public function getMethod(): string
{
return \strtoupper($this->method);
}
public function withMethod($method): ClientRequest
{
return $this->setMethod($method, clone $this);
}
public function getUri(): UriInterface
{
return $this->uri;
}
public function withUri(UriInterface $uri, $preserveHost = false): static
{
$instance = clone $this;
$instance->uri = $uri;
if (true === $preserveHost) {
return $instance->withHeader('Host', $this->uri->getHost() ?: $uri->getHost());
}
return $instance->withHeader('Host', $uri->getHost());
}
public function getRequestTarget(): string
{
if ($this->requestTarget) {
return $this->requestTarget;
}
if (!$path = $this->uri->getPath()) {
return '/';
}
if ($query = $this->uri->getQuery()) {
$path .= '?' . $query;
}
return $path;
}
public function withRequestTarget($requestTarget): static
{
if (\preg_match('/\s+/', $requestTarget)) {
throw new \InvalidArgumentException(
self::E_INVALID_REQUEST_TARGET,
HttpStatus::BAD_REQUEST);
}
$instance = clone $this;
$instance->requestTarget = $requestTarget;
return $instance;
}
public function getPath(): string
{
return \str_replace($_SERVER['SCRIPT_NAME'], '', $this->uri->getPath()) ?: '/';
}
public function getBaseUri(): string
{
if (false === empty($host = $this->getUri()->getHost())) {
$port = $this->getUri()->getPort();
$port && $port = ":{$port}";
return $this->getUri()->getScheme() . "://{$host}{$port}";
}
return '';
}
public function isSecure(): bool
{
return 'https' === $this->uri->getScheme();
}
public function isSafeMethod(): bool
{
return \in_array($this->method, Request::SAFE_METHODS);
}
protected function setHost(): void
{
$this->headersMap['host'] = 'Host';
$this->headers = ['Host' => $this->uri->getHost() ?: $_SERVER['HTTP_HOST'] ?? ''] + $this->headers;
}
/**
* @param string $method The HTTP method
* @param RequestInterface $instance
*
* @return static
*/
protected function setMethod(string $method, RequestInterface $instance): RequestInterface
{
$instance->method = \strtoupper($method);
return $instance;
}
/**
* Checks if body is non-empty if HTTP method is one of the *safe* methods.
* The consuming code may disallow this and return the response object.
*
* @return Response|null
*/
protected function assertSafeMethod(): ?Response
{
if ($this->isSafeMethod() && $this->getBody()->getSize() > 0) {
return $this->getPhpError(HttpStatus::BAD_REQUEST, self::E_SAFE_METHODS_WITH_BODY);
}
return null;
}
/**
* @param mixed $body
*
* @return mixed If $body is iterable returns JSON stringified body, or whatever it is
*/
protected function prepareBody(mixed $body): mixed
{
if (\is_iterable($body)) {
return json_serialize($body);
}
return $body;
}
/**
* @param int $status
* @param string|null $message
*
* @return Response JSON error message
* @link https://tools.ietf.org/html/rfc7807
*/
protected function getPhpError(int $status, ?string $message = null): Response
{
return new ServerResponse(json_serialize([
'title' => HttpStatus::CODE[$status],
'detail' => $message ?? \error_get_last()['message'] ?? HttpStatus::CODE[$status],
'instance' => (string)$this->getUri(),
'type' => 'https://httpstatuses.com/' . $status,
'status' => $status,
]), $status, ['Content-Type' => 'application/problem+json']);
}
}