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
|
|
|
|