Passed
Push — master ( a4502d...24a613 )
by Thomas Mauro
11:47
created

RequestMatcherFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\HTTPlugModule\PluginFactory;
6
7
use Http\Client\Common\Plugin;
8
use Http\Client\Common\Plugin\RequestMatcherPlugin;
9
use Http\Message\RequestMatcher;
10
use InvalidArgumentException;
11
use function is_string;
12
use Psr\Container\ContainerInterface;
13
use TMV\HTTPlugModule\PluginFactoryManager;
14
15
class RequestMatcherFactory implements PluginFactory
16
{
17
    /** @var ContainerInterface */
18
    private $container;
19
20 3
    public function __construct(ContainerInterface $container)
21
    {
22 3
        $this->container = $container;
23 3
    }
24
25 3
    public function createPlugin(array $config = []): Plugin
26
    {
27 3
        $requestMatcherName = $config['request_matcher'] ?? null;
28
29 3
        if (! is_string($requestMatcherName)) {
30
            throw new InvalidArgumentException('Invalid request matcher name');
31
        }
32
33 3
        $requestMatcher = $this->container->get($requestMatcherName);
34
35 3
        if (! $requestMatcher instanceof RequestMatcher) {
36
            throw new InvalidArgumentException('Invalid request matcher');
37
        }
38
39 3
        $successPlugin = $config['success_plugin'] ?? null;
40 3
        $failurePlugin = $config['failure_plugin'] ?? null;
41
42 3
        return new RequestMatcherPlugin(
43 3
            $requestMatcher,
44 3
            $successPlugin ? $this->getPlugin($successPlugin) : null,
45 3
            $failurePlugin ? $this->getPlugin($failurePlugin) : null
46
        );
47
    }
48
49 2
    private function getPlugin($plugin): Plugin
50
    {
51 2
        if (is_string($plugin)) {
52 1
            return $this->container->get($plugin);
53
        }
54
55 1
        if (! \is_array($plugin)) {
56
            throw new InvalidArgumentException('Invalid plugin');
57
        }
58
59 1
        $name = $plugin['name'] ?? null;
60
61 1
        if (! is_string($name)) {
62
            throw new InvalidArgumentException('Invalid plugin name');
63
        }
64
65
        /** @var PluginFactoryManager $pluginFactoryManager */
66 1
        $pluginFactoryManager = $this->container->get(PluginFactoryManager::class);
67
68 1
        return $pluginFactoryManager->getFactory($name)->createPlugin($plugin['config'] ?? []);
69
    }
70
}
71