-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientBuilder.php
More file actions
93 lines (75 loc) · 2.46 KB
/
ClientBuilder.php
File metadata and controls
93 lines (75 loc) · 2.46 KB
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
<?php
namespace ProgrammatorDev\Api\Builder;
use Http\Client\Common\HttpMethodsClient;
use Http\Client\Common\Plugin;
use Http\Client\Common\PluginClientFactory;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use ProgrammatorDev\Api\Exception\PluginException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
class ClientBuilder
{
/** @var Plugin[] */
private array $plugins = [];
public function __construct(
private ?ClientInterface $client = null,
private ?RequestFactoryInterface $requestFactory = null,
private ?StreamFactoryInterface $streamFactory = null
)
{
$this->client ??= Psr18ClientDiscovery::find();
$this->requestFactory ??= Psr17FactoryDiscovery::findRequestFactory();
$this->streamFactory ??= Psr17FactoryDiscovery::findStreamFactory();
}
public function getClient(): HttpMethodsClient
{
$pluginClientFactory = new PluginClientFactory();
$client = $pluginClientFactory->createClient($this->client, $this->plugins);
return new HttpMethodsClient(
$client,
$this->requestFactory,
$this->streamFactory
);
}
public function setClient(ClientInterface $client): self
{
$this->client = $client;
return $this;
}
public function getRequestFactory(): RequestFactoryInterface
{
return $this->requestFactory;
}
public function setRequestFactory(RequestFactoryInterface $requestFactory): self
{
$this->requestFactory = $requestFactory;
return $this;
}
public function getStreamFactory(): StreamFactoryInterface
{
return $this->streamFactory;
}
public function setStreamFactory(StreamFactoryInterface $streamFactory): self
{
$this->streamFactory = $streamFactory;
return $this;
}
public function addPlugin(Plugin $plugin, int $priority): self
{
if (isset($this->plugins[$priority])) {
throw new PluginException(
sprintf('A plugin with priority %d already exists.', $priority)
);
}
$this->plugins[$priority] = $plugin;
// sort plugins by priority (key) in descending order
krsort($this->plugins);
return $this;
}
public function getPlugins(): array
{
return $this->plugins;
}
}