Passed
Push — master ( 2fc57b...1ebcaf )
by Thomas
02:57
created

BundledSource::__construct()   B

Complexity

Conditions 8
Paths 11

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 17
c 1
b 0
f 0
nc 11
nop 1
dl 0
loc 24
ccs 17
cts 17
cp 1
crap 8
rs 8.4444
1
<?php
2
3
namespace MadWizard\WebAuthn\Metadata\Source;
4
5
use MadWizard\WebAuthn\Exception\UnexpectedValueException;
6
use MadWizard\WebAuthn\Metadata\Provider\Apple\AppleDevicesProvider;
7
use MadWizard\WebAuthn\Metadata\Provider\MetadataProviderInterface;
8
9
final class BundledSource implements MetadataSourceInterface
10
{
11
    private const SETS =
12
        [
13
            'apple' => false,
14
            // 'yubico-u2f' => true,
15
        ];
16
17
    /**
18
     * @var string[]
19
     * @phpstan-var array<string, class-string>
20
     */
21
    private const PROVIDERS = [
22
        'apple' => AppleDevicesProvider::class,
23
    ];
24
25
    /**
26
     * @var array<string, bool>
27
     */
28
    private $enabledSets;
29
30 7
    public function __construct(array $sets = ['@all'])
31
    {
32 7
        $this->enabledSets = self::SETS;
33 7
        foreach ($sets as $set) {
34 6
            if ($set === '') {
35 1
                throw new UnexpectedValueException('Empty set name');
36
            }
37
38 5
            if ($set === '@all') {
39 2
                $this->enabledSets = array_fill_keys(array_keys(self::SETS), true);
40
            } else {
41 4
                $add = true;
42 4
                if ($set[0] === '-') {
43 1
                    $set = substr($set, 1);
44 1
                    $add = false;
45
                }
46
47 4
                if (!isset(self::SETS[$set])) {
48 2
                    throw new UnexpectedValueException(sprintf("Invalid set name '%s'.", $set));
49
                }
50 2
                if ($add) {
51 1
                    $this->enabledSets[$set] = true;
52 1
                } elseif (isset($this->enabledSets[$set])) {
53 1
                    $this->enabledSets[$set] = false;
54
                }
55
            }
56
        }
57 4
    }
58
59
    public function getEnableSets(): array
60
    {
61
        return array_keys(array_filter($this->enabledSets, static function ($value) { return $value; }));
62
    }
63
64
    /**
65
     * @return MetadataProviderInterface[]
66
     */
67 4
    public function createProviders(): array
68
    {
69 4
        $providers = [];
70 4
        foreach ($this->enabledSets as $type => $enabled) {
71 4
            if ($enabled) {
72 3
                $className = self::PROVIDERS[$type];
73 3
                $providers[] = new $className();
74
            }
75
        }
76 4
        return $providers;
77
    }
78
}
79