Completed
Pull Request — master (#43)
by Markus
02:59
created

PluginClient::addPlugin()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Client\Common\EmulatedHttpAsyncClient;
6
use Http\Client\Exception;
7
use Http\Client\HttpAsyncClient;
8
use Http\Client\HttpClient;
9
use Http\Client\Plugin\Exception\LoopException;
10
use Http\Promise\FulfilledPromise;
11
use Http\Promise\RejectedPromise;
12
use Psr\Http\Message\RequestInterface;
13
use Symfony\Component\OptionsResolver\OptionsResolver;
14
15
/**
16
 * The client managing plugins and providing a decorator around HTTP Clients.
17
 *
18
 * @author Joel Wurtz <[email protected]>
19
 */
20
final class PluginClient implements HttpClient, HttpAsyncClient
21
{
22
    /**
23
     * An HTTP async client.
24
     *
25
     * @var HttpAsyncClient
26
     */
27
    private $client;
28
29
    /**
30
     * The plugin chain.
31
     *
32
     * @var Plugin[]
33
     */
34
    private $plugins;
35
36
    /**
37
     * A list of options.
38
     *
39
     * @var array
40
     */
41
    private $options;
42
43
    /**
44
     * @param HttpClient|HttpAsyncClient $client
45
     * @param Plugin[]                   $plugins
46
     * @param array                      $options
47
     *
48
     * @throws \RuntimeException if client is not an instance of HttpClient or HttpAsyncClient
49
     */
50 10
    public function __construct($client, array $plugins = [], array $options = [])
51
    {
52 10
        if ($client instanceof HttpAsyncClient) {
53 3
            $this->client = $client;
54 10
        } elseif ($client instanceof HttpClient) {
55 7
            $this->client = new EmulatedHttpAsyncClient($client);
56 7
        } else {
57
            throw new \RuntimeException('Client must be an instance of Http\\Client\\HttpClient or Http\\Client\\HttpAsyncClient');
58
        }
59
60 10
        $this->plugins = $plugins;
61 10
        $this->options = $this->configure($options);
62 10
    }
63
64
    /**
65
     * Adds a plugin to the client.
66
     *
67
     * @param Plugin $plugin
68
     */
69 1
    public function addPlugin(Plugin $plugin)
70
    {
71 1
        $this->plugins[] = $plugin;
72 1
    }
73
74
    /**
75
     * Get all active plugins.
76
     *
77
     * @return Plugin[]
78
     */
79 2
    public function getPlugins()
80
    {
81 2
        return $this->plugins;
82
    }
83
84
    /**
85
     * Assign plugins to the client.
86
     *
87
     * @param Plugin[] $plugins
88
     */
89 1
    public function setPlugins(array $plugins = [])
90
    {
91 1
        $this->plugins = $plugins;
92 1
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 4
    public function sendRequest(RequestInterface $request)
98
    {
99
        // If we don't have an http client, use the async call
100 4
        if (!($this->client instanceof HttpClient)) {
101 1
            return $this->sendAsyncRequest($request)->wait();
102
        }
103
104
        // Else we want to use the synchronous call of the underlying client, and not the async one in the case
105
        // we have both an async and sync call
106
        $pluginChain = $this->createPluginChain($this->plugins, function (RequestInterface $request) {
107
            try {
108 2
                return new FulfilledPromise($this->client->sendRequest($request));
109
            } catch (Exception $exception) {
110
                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...
111
            }
112 3
        });
113
114 3
        return $pluginChain($request)->wait();
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 2
    public function sendAsyncRequest(RequestInterface $request)
121
    {
122
        $pluginChain = $this->createPluginChain($this->plugins, function (RequestInterface $request) {
123 2
            return $this->client->sendAsyncRequest($request);
124 2
        });
125
126 2
        return $pluginChain($request);
127
    }
128
129
    /**
130
     * Configure the plugin client.
131
     *
132
     * @param array $options
133
     *
134
     * @return array
135
     */
136 10
    private function configure(array $options = [])
137
    {
138 10
        $resolver = new OptionsResolver();
139 10
        $resolver->setDefaults([
140 10
            'max_restarts' => 10,
141 10
        ]);
142
143 10
        return $resolver->resolve($options);
144
    }
145
146
    /**
147
     * Create the plugin chain.
148
     *
149
     * @param Plugin[] $pluginList     A list of plugins
150
     * @param callable $clientCallable Callable making the HTTP call
151
     *
152
     * @return callable
153
     */
154 5
    private function createPluginChain($pluginList, callable $clientCallable)
155
    {
156 5
        $firstCallable = $lastCallable = $clientCallable;
157
158 5
        while ($plugin = array_pop($pluginList)) {
159
            $lastCallable = function (RequestInterface $request) use ($plugin, $lastCallable, &$firstCallable) {
160 1
                return $plugin->handleRequest($request, $lastCallable, $firstCallable);
161 1
            };
162
163 1
            $firstCallable = $lastCallable;
164 1
        }
165
166 5
        $firstCalls = 0;
167 5
        $firstCallable = function (RequestInterface $request) use ($lastCallable, &$firstCalls) {
168 5
            if ($firstCalls > $this->options['max_restarts']) {
169 1
                throw new LoopException('Too many restarts in plugin client', $request);
170
            }
171
172 5
            ++$firstCalls;
173
174 5
            return $lastCallable($request);
175 5
        };
176
177 5
        return $firstCallable;
178
    }
179
}
180