Completed
Push — master ( d61dd2...0e6a80 )
by David
02:42 queued 11s
created

PluginClientBuilder::addPlugin()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
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
 * Build an instance of a PluginClient with a dynamic list of plugins.
12
 *
13
 * @author Baptiste Clavié <[email protected]>
14
 */
15
final class PluginClientBuilder
16
{
17
    /** @var Plugin[][] List of plugins ordered by priority [priority => Plugin[]]). */
18
    private $plugins = [];
19
20
    /** @var array Array of options to give to the plugin client */
21
    private $options = [];
22
23
    /**
24
     * @param int $priority Priority of the plugin. The higher comes first.
25
     */
26
    public function addPlugin(Plugin $plugin, int $priority = 0): self
27
    {
28
        $this->plugins[$priority][] = $plugin;
29
30
        return $this;
31
    }
32
33
    public function setOption(string $name, $value): self
34
    {
35
        $this->options[$name] = $value;
36
37
        return $this;
38
    }
39
40
    public function removeOption(string $name): self
41
    {
42
        unset($this->options[$name]);
43
44
        return $this;
45
    }
46
47
    /**
48
     * @param ClientInterface | HttpAsyncClient $client
49
     */
50
    public function createClient($client): PluginClient
51
    {
52
        if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) {
53
            throw new \RuntimeException('You must provide a valid http client');
54
        }
55
56
        $plugins = $this->plugins;
57
58
        if (0 === count($plugins)) {
59
            $plugins[] = [];
60
        }
61
62
        krsort($plugins);
63
        $plugins = array_merge(...$plugins);
64
65
        return new PluginClient(
66
            $client,
67
            array_values($plugins),
68
            $this->options
69
        );
70
    }
71
}
72