readKeysFromArray()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
nc 3
nop 2
dl 0
loc 18
rs 9.6111
c 1
b 0
f 0
ccs 10
cts 10
cp 1
crap 5
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