1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace EasyHttp\MockBuilder\ResponseBuilders; |
4
|
|
|
|
5
|
|
|
use EasyHttp\MockBuilder\Contracts\ResponseBuilder; |
6
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
7
|
|
|
use GuzzleHttp\Psr7\Response; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
|
10
|
|
|
class GuzzleResponseBuilder implements ResponseBuilder |
11
|
|
|
{ |
12
|
|
|
private int $statusCode = 200; |
13
|
|
|
private array $headers = []; |
14
|
|
|
private string $body = ''; |
15
|
|
|
private $bodyHandler; |
16
|
|
|
private array $json = []; |
17
|
|
|
private ?RequestInterface $request; |
18
|
|
|
|
19
|
56 |
|
public function setRequest(?RequestInterface $request = null) |
20
|
|
|
{ |
21
|
56 |
|
$this->request = $request; |
22
|
|
|
} |
23
|
|
|
|
24
|
6 |
|
public function statusCode(int $statusCode): self |
25
|
|
|
{ |
26
|
6 |
|
$this->statusCode = $statusCode; |
27
|
|
|
|
28
|
6 |
|
return $this; |
29
|
|
|
} |
30
|
|
|
|
31
|
1 |
|
public function getStatusCode(): int |
32
|
|
|
{ |
33
|
1 |
|
return $this->statusCode; |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
public function headers(array $headers): self |
37
|
|
|
{ |
38
|
2 |
|
$this->headers = $headers; |
39
|
|
|
|
40
|
2 |
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
public function getHeaders(): array |
44
|
|
|
{ |
45
|
1 |
|
return $this->headers; |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
public function getBody(): string |
49
|
|
|
{ |
50
|
2 |
|
return $this->body; |
51
|
|
|
} |
52
|
|
|
|
53
|
118 |
|
public function body($body): self |
54
|
|
|
{ |
55
|
118 |
|
$this->json = []; |
56
|
118 |
|
$this->body = ''; |
57
|
118 |
|
$this->bodyHandler = null; |
58
|
|
|
|
59
|
118 |
|
if (is_callable($body)) { |
60
|
1 |
|
$this->bodyHandler = $body; |
61
|
|
|
} |
62
|
|
|
|
63
|
118 |
|
if (is_string($body)) { |
64
|
117 |
|
$this->body = $body; |
65
|
|
|
} |
66
|
|
|
|
67
|
118 |
|
return $this; |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
public function getJson(): array |
71
|
|
|
{ |
72
|
2 |
|
return $this->json; |
73
|
|
|
} |
74
|
|
|
|
75
|
3 |
|
public function json(array $json): self |
76
|
|
|
{ |
77
|
3 |
|
$this->body = ''; |
78
|
3 |
|
$this->json = $json; |
79
|
|
|
|
80
|
3 |
|
return $this; |
81
|
|
|
} |
82
|
|
|
|
83
|
56 |
|
public function response(): FulfilledPromise |
84
|
|
|
{ |
85
|
56 |
|
$body = ''; |
86
|
|
|
|
87
|
56 |
|
if ($this->bodyHandler) { |
88
|
1 |
|
$clousure = $this->bodyHandler; |
89
|
1 |
|
$body = $clousure($this->request); |
90
|
55 |
|
} elseif (!empty($this->json)) { |
91
|
1 |
|
$body = json_encode($this->json, true); |
|
|
|
|
92
|
54 |
|
} elseif (!empty($this->body)) { |
93
|
50 |
|
$body = $this->body; |
94
|
|
|
} |
95
|
|
|
|
96
|
56 |
|
return new FulfilledPromise( |
97
|
56 |
|
new Response($this->statusCode, $this->headers, $body) |
98
|
|
|
); |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|