PhpConfigReader::read()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 32
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 32
rs 9.5222
cc 5
nc 5
nop 1
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 Override;
12
use RuntimeException;
13
14
use function is_array;
15
16
final class PhpConfigReader implements ConfigReaderInterface
17
{
18
    use EventDispatchingCapabilities;
19
20
    /**
21
     * @return array<string,mixed>
22
     */
23
    #[Override]
24
    public function read(string $absolutePath): array
25
    {
26
        if (!$this->canRead($absolutePath)) {
27
            return [];
28
        }
29
30
        self::dispatchEvent(new ReadPhpConfigEvent($absolutePath));
31
32
        /**
33
         * @psalm-suppress UnresolvableInclude
34
         *
35
         * @var null|string[]|JsonSerializable|mixed $content
36
         */
37
        $content = include $absolutePath;
38
39
        if ($content === null) {
40
            return [];
41
        }
42
43
        if ($content instanceof JsonSerializable) {
44
            /** @var array<string,mixed> $jsonSerialized */
45
            $jsonSerialized = $content->jsonSerialize();
46
            return $jsonSerialized;
47
        }
48
49
        if (!is_array($content)) {
50
            throw new RuntimeException('The PHP config file must return an array or a JsonSerializable object!');
51
        }
52
53
        /** @var array<string,mixed> $content */
54
        return $content;
55
    }
56
57
    private function canRead(string $absolutePath): bool
58
    {
59
        $extension = pathinfo($absolutePath, PATHINFO_EXTENSION);
60
61
        return $extension === 'php' && file_exists($absolutePath);
62
    }
63
}
64