PluginClientBuilder.php 1.8 KB

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