1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace DanBettles\Defence\Tests\TestsFactory; |
6
|
|
|
|
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
8
|
|
|
|
9
|
|
|
use function array_key_exists; |
10
|
|
|
use function is_array; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @phpstan-type Headers array<string,string> |
14
|
|
|
* @phpstan-type InputBagValue mixed[]|bool|float|int|string|null |
15
|
|
|
* @phpstan-type RequestParameters array<string,InputBagValue> |
16
|
|
|
* @phpstan-type CreateOptions array{method?:string,headers?:Headers,query?:RequestParameters,body?:RequestParameters} |
17
|
|
|
*/ |
18
|
|
|
class RequestFactory |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Creates a `GET` request by default |
22
|
|
|
* |
23
|
|
|
* @phpstan-param CreateOptions $options |
24
|
|
|
*/ |
25
|
|
|
public function create(array $options): Request |
26
|
|
|
{ |
27
|
|
|
$request = new Request(); |
28
|
|
|
$request->setMethod($options['method'] ?? Request::METHOD_GET); |
29
|
|
|
|
30
|
|
|
if (array_key_exists('headers', $options)) { |
31
|
|
|
foreach ($options['headers'] as $name => $value) { |
32
|
|
|
$request->headers->set($name, $value); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (array_key_exists('query', $options)) { |
37
|
|
|
foreach ($options['query'] as $name => $value) { |
38
|
|
|
$request->query->set($name, $value); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if (array_key_exists('body', $options)) { |
43
|
|
|
$body = $options['body']; |
44
|
|
|
|
45
|
|
|
if (is_array($body)) { |
46
|
|
|
foreach ($body as $name => $value) { |
47
|
|
|
$request->request->set($name, $value); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $request; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Creates a `GET` request |
57
|
|
|
* |
58
|
|
|
* @phpstan-param Headers $headers |
59
|
|
|
*/ |
60
|
|
|
public function createWithHeaders(array $headers): Request |
61
|
|
|
{ |
62
|
|
|
return $this->create(['headers' => $headers]); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @phpstan-param RequestParameters $parameters |
67
|
|
|
*/ |
68
|
|
|
public function createPost(array $parameters = []): Request |
69
|
|
|
{ |
70
|
|
|
return $this->create([ |
71
|
|
|
'method' => Request::METHOD_POST, |
72
|
|
|
'body' => $parameters, |
73
|
|
|
]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @phpstan-param RequestParameters $parameters |
78
|
|
|
*/ |
79
|
|
|
public function createGet(array $parameters = []): Request |
80
|
|
|
{ |
81
|
|
|
return $this->create([ |
82
|
|
|
'method' => Request::METHOD_GET, |
83
|
|
|
'query' => $parameters, |
84
|
|
|
]); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|