ContainerConfigLocator::getConfig()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 9.9332
cc 4
nc 5
nop 1
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @see       https://github.com/soluble-io/soluble-mediatools for the canonical repository
7
 *
8
 * @copyright Copyright (c) 2018-2020 Sébastien Vanvelthem. (https://github.com/belgattitude)
9
 * @license   https://github.com/soluble-io/soluble-mediatools/blob/master/LICENSE.md MIT
10
 */
11
12
namespace Soluble\MediaTools\Common\Config;
13
14
use Psr\Container\ContainerInterface;
15
use Soluble\MediaTools\Common\Exception\InvalidConfigException;
16
17
final class ContainerConfigLocator
18
{
19
    public const DEFAULT_ENTRY_NAME = 'config';
20
21
    /** @var ContainerInterface */
22
    private $container;
23
24
    /** @var string */
25
    private $entryName;
26
27 63
    public function __construct(
28
        ContainerInterface $container,
29
        string $entryName = self::DEFAULT_ENTRY_NAME
30
    ) {
31 63
        $this->container = $container;
32 63
        $this->entryName = $entryName;
33 63
    }
34
35
    /**
36
     * @throws InvalidConfigException
37
     */
38 63
    public function getConfig(?string $configKey = null): array
39
    {
40
        try {
41 63
            $containerConfig = $this->container->get($this->entryName);
42 2
        } catch (\Throwable $e) {
43 2
            throw new InvalidConfigException(
44 2
                sprintf('Cannot resolve container entry \'%s\' ($entryName).', $this->entryName)
45
            );
46
        }
47
48 61
        $config = $configKey === null ? $containerConfig : ($containerConfig[$configKey] ?? null);
49
50 61
        if (!is_array($config)) {
51 2
            throw new InvalidConfigException(
52 2
                sprintf('Cannot find a configuration ($entryName=%s found, invalid $configKey=%s).', $this->entryName, $configKey ?? '')
53
            );
54
        }
55
56 59
        return $config;
57
    }
58
}
59