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