Skip to content

Commit 0a563ca

Browse files
committed
Add plugin client builder
1 parent f9f44c6 commit 0a563ca

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/PluginClientBuilder.php

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

0 commit comments

Comments
 (0)