Completed
Pull Request — master (#22)
by Tobias
03:43
created

PluginClient   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 93.88%

Importance

Changes 4
Bugs 1 Features 2
Metric Value
wmc 12
c 4
b 1
f 2
lcom 1
cbo 7
dl 0
loc 144
ccs 46
cts 49
cp 0.9388
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A sendRequest() 0 19 3
A sendAsyncRequest() 0 8 1
A configure() 0 10 1
B createPluginChain() 0 34 4
1
<?php
2
3
namespace Http\Client\Common;
4
5
use Http\Client\Common\Exception\LoopException;
6
use Http\Client\Exception as HttplugException;
7
use Http\Client\HttpAsyncClient;
8
use Http\Client\HttpClient;
9
use Http\Promise\FulfilledPromise;
10
use Http\Promise\RejectedPromise;
11
use Psr\Http\Message\RequestInterface;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
14
/**
15
 * The client managing plugins and providing a decorator around HTTP Clients.
16
 *
17
 * @author Joel Wurtz <[email protected]>
18
 */
19
final class PluginClient implements HttpClient, HttpAsyncClient
20
{
21
    /**
22
     * An HTTP async client.
23
     *
24
     * @var HttpAsyncClient
25
     */
26
    private $client;
27
28
    /**
29
     * The plugin chain.
30
     *
31
     * @var Plugin[]
32
     */
33
    private $plugins;
34
35
    /**
36
     * A list of options.
37
     *
38
     * @var array
39
     */
40
    private $options;
41
42
    /**
43
     * @param HttpClient|HttpAsyncClient $client
44
     * @param Plugin[]                   $plugins
45
     * @param array                      $options {
46
     *
47
     *     @var int      $max_restarts
48
     *     @var Plugin[] $debug_plugins an array of plugins that are injected between each normal plugin
49
     * }
50
     *
51
     * @throws \RuntimeException if client is not an instance of HttpClient or HttpAsyncClient
52
     */
53 8
    public function __construct($client, array $plugins = [], array $options = [])
54
    {
55 8
        if ($client instanceof HttpAsyncClient) {
56 3
            $this->client = $client;
57 8
        } elseif ($client instanceof HttpClient) {
58 5
            $this->client = new EmulatedHttpAsyncClient($client);
59 5
        } else {
60
            throw new \RuntimeException('Client must be an instance of Http\\Client\\HttpClient or Http\\Client\\HttpAsyncClient');
61
        }
62
63 8
        $this->plugins = $plugins;
64 8
        $this->options = $this->configure($options);
65 8
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 4
    public function sendRequest(RequestInterface $request)
71
    {
72
        // If we don't have an http client, use the async call
73 4
        if (!($this->client instanceof HttpClient)) {
74 1
            return $this->sendAsyncRequest($request)->wait();
75
        }
76
77
        // Else we want to use the synchronous call of the underlying client, and not the async one in the case
78
        // we have both an async and sync call
79
        $pluginChain = $this->createPluginChain($this->plugins, function (RequestInterface $request) {
80
            try {
81 2
                return new FulfilledPromise($this->client->sendRequest($request));
82
            } catch (HttplugException $exception) {
83
                return new RejectedPromise($exception);
0 ignored issues
show
Documentation introduced by
$exception is of type object<Http\Client\Exception>, but the function expects a object<Exception>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
            }
85 3
        });
86
87 3
        return $pluginChain($request)->wait();
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93 2
    public function sendAsyncRequest(RequestInterface $request)
94
    {
95
        $pluginChain = $this->createPluginChain($this->plugins, function (RequestInterface $request) {
96 2
            return $this->client->sendAsyncRequest($request);
97 2
        });
98
99 2
        return $pluginChain($request);
100
    }
101
102
    /**
103
     * Configure the plugin client.
104
     *
105
     * @param array $options
106
     *
107
     * @return array
108
     */
109 8
    private function configure(array $options = [])
110
    {
111 8
        $resolver = new OptionsResolver();
112 8
        $resolver->setDefaults([
113 8
            'max_restarts' => 10,
114 8
            'debug_plugins' => [],
115 8
        ]);
116
117 8
        return $resolver->resolve($options);
118
    }
119
120
    /**
121
     * Create the plugin chain.
122
     *
123
     * @param Plugin[] $pluginList     A list of plugins
124
     * @param callable $clientCallable Callable making the HTTP call
125
     *
126
     * @return callable
127
     */
128 5
    private function createPluginChain($pluginList, callable $clientCallable)
129
    {
130 5
        $firstCallable = $lastCallable = $clientCallable;
131
132
        /*
133
         * Inject debug plugins between each plugin.
134
         */
135 5
        $pluginListWithDebug = $this->options['debug_plugins'];
136 5
        foreach ($pluginList as $plugin) {
137 1
            $pluginListWithDebug[] = $plugin;
138 1
            $pluginListWithDebug = array_merge($pluginListWithDebug, $this->options['debug_plugins']);
139 5
        }
140
141 5
        while ($plugin = array_pop($pluginListWithDebug)) {
142
            $lastCallable = function (RequestInterface $request) use ($plugin, $lastCallable, &$firstCallable) {
143 1
                return $plugin->handleRequest($request, $lastCallable, $firstCallable);
144 1
            };
145
146 1
            $firstCallable = $lastCallable;
147 1
        }
148
149 5
        $firstCalls = 0;
150 5
        $firstCallable = function (RequestInterface $request) use ($lastCallable, &$firstCalls) {
151 5
            if ($firstCalls > $this->options['max_restarts']) {
152 1
                throw new LoopException('Too many restarts in plugin client', $request);
153
            }
154
155 5
            ++$firstCalls;
156
157 5
            return $lastCallable($request);
158 5
        };
159
160 5
        return $firstCallable;
161
    }
162
}
163