Skip to content

Commit 021b245

Browse files
committed
Add plugin client builder
1 parent f9f44c6 commit 021b245

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

src/PluginClientBuilder.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Http\Client\Common;
6+
7+
use Http\Client\HttpAsyncClient;
8+
use Psr\Http\Client\ClientInterface;
9+
10+
/**
11+
* Build an instance of a PluginClient with a dynamic list of plugins.
12+
*
13+
* @author Baptiste Clavié <clavie.b@gmail.com>
14+
*/
15+
final class PluginClientBuilder
16+
{
17+
/** @var Plugin[][] List of plugins ordered by priority [priority => Plugin[]]). */
18+
private $plugins = [];
19+
20+
/** @var array Array of options to give to the plugin client */
21+
private $options = [];
22+
23+
/**
24+
* @param int $priority Priority of the plugin. The higher comes first.
25+
*/
26+
public function addPlugin(Plugin $plugin, int $priority = 0): self
27+
{
28+
$this->plugins[$priority][] = $plugin;
29+
30+
return $this;
31+
}
32+
33+
public function setOption(string $name, $value): self
34+
{
35+
$this->options[$name] = $value;
36+
37+
return $this;
38+
}
39+
40+
public function removeOption(string $name): self
41+
{
42+
unset($this->options[$name]);
43+
44+
return $this;
45+
}
46+
47+
/**
48+
* @param ClientInterface | HttpAsyncClient $client
49+
*/
50+
public function createClient($client): PluginClient
51+
{
52+
if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) {
53+
throw new \RuntimeException('You must provide a valid http client');
54+
}
55+
56+
$plugins = $this->plugins;
57+
58+
if (0 === count($plugins)) {
59+
$plugins[] = [];
60+
}
61+
62+
krsort($plugins);
63+
$plugins = array_merge(...$plugins);
64+
65+
return new PluginClient(
66+
$client,
67+
array_values($plugins),
68+
$this->options
69+
);
70+
}
71+
}

0 commit comments

Comments
 (0)