Passed
Push — misc/create-event-dispatching-... ( d93e6c )
by Chema
05:17 queued 47s
created

PhpConfigReader::dispatchEvent()   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
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 22
    public function read(string $absolutePath): array
23
    {
24 22
        if (!$this->canRead($absolutePath)) {
25 20
            return [];
26
        }
27
28 21
        $this->dispatchEvent(new ReadPhpConfigEvent($absolutePath));
29
30
        /**
31
         * @psalm-suppress UnresolvableInclude
32
         *
33
         * @var null|string[]|JsonSerializable|mixed $content
34
         */
35 21
        $content = include $absolutePath;
36
37 21
        if ($content === null) {
38
            return [];
39
        }
40
41 21
        if ($content instanceof JsonSerializable) {
42
            /** @var array<string,mixed> $jsonSerialized */
43 1
            $jsonSerialized = $content->jsonSerialize();
44 1
            return $jsonSerialized;
45
        }
46
47 21
        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 21
        return $content;
53
    }
54
55 22
    private function canRead(string $absolutePath): bool
56
    {
57 22
        $extension = pathinfo($absolutePath, PATHINFO_EXTENSION);
58
59 22
        return $extension === 'php' && file_exists($absolutePath);
60
    }
61
}
62