Passed
Branch master (e4e723)
by Lucas
02:36
created

SchemaEnumAttribute   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 40
rs 10
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A matchesLoose() 0 3 2
A __construct() 0 4 1
A values() 0 4 1
A parseContextual() 0 9 2
A from() 0 3 1
A getValuesVerbose() 0 3 1
1
<?php
2
3
namespace Ipag\Sdk\Model\Schema;
4
5
use Ipag\Sdk\Model\Schema\Exception\SchemaAttributeParseException;
6
7
class SchemaEnumAttribute extends SchemaAttribute
8
{
9
    protected array $values;
10
11
    public function __construct(Schema $schema, string $name)
12
    {
13
        parent::__construct($schema, $name);
14
        $this->values = [];
15
    }
16
17
    public function values(array $values): self
18
    {
19
        $this->values = $values;
20
        return $this;
21
    }
22
23
    private function matchesLoose($value)
24
    {
25
        return array_reduce($this->values, fn($x, $y) => $x ?? ($y == $value ? $y : null), null);
26
    }
27
28
    public function parseContextual($value)
29
    {
30
        $value = $this->matchesLoose($value);
31
        if (!is_null($value)) {
32
            return $value;
33
        }
34
35
        $many = $this->getValuesVerbose();
36
        throw new SchemaAttributeParseException($this, "Provided value is not one of {$many}");
37
    }
38
39
    private function getValuesVerbose(): string
40
    {
41
        return implode(', ', $this->values);
42
    }
43
44
    public static function from(Schema $schema, string $name): self
45
    {
46
        return parent::from($schema, $name);
0 ignored issues
show
Bug Best Practice introduced by
The expression return parent::from($schema, $name) returns the type Ipag\Sdk\Model\Schema\SchemaAttribute which includes types incompatible with the type-hinted return Ipag\Sdk\Model\Schema\SchemaEnumAttribute.
Loading history...
47
    }
48
}