Passed
Push — master ( 1ec89a...1818e9 )
by Vincent
06:54 queued 04:35
created

VersionService::getVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VGirol\JsonApiStructure;
6
7
require_once 'Versions.php';
8
9
class VersionService
10
{
11
    use CanUseDotPath;
12
13
    private $default = VERSION_1_0;
14
15
    private $version;
16
17
    private $cache = [];
18
19
    /**
20
     * Create a new instance
21
     *
22
     * @param string|null $version The version of the JSON:API specification
23
     *
24
     * @return void
25
     */
26 768
    public function __construct(string $version = null)
27
    {
28 768
        $this->setVersion($version ?? $this->default);
29 768
    }
30
31
    /**
32
     * Set the version of the JSON:API specification
33
     *
34
     * @param string $version
35
     *
36
     * @return static
37
     */
38 768
    public function setVersion(string $version)
39
    {
40 768
        $this->version = $version;
41 768
        $this->createCache();
42
43 768
        return $this;
44
    }
45
46
    /**
47
     * Get the version of the JSON:API specification
48
     *
49
     * @return string
50
     */
51
    public function getVersion(): string
52
    {
53
        return $this->version;
54
    }
55
56 441
    public function getRule(string $path)
57
    {
58 441
        return $this->retrieve($path, $this->cache);
59
    }
60
61 768
    private function createCache(): void
62
    {
63 768
        $rules = include 'VersionRules.php';
64
65 768
        $major = 1;
66 768
        $minor = 0;
67
68
        do {
69 768
            $version = constant("\VGirol\JsonApiStructure\VERSION_{$major}_{$minor}");
70 768
            if (!\array_key_exists($version, $rules)) {
71
                $minor = 0;
72
                $major++;
73
            }
74
75 768
            $this->cache = \array_merge_recursive($this->cache, $rules[$version]);
76 768
            $minor++;
77 768
        } while ($version != $this->version);
78 768
    }
79
}
80