PluginAbstractFactory::getPluginConfig()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 21
ccs 0
cts 15
cp 0
rs 9.9332
cc 4
nc 4
nop 2
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\HTTPlugModule\DIFactory;
6
7
use Http\Client\Common\Plugin;
8
use Psr\Container\ContainerInterface;
9
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
10
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
11
use Laminas\ServiceManager\Factory\AbstractFactoryInterface;
12
use TMV\HTTPlugModule\PluginFactoryManager;
13
14
use function count;
15
use function explode;
16
use function is_array;
17
18
/**
19
 * @psalm-api
20
 */
21
class PluginAbstractFactory implements AbstractFactoryInterface
22
{
23
    protected function getServiceTypeName(): string
24
    {
25
        return 'plugins';
26
    }
27
28
    /**
29
     * @return array<string, string|array<string, mixed>>|null
30
     *
31
     * @psalm-return null|array{0: string, 1: array<string, mixed>}
32
     */
33
    private function getPluginConfig(ContainerInterface $container, string $requestedName): ?array
34
    {
35
        if (! str_starts_with($requestedName, 'httplug.plugins.')) {
36
            return null;
37
        }
38
39
        $exploded = explode('.', $requestedName);
40
41
        if (4 !== count($exploded)) {
42
            return null;
43
        }
44
45
        [,, $pluginName, $serviceName] = $exploded;
46
47
        $config = $container->get('config')['httplug']['plugins'][$pluginName][$serviceName] ?? null;
48
49
        if (! is_array($config)) {
50
            return null;
51
        }
52
53
        return [$pluginName, $config];
54
    }
55
56
    /**
57
     * @param string $requestedName
58
     */
59
    public function canCreate(ContainerInterface $container, $requestedName): bool
60
    {
61
        return is_array($this->getPluginConfig($container, $requestedName));
62
    }
63
64
    /**
65
     * Create an object.
66
     *
67
     * @param string $requestedName
68
     * @param null|array<mixed> $options
69
     *
70
     * @throws ServiceNotFoundException if unable to resolve the service
71
     * @throws ServiceNotCreatedException if an exception is raised when
72
     *                                    creating a service
73
     */
74
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null): Plugin
75
    {
76
        [$pluginName, $config] = $this->getPluginConfig($container, $requestedName);
77
78
        /** @var PluginFactoryManager $pluginFactoryManager */
79
        $pluginFactoryManager = $container->get(PluginFactoryManager::class);
80
81
        return $pluginFactoryManager->getFactory($pluginName)->createPlugin($config);
82
    }
83
}
84