Skip to content

Commit fd4fd0a

Browse files
fbourigaultNyholm
authored andcommitted
add plugin client factory (#71)
1 parent 33b6d65 commit fd4fd0a

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
### Added
6+
7+
- `PluginClientFactory` to create `PluginClient` instances.
8+
59
### Deprecated
610

711
- The `debug_plugins` option for `PluginClient` is deprecated and will be removed in 2.0. Use the decorator design pattern instead like in [ProfilePlugin](https://github.com/php-http/HttplugBundle/blob/de33f9c14252f22093a5ec7d84f17535ab31a384/Collector/ProfilePlugin.php).

spec/PluginClientFactorySpec.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace spec\Http\Client\Common;
4+
5+
use Http\Client\HttpClient;
6+
use PhpSpec\ObjectBehavior;
7+
8+
class PluginClientFactorySpec extends ObjectBehavior
9+
{
10+
function it_is_initializable()
11+
{
12+
$this->shouldHaveType('Http\Client\Common\PluginClientFactory');
13+
}
14+
15+
function it_returns_a_plugin_client(HttpClient $httpClient)
16+
{
17+
$client = $this->createClient($httpClient);
18+
19+
$client->shouldHaveType('Http\Client\Common\PluginClient');
20+
}
21+
}

src/PluginClientFactory.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
namespace Http\Client\Common;
4+
5+
use Http\Client\HttpAsyncClient;
6+
use Http\Client\HttpClient;
7+
8+
/**
9+
* @author Fabien Bourigault <[email protected]>
10+
*/
11+
final class PluginClientFactory
12+
{
13+
/**
14+
* @var callable
15+
*/
16+
private static $factory;
17+
18+
/**
19+
* Set the factory to use.
20+
* The callable to provide must have the same arguments and return type as PluginClientFactory::createClient.
21+
* This is used by the HTTPlugBundle to provide a better Symfony integration.
22+
*
23+
* @internal
24+
*
25+
* @param callable $factory
26+
*/
27+
public static function setFactory(callable $factory)
28+
{
29+
static::$factory = $factory;
30+
}
31+
32+
/**
33+
* @param HttpClient|HttpAsyncClient $client
34+
* @param Plugin[] $plugins
35+
* @param array $options {
36+
*
37+
* @var string $client_name to give client a name which may be used when displaying client information like in
38+
* the HTTPlugBundle profiler.
39+
* }
40+
*
41+
* @see PluginClient constructor for PluginClient specific $options.
42+
*
43+
* @return PluginClient
44+
*/
45+
public function createClient($client, array $plugins = [], array $options = [])
46+
{
47+
if (static::$factory) {
48+
$factory = static::$factory;
49+
50+
return $factory($client, $plugins, $options);
51+
}
52+
53+
return new PluginClient($client, $plugins, $options);
54+
}
55+
}

0 commit comments

Comments
 (0)