| 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 |
* Factory to create PluginClient instances. Using this factory instead of calling PluginClient constructor will enable |
| 12 |
* the Symfony profiling without any configuration. |
| 13 |
* |
| 14 |
* @author Fabien Bourigault <bourigaultfabien@gmail.com> |
| 15 |
*/ |
| 16 |
final class PluginClientFactory |
| 17 |
{ |
| 18 |
/** |
| 19 |
* @var (callable(ClientInterface|HttpAsyncClient, Plugin[], array): PluginClient)|null |
| 20 |
*/ |
| 21 |
private static $factory; |
| 22 |
|
| 23 |
/** |
| 24 |
* Set the factory to use. |
| 25 |
* The callable to provide must have the same arguments and return type as PluginClientFactory::createClient. |
| 26 |
* This is used by the HTTPlugBundle to provide a better Symfony integration. |
| 27 |
* Unlike the createClient method, this one is static to allow zero configuration profiling by hooking into early |
| 28 |
* application execution. |
| 29 |
* |
| 30 |
* @internal |
| 31 |
* |
| 32 |
* @param callable(ClientInterface|HttpAsyncClient, Plugin[], array): PluginClient $factory |
| 33 |
*/ |
| 34 |
public static function setFactory(callable $factory): void |
| 35 |
{ |
| 36 |
static::$factory = $factory; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* @param ClientInterface|HttpAsyncClient $client |
| 41 |
* @param Plugin[] $plugins |
| 42 |
* @param array{'client_name'?: string} $options |
| 43 |
* |
| 44 |
* Configuration options: |
| 45 |
* - client_name: to give client a name which may be used when displaying client information |
| 46 |
* like in the HTTPlugBundle profiler |
| 47 |
* |
| 48 |
* @see PluginClient constructor for PluginClient specific $options. |
| 49 |
*/ |
| 50 |
public function createClient($client, array $plugins = [], array $options = []): PluginClient |
| 51 |
{ |
| 52 |
if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) { |
| 53 |
throw new \TypeError( |
| 54 |
sprintf('%s::createClient(): Argument #1 ($client) must be of type %s|%s, %s given', self::class, ClientInterface::class, HttpAsyncClient::class, get_debug_type($client)) |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
if (static::$factory) { |
| 59 |
$factory = static::$factory; |
| 60 |
|
| 61 |
return $factory($client, $plugins, $options); |
| 62 |
} |
| 63 |
|
| 64 |
unset($options['client_name']); |
| 65 |
|
| 66 |
return new PluginClient($client, $plugins, $options); |
| 67 |
} |
| 68 |
} |
| 69 |
|