|
| 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 ClientInterface | HttpClient | HttpAsyncClient */ |
| 26 | + private $client; |
| 27 | + |
| 28 | + /** @var ?PluginClient */ |
| 29 | + private $pluginClient; |
| 30 | + |
| 31 | + /** |
| 32 | + * @param ClientInterface | HttpClient | HttpAsyncClient $client Client to nest into the plugin client |
| 33 | + */ |
| 34 | + public function __construct($client) |
| 35 | + { |
| 36 | + if (!$client instanceof ClientInterface && !$client instanceof HttpClient && !$client instanceof HttpAsyncClient) { |
| 37 | + throw new \RuntimeException('You must provide a valid http client'); |
| 38 | + } |
| 39 | + |
| 40 | + $this->client = $client; |
| 41 | + } |
| 42 | + |
| 43 | + public function addPlugin(string $name, Plugin $plugin): self |
| 44 | + { |
| 45 | + $builder = new self($this->client); |
| 46 | + |
| 47 | + $builder->pluginClient = null; |
| 48 | + $builder->plugins = $this->plugins; |
| 49 | + $builder->plugins[$name] = $plugin; |
| 50 | + |
| 51 | + return $builder; |
| 52 | + } |
| 53 | + |
| 54 | + public function removePlugin(string $name): self |
| 55 | + { |
| 56 | + $builder = new self($this->client); |
| 57 | + |
| 58 | + $builder->pluginClient = null; |
| 59 | + $builder->plugins = $this->plugins; |
| 60 | + unset($builder->plugins[$name]); |
| 61 | + |
| 62 | + return $builder; |
| 63 | + } |
| 64 | + |
| 65 | + public function createClient(array $options = []): PluginClient |
| 66 | + { |
| 67 | + if (null === $this->pluginClient) { |
| 68 | + $this->pluginClient = new PluginClient( |
| 69 | + $this->client, |
| 70 | + array_values($this->plugins), |
| 71 | + $options |
| 72 | + ); |
| 73 | + } |
| 74 | + |
| 75 | + return $this->pluginClient; |
| 76 | + } |
| 77 | +} |
0 commit comments