Skip to content

Commit be88c95

Browse files
committed
Add plugin client builder
1 parent f9f44c6 commit be88c95

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/PluginClientBuilder.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
* @author Baptiste Clavié <clavie.b@gmail.com>
15+
*/
16+
final class PluginClientBuilder
17+
{
18+
/** @var Plugin[][] */
19+
private $plugins = [];
20+
21+
public function addPlugin(Plugin $plugin, int $priority = 0): self
22+
{
23+
$this->plugins[$priority][] = $plugin;
24+
25+
return $this;
26+
}
27+
28+
public function createClient($client, array $options = []): PluginClient
29+
{
30+
if (!$client instanceof ClientInterface && !$client instanceof HttpClient && !$client instanceof HttpAsyncClient) {
31+
throw new \RuntimeException('You must provide a valid http client');
32+
}
33+
34+
$plugins = $this->plugins;
35+
36+
if (count($plugins) > 0) {
37+
krsort($plugins);
38+
$plugins = array_merge(...$plugins);
39+
}
40+
41+
return new PluginClient(
42+
$client,
43+
array_values($plugins),
44+
$options
45+
);
46+
}
47+
}

0 commit comments

Comments
 (0)