-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathClient.php
255 lines (220 loc) · 7.59 KB
/
Client.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<?php
namespace Http\Mock;
use Http\Client\Common\HttpAsyncClientEmulator;
use Http\Client\Exception;
use Http\Client\HttpAsyncClient;
use Http\Client\HttpClient;
use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Message\RequestMatcher;
use Http\Message\ResponseFactory;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
/**
* An implementation of the HTTP client that is useful for automated tests.
*
* This mock does not send requests but stores them for later retrieval.
* You can configure the mock with responses to return and/or exceptions to throw.
*
* @author David de Boer <david@ddeboer.nl>
*/
class Client implements HttpClient, HttpAsyncClient
{
use HttpAsyncClientEmulator;
/**
* @var ResponseFactory|ResponseFactoryInterface
*/
private $responseFactory;
/**
* @var array
*/
private $conditionalResults = [];
/**
* @var RequestInterface[]
*/
private $requests = [];
/**
* @var ResponseInterface[]
*/
private $responses = [];
/**
* @var ResponseInterface|null
*/
private $defaultResponse;
/**
* @var Exception[]
*/
private $exceptions = [];
/**
* @var Exception|null
*/
private $defaultException;
/**
* @param ResponseFactory|ResponseFactoryInterface|null
*/
public function __construct($responseFactory = null)
{
if (!$responseFactory instanceof ResponseFactory && !$responseFactory instanceof ResponseFactoryInterface && null !== $responseFactory) {
throw new \TypeError(
sprintf('%s::__construct(): Argument #1 ($responseFactory) must be of type %s|%s|null, %s given', self::class, ResponseFactory::class, ResponseFactoryInterface::class, get_debug_type($responseFactory))
);
}
if ($responseFactory) {
$this->responseFactory = $responseFactory;
return;
}
try {
$this->responseFactory = Psr17FactoryDiscovery::findResponseFactory();
} catch (NotFoundException $notFoundException) {
try {
$this->responseFactory = MessageFactoryDiscovery::find();
} catch (NotFoundException $e) {
// throw the psr-17 exception to make people install the new way and not the old
throw $notFoundException;
}
}
}
/**
* Respond with the prepared behaviour, in the following order.
*
* - Throw the next exception in the list and advance
* - Return the next response in the list and advance
* - Throw the default exception if set (forever)
* - Return the default response if set (forever)
* - Create a new empty response with the response factory
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$this->requests[] = $request;
foreach ($this->conditionalResults as $result) {
/**
* @var RequestMatcher
*/
$matcher = $result['matcher'];
/**
* @var callable
*/
$callable = $result['callable'];
if ($matcher->matches($request)) {
return $callable($request);
}
}
if (count($this->exceptions) > 0) {
throw array_shift($this->exceptions);
}
if (count($this->responses) > 0) {
return array_shift($this->responses);
}
if ($this->defaultException) {
throw $this->defaultException;
}
if ($this->defaultResponse) {
return $this->defaultResponse;
}
// Return success response by default
return $this->responseFactory->createResponse();
}
/**
* Adds an exception to be thrown or response to be returned if the request
* matcher matches.
*
* For more complex logic, pass a callable as $result. The method is given
* the request and MUST either return a ResponseInterface or throw an
* exception that implements the PSR-18 / HTTPlug exception interface.
*
* @param ResponseInterface|Exception|ClientExceptionInterface|callable $result
*/
public function on(RequestMatcher $requestMatcher, $result)
{
if (!$result instanceof ResponseInterface && !$result instanceof Exception && !$result instanceof ClientExceptionInterface && !is_callable($result)) {
throw new \TypeError(
sprintf('%s::on(): Argument #2 ($result) must be of type %s|%s|%s|callable, %s given', self::class, ResponseInterface::class, Exception::class, ClientExceptionInterface::class, get_debug_type($result))
);
}
$callable = self::makeCallable($result);
$this->conditionalResults[] = [
'matcher' => $requestMatcher,
'callable' => $callable,
];
}
/**
* @param ResponseInterface|Exception|ClientExceptionInterface|callable $result
*
* @return callable
*/
private static function makeCallable($result)
{
if (is_callable($result)) {
return $result;
}
if ($result instanceof ResponseInterface) {
return function () use ($result) {
return $result;
};
}
return function () use ($result) {
throw $result;
};
}
/**
* Adds an exception that will be thrown.
*/
public function addException(\Exception $exception)
{
if (!$exception instanceof Exception) {
@trigger_error('Clients may only throw exceptions of type '.Exception::class.'. Setting an exception of class '.get_class($exception).' will not be possible anymore in the future', E_USER_DEPRECATED);
}
$this->exceptions[] = $exception;
}
/**
* Sets the default exception to throw when the list of added exceptions and responses is exhausted.
*
* If both a default exception and a default response are set, the exception will be thrown.
*/
public function setDefaultException(?\Exception $defaultException = null)
{
if (null !== $defaultException && !$defaultException instanceof Exception) {
@trigger_error('Clients may only throw exceptions of type '.Exception::class.'. Setting an exception of class '.get_class($defaultException).' will not be possible anymore in the future', E_USER_DEPRECATED);
}
$this->defaultException = $defaultException;
}
/**
* Adds a response that will be returned in first in first out order.
*/
public function addResponse(ResponseInterface $response)
{
$this->responses[] = $response;
}
/**
* Sets the default response to be returned when the list of added exceptions and responses is exhausted.
*/
public function setDefaultResponse(?ResponseInterface $defaultResponse = null)
{
$this->defaultResponse = $defaultResponse;
}
/**
* Returns requests that were sent.
*
* @return RequestInterface[]
*/
public function getRequests()
{
return $this->requests;
}
public function getLastRequest()
{
return end($this->requests);
}
public function reset()
{
$this->conditionalResults = [];
$this->responses = [];
$this->exceptions = [];
$this->requests = [];
$this->setDefaultException();
$this->setDefaultResponse();
}
}