Enum   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
B build() 0 24 3
A __construct() 0 3 1
A process() 0 11 4
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Config\Property;
5
6
use Innmind\Config\{
7
    Property,
8
    Properties,
9
    Exception\SchemaNotParseable,
10
    Exception\InvalidArgumentException,
11
};
12
use Innmind\Immutable\{
13
    Str,
14
    SetInterface,
15
    Set,
16
};
17
18
final class Enum implements Property
19
{
20
    private const PATTERN = '~^\??enum\((?<values>.+)\)$~';
21
22
    private $values;
23
    private $optional = false;
24
25 13
    private function __construct(Set $values)
26
    {
27 13
        $this->values = $values;
28 13
    }
29
30 16
    public static function build(Str $schema, Properties $properties): Property
31
    {
32 16
        if (!$schema->matches(self::PATTERN)) {
33 3
            throw new SchemaNotParseable((string) $schema);
34
        }
35
36 13
        $self = new self(
37
            $schema
38 13
                ->capture(self::PATTERN)
39 13
                ->get('values')
40 13
                ->split('|')
41 13
                ->reduce(
42 13
                    Set::of('string'),
43 13
                    static function(SetInterface $values, Str $value): SetInterface {
44 13
                        return $values->add((string) $value);
45 13
                    }
46
                )
47
        );
48
49 13
        if ((string) $schema->substring(0, 1) === '?') {
50 6
            $self->optional = true;
51
        }
52
53 13
        return $self;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 7
    public function process($value)
60
    {
61 7
        if (is_null($value) && $this->optional) {
62 3
            return null;
63
        }
64
65 4
        if (!$this->values->contains($value)) {
66 1
            throw new InvalidArgumentException;
67
        }
68
69 3
        return $value;
70
    }
71
}
72