1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace EasyHttp\LayerContracts; |
4
|
|
|
|
5
|
|
|
use EasyHttp\LayerContracts\Contracts\EasyClientContract; |
6
|
|
|
use EasyHttp\LayerContracts\Contracts\HttpClientAdapter; |
7
|
|
|
use EasyHttp\LayerContracts\Contracts\HttpClientRequest; |
8
|
|
|
use EasyHttp\LayerContracts\Contracts\HttpClientResponse; |
9
|
|
|
|
10
|
|
|
abstract class AbstractClient implements EasyClientContract |
11
|
|
|
{ |
12
|
|
|
protected HttpClientAdapter $adapter; |
13
|
|
|
|
14
|
|
|
protected HttpClientRequest $request; |
15
|
|
|
|
16
|
|
|
protected $handler; |
17
|
|
|
|
18
|
1 |
|
public function getRequest(): HttpClientRequest |
19
|
|
|
{ |
20
|
1 |
|
return $this->request; |
21
|
|
|
} |
22
|
|
|
|
23
|
4 |
|
public function call(string $method, string $uri): HttpClientResponse |
24
|
|
|
{ |
25
|
4 |
|
$request = $this->buildRequest($method, $uri); |
26
|
4 |
|
return $this->getAdapter()->request($request); |
27
|
|
|
} |
28
|
|
|
|
29
|
2 |
|
public function prepareRequest(string $method, string $uri): self |
30
|
|
|
{ |
31
|
2 |
|
$this->request = $this->buildRequest($method, $uri); |
32
|
|
|
|
33
|
2 |
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
public function withHandler(callable $handler): self |
37
|
|
|
{ |
38
|
2 |
|
$this->flushAdapter(); |
39
|
2 |
|
$this->handler = $handler; |
40
|
|
|
|
41
|
2 |
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
public function execute(): HttpClientResponse |
45
|
|
|
{ |
46
|
1 |
|
return $this->getAdapter()->request($this->request); |
47
|
|
|
} |
48
|
|
|
|
49
|
5 |
|
protected function getAdapter(): HttpClientAdapter |
50
|
|
|
{ |
51
|
5 |
|
if ($this->hasAdapter()) { |
52
|
1 |
|
return $this->adapter; |
53
|
|
|
} |
54
|
|
|
|
55
|
5 |
|
$this->adapter = $this->buildAdapter(); |
56
|
|
|
|
57
|
5 |
|
return $this->adapter; |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
protected function hasAdapter(): bool |
61
|
|
|
{ |
62
|
5 |
|
return (bool) ($this->adapter ?? null); |
63
|
|
|
} |
64
|
|
|
|
65
|
5 |
|
protected function hasHandler(): bool |
66
|
|
|
{ |
67
|
5 |
|
return (bool) ($this->handler ?? null); |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
protected function flushAdapter(): void |
71
|
|
|
{ |
72
|
2 |
|
unset($this->adapter); |
73
|
2 |
|
} |
74
|
|
|
|
75
|
|
|
abstract protected function buildRequest(string $method, string $uri): HttpClientRequest; |
76
|
|
|
abstract protected function buildAdapter(): HttpClientAdapter; |
77
|
|
|
} |
78
|
|
|
|