RequestMatcherFactory   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 23
c 1
b 0
f 0
dl 0
loc 59
ccs 20
cts 24
cp 0.8333
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A createPlugin() 0 21 5
A getPlugin() 0 20 4
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 Psr\Container\ContainerInterface;
12
use TMV\HTTPlugModule\PluginFactoryManager;
13
14
use function is_string;
15
16
class RequestMatcherFactory implements PluginFactory
17
{
18
    private ContainerInterface $container;
19
20 3
    public function __construct(ContainerInterface $container)
21
    {
22 3
        $this->container = $container;
23 3
    }
24
25
    /**
26
     * @param array<string, mixed> $config
27
     */
28
    public function createPlugin(array $config = []): Plugin
29
    {
30 3
        $requestMatcherName = $config['request_matcher'] ?? null;
31
32 3
        if (! is_string($requestMatcherName)) {
33
            throw new InvalidArgumentException('Invalid request matcher name');
34 3
        }
35
36
        $requestMatcher = $this->container->get($requestMatcherName);
37
38 3
        if (! $requestMatcher instanceof RequestMatcher) {
39
            throw new InvalidArgumentException('Invalid request matcher');
40 3
        }
41
42
        $successPlugin = $config['success_plugin'] ?? null;
43
        $failurePlugin = $config['failure_plugin'] ?? null;
44 3
45 3
        return new RequestMatcherPlugin(
46
            $requestMatcher,
47 3
            $successPlugin ? $this->getPlugin($successPlugin) : null,
48 3
            $failurePlugin ? $this->getPlugin($failurePlugin) : null
49 3
        );
50 3
    }
51
52
    /**
53
     * @param string|array<string, mixed> $plugin
54
     */
55
    private function getPlugin($plugin): Plugin
56
    {
57
        if (is_string($plugin)) {
58
            return $this->container->get($plugin);
59 2
        }
60
61 2
        if (! \is_array($plugin)) {
0 ignored issues
show
introduced by
The condition is_array($plugin) is always true.
Loading history...
62 1
            throw new InvalidArgumentException('Invalid plugin');
63
        }
64
65 1
        $name = $plugin['name'] ?? null;
66
67
        if (! is_string($name)) {
68
            throw new InvalidArgumentException('Invalid plugin name');
69 1
        }
70
71 1
        /** @var PluginFactoryManager $pluginFactoryManager */
72
        $pluginFactoryManager = $this->container->get(PluginFactoryManager::class);
73
74
        return $pluginFactoryManager->getFactory($name)->createPlugin($plugin['config'] ?? []);
75
    }
76
}
77