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

PhpConfigReader   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 88.89%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 48
rs 10
c 0
b 0
f 0
ccs 16
cts 18
cp 0.8889
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 31 5
A triggerEvent() 0 3 1
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\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