Passed
Push — master ( eff209...0e7332 )
by Edward
05:02
created

PropertyLoader::loadPropertyRangeSet()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\UniLex\RegExp;
6
7
use Remorhaz\UniLex\RegExp\FSM\RangeSet;
8
9
use function error_clear_last;
10
use function error_get_last;
11
use function is_string;
12
13
final class PropertyLoader implements PropertyLoaderInterface
14
{
15
16
    private $path;
17
18
    private $index;
19
20
    private $cache = [];
21
22
    public static function create(): self
23
    {
24
        $index = require __DIR__ . '/PropertyIndex.php';
25
26
        return new self(__DIR__, $index);
27
    }
28
29
    public function __construct(string $path, array $index)
30
    {
31
        $this->path = $path;
32
        $this->index = $index;
33
    }
34
35
    public function getRangeSet(string $propertyName): RangeSet
36
    {
37
        if (!isset($this->cache[$propertyName])) {
38
            $this->cache[$propertyName] = $this->loadRangeSet($propertyName);
39
        }
40
41
        return $this->cache[$propertyName];
42
    }
43
44
    private function loadRangeSet(string $propertyName): RangeSet
45
    {
46
        if (!isset($this->index[$propertyName])) {
47
            throw new Exception\PropertyRangeSetNotFoundException($propertyName);
48
        }
49
50
        $file = $this->index[$propertyName];
51
        if (!is_string($file)) {
52
            throw new Exception\InvalidPropertyConfigException($propertyName, $file);
53
        }
54
        $fileName = $this->path . $file;
55
        error_clear_last();
56
        /** @noinspection PhpIncludeInspection */
57
        $rangeSet = @include $fileName;
58
        if (false === $rangeSet) {
59
            $lastError = error_get_last();
60
            if (isset($lastError)) {
61
                throw new Exception\PropertyFileNotLoadedException(
62
                    $propertyName,
63
                    $fileName,
64
                    $lastError['message'] ?? null
65
                );
66
            }
67
        }
68
        if ($rangeSet instanceof RangeSet) {
69
            return $rangeSet;
70
        }
71
72
        throw new Exception\InvalidPropertyRangeSetException($propertyName, $fileName, $rangeSet);
73
    }
74
}
75