Skip to content

Commit 3edf370

Browse files
committed
Add plugin client builder
1 parent f9f44c6 commit 3edf370

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/PluginClientBuilder.php

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Http\Client\Common;
6+
7+
use Psr\Http\Client\ClientInterface;
8+
9+
use Http\Client\HttpClient;
10+
use Http\Client\HttpAsyncClient;
11+
12+
/**
13+
* Build an instance of a PluginClient with a dynamic list of plugins.
14+
*
15+
* This builder is immutable, each "build" methods will instead create a new
16+
* instance of itself with or without the affected plugin, destroying a
17+
* potentially http client built in the new instance.
18+
*
19+
* @author Baptiste Clavié <[email protected]>
20+
*/
21+
final class PluginClientBuilder
22+
{
23+
/** @var Plugin[] */
24+
private $plugins = [];
25+
26+
/** @var ?PluginClient */
27+
private $client;
28+
29+
public function addPlugin(Plugin $plugin): self
30+
{
31+
$builder = new self();
32+
33+
$builder->client = null;
34+
$builder->plugins = $this->plugins;
35+
$builder->plugins[get_class($plugin)] = $plugin;
36+
37+
return $builder;
38+
}
39+
40+
public function removePlugin(string $fqcn): self
41+
{
42+
$builder = new self();
43+
44+
$builder->client = null;
45+
$builder->plugins = $this->plugins;
46+
unset($builder->plugins[$fqcn]);
47+
48+
return $builder;
49+
}
50+
51+
/**
52+
* @param ClientInterface | HttpClient | HttpAsyncClient $client Client to nest into the plugin client
53+
*/
54+
public function createClient($client, array $options = []): PluginClient
55+
{
56+
if (!$client instanceof ClientInterface && !$client instanceof HttpClient && !$client instanceof HttpAsyncClient) {
57+
throw new \RuntimeException('You must provide a valid http client');
58+
}
59+
60+
if (null === $this->client) {
61+
$this->client = new PluginClient(
62+
$client,
63+
array_values($this->plugins),
64+
$options
65+
);
66+
}
67+
68+
return $this->client;
69+
}
70+
}

0 commit comments

Comments
 (0)