Skip to content

Commit 3358fa6

Browse files
committed
Add plugin client builder
1 parent f9f44c6 commit 3358fa6

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/PluginClientBuilder.php

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

0 commit comments

Comments
 (0)