Completed
Push — master ( 79451c...b20886 )
by Dawid
04:40
created

ApiVersionFeaturesProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\Service;
6
7
use Spiechu\SymfonyCommonsBundle\ApiFeature\Definition;
8
9
class ApiVersionFeaturesProvider
10
{
11
    /**
12
     * @var ApiVersionProvider
13
     */
14
    protected $apiVersionProvider;
15
16
    /**
17
     * @var Definition[]
18
     */
19
    protected $features;
20
21
    /**
22
     * @param ApiVersionProvider $apiVersionProvider
23
     */
24 1
    public function __construct(ApiVersionProvider $apiVersionProvider)
25
    {
26 1
        $this->apiVersionProvider = $apiVersionProvider;
27
28 1
        $this->features = [];
29 1
    }
30
31
    /**
32
     * @param iterable $features
33
     *
34
     * @throws \InvalidArgumentException
35
     */
36 1
    public function addFeatures(iterable $features): void
37
    {
38 1
        foreach ($features as $name => $options) {
39 1
            if (isset($this->features[$name])) {
40
                throw new \InvalidArgumentException(sprintf('Feature with given name "%s" already exists', $name));
41
            }
42
43 1
            $this->features[$name] = new Definition($name, $options['since'] ?? null, $options['until'] ?? null);
44
        }
45 1
    }
46
47
    /**
48
     * @return Definition[]
49
     *
50
     * @throws \RuntimeException
51
     */
52 1
    public function getAvailableFeatures(): array
53
    {
54 1
        $currentVersion = $this->apiVersionProvider->getApiVersion();
55
56 1
        if ($currentVersion === null) {
57
            throw new \RuntimeException('API version is not set');
58
        }
59
60 1
        $matchingFeatures = [];
61
62 1
        foreach ($this->features as $feature) {
63 1
            if ($feature->isAvailableForVersion($currentVersion)) {
64 1
                $matchingFeatures[$feature->getName()] = $feature;
65
            }
66
        }
67
68 1
        return $matchingFeatures;
69
    }
70
}
71