PhpConfigReader   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 45
ccs 14
cts 16
cp 0.875
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 31 5
A canRead() 0 5 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Config\ConfigReader;
6
7
use Gacela\Framework\Config\ConfigReaderInterface;
8
use Gacela\Framework\Event\ConfigReader\ReadPhpConfigEvent;
9
use Gacela\Framework\Event\Dispatcher\EventDispatchingCapabilities;
10
use JsonSerializable;
11
use RuntimeException;
12
13
use function is_array;
14
15
final class PhpConfigReader implements ConfigReaderInterface
16
{
17
    use EventDispatchingCapabilities;
18
19
    /**
20
     * @return array<string,mixed>
21
     */
22 30
    public function read(string $absolutePath): array
23
    {
24 30
        if (!$this->canRead($absolutePath)) {
25 25
            return [];
26
        }
27
28 16
        self::dispatchEvent(new ReadPhpConfigEvent($absolutePath));
29
30
        /**
31
         * @psalm-suppress UnresolvableInclude
32
         *
33
         * @var null|string[]|JsonSerializable|mixed $content
34
         */
35 16
        $content = include $absolutePath;
36
37 16
        if ($content === null) {
38
            return [];
39
        }
40
41 16
        if ($content instanceof JsonSerializable) {
42
            /** @var array<string,mixed> $jsonSerialized */
43 1
            $jsonSerialized = $content->jsonSerialize();
44 1
            return $jsonSerialized;
45
        }
46
47 16
        if (!is_array($content)) {
48
            throw new RuntimeException('The PHP config file must return an array or a JsonSerializable object!');
49
        }
50
51
        /** @var array<string,mixed> $content */
52 16
        return $content;
53
    }
54
55 30
    private function canRead(string $absolutePath): bool
56
    {
57 30
        $extension = pathinfo($absolutePath, PATHINFO_EXTENSION);
58
59 30
        return $extension === 'php' && file_exists($absolutePath);
60
    }
61
}
62