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

PhpConfigReader::triggerEvent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
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