| 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 |
/** |
| 34 |
* @param mixed $value |
| 35 |
*/ |
| 36 |
public function setOption(string $name, $value): self |
| 37 |
{ |
| 38 |
$this->options[$name] = $value; |
| 39 |
|
| 40 |
return $this; |
| 41 |
} |
| 42 |
|
| 43 |
public function removeOption(string $name): self |
| 44 |
{ |
| 45 |
unset($this->options[$name]); |
| 46 |
|
| 47 |
return $this; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* @param ClientInterface|HttpAsyncClient $client |
| 52 |
*/ |
| 53 |
public function createClient($client): PluginClient |
| 54 |
{ |
| 55 |
if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) { |
| 56 |
throw new \TypeError( |
| 57 |
sprintf('%s::createClient(): Argument #1 ($client) must be of type %s|%s, %s given', self::class, ClientInterface::class, HttpAsyncClient::class, get_debug_type($client)) |
| 58 |
); |
| 59 |
} |
| 60 |
|
| 61 |
$plugins = $this->plugins; |
| 62 |
|
| 63 |
if (0 === count($plugins)) { |
| 64 |
$plugins[] = []; |
| 65 |
} |
| 66 |
|
| 67 |
krsort($plugins); |
| 68 |
$plugins = array_merge(...$plugins); |
| 69 |
|
| 70 |
return new PluginClient( |
| 71 |
$client, |
| 72 |
array_values($plugins), |
| 73 |
$this->options |
| 74 |
); |
| 75 |
} |
| 76 |
} |
| 77 |
|