Passed
Pull Request — master (#216)
by Jesús
06:39 queued 03:20
created

PhpConfigReader::read()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0909

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 5
nop 1
dl 0
loc 31
rs 9.5555
c 0
b 0
f 0
ccs 11
cts 13
cp 0.8462
crap 5.0909
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Config\ConfigReader;
6
7
use Gacela\Framework\Config\Config;
8
use Gacela\Framework\Config\ConfigReaderInterface;
9
use Gacela\Framework\EventListener\ConfigReader\ReadPhpConfigEvent;
10
use Gacela\Framework\EventListener\GacelaEventInterface;
11
use JsonSerializable;
12
use RuntimeException;
13
14
use function is_array;
15
16
final class PhpConfigReader implements ConfigReaderInterface
17
{
18
    /**
19
     * @return array<string,mixed>
20
     */
21 22
    public function read(string $absolutePath): array
22
    {
23 22
        if (!$this->canRead($absolutePath)) {
24 20
            return [];
25
        }
26
27 21
        $this->triggerEvent(new ReadPhpConfigEvent($absolutePath));
28
29
        /**
30
         * @psalm-suppress UnresolvableInclude
31
         *
32
         * @var null|string[]|JsonSerializable|mixed $content
33
         */
34 21
        $content = include $absolutePath;
35
36 21
        if ($content === null) {
37
            return [];
38
        }
39
40 21
        if ($content instanceof JsonSerializable) {
41
            /** @var array<string,mixed> $jsonSerialized */
42 1
            $jsonSerialized = $content->jsonSerialize();
43 1
            return $jsonSerialized;
44
        }
45
46 21
        if (!is_array($content)) {
47
            throw new RuntimeException('The PHP config file must return an array or a JsonSerializable object!');
48
        }
49
50
        /** @var array<string,mixed> $content */
51 21
        return $content;
52
    }
53
54 22
    private function canRead(string $absolutePath): bool
55
    {
56 22
        $extension = pathinfo($absolutePath, PATHINFO_EXTENSION);
57
58 22
        return $extension === 'php' && file_exists($absolutePath);
59
    }
60
61 21
    private function triggerEvent(GacelaEventInterface $event): void
62
    {
63 21
        Config::getEventDispatcher()->dispatch($event);
64
    }
65
}
66