1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Config\Factory; |
6
|
|
|
|
7
|
|
|
use ArrayAccess; |
8
|
|
|
use Interop\Container\ContainerInterface; |
9
|
|
|
use Laminas\ServiceManager\Exception\ServiceNotCreatedException; |
10
|
|
|
use Laminas\ServiceManager\Factory\AbstractFactoryInterface; |
11
|
|
|
use Shlinkio\Shlink\Config\Exception\InvalidArgumentException; |
12
|
|
|
|
13
|
|
|
use function array_shift; |
14
|
|
|
use function explode; |
15
|
|
|
use function is_array; |
16
|
|
|
use function sprintf; |
17
|
|
|
use function substr_count; |
18
|
|
|
|
19
|
|
|
class DottedAccessConfigAbstractFactory implements AbstractFactoryInterface |
20
|
|
|
{ |
21
|
4 |
|
public function canCreate(ContainerInterface $container, $requestedName): bool // phpcs:ignore |
22
|
|
|
{ |
23
|
4 |
|
return substr_count($requestedName, '.') > 0; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Create an object |
28
|
|
|
* |
29
|
|
|
* @param string $requestedName |
30
|
|
|
* @return mixed|null |
31
|
|
|
*/ |
32
|
|
|
// phpcs:ignore |
33
|
3 |
|
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null) |
34
|
|
|
{ |
35
|
3 |
|
$parts = explode('.', $requestedName); |
36
|
3 |
|
$serviceName = array_shift($parts); |
37
|
3 |
|
if (! $container->has($serviceName)) { |
38
|
1 |
|
throw new ServiceNotCreatedException(sprintf( |
39
|
1 |
|
'Defined service "%s" could not be found in container after resolving dotted expression "%s".', |
40
|
1 |
|
$serviceName, |
41
|
1 |
|
$requestedName, |
42
|
|
|
)); |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
$array = $container->get($serviceName); |
46
|
2 |
|
return $this->readKeysFromArray($parts, $array); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param array $keys |
51
|
|
|
* @param array|\ArrayAccess $array |
52
|
|
|
* @return mixed|null |
53
|
|
|
* @throws InvalidArgumentException |
54
|
|
|
*/ |
55
|
2 |
|
private function readKeysFromArray(array $keys, $array) |
56
|
|
|
{ |
57
|
2 |
|
$key = array_shift($keys); |
58
|
|
|
|
59
|
|
|
// As soon as one of the provided keys is not found, throw an exception |
60
|
2 |
|
if (! isset($array[$key])) { |
61
|
1 |
|
throw new InvalidArgumentException(sprintf( |
62
|
1 |
|
'The key "%s" provided in the dotted notation could not be found in the array service', |
63
|
1 |
|
$key, |
64
|
|
|
)); |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
$value = $array[$key]; |
68
|
2 |
|
if (! empty($keys) && (is_array($value) || $value instanceof ArrayAccess)) { |
69
|
2 |
|
$value = $this->readKeysFromArray($keys, $value); |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
return $value; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|