Passed
Push — master ( 56ac53...50cf31 )
by Carlos C
03:36
created

BaseConverterSequence::checkIsValid()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 4
nop 1
dl 0
loc 20
ccs 12
cts 12
cp 1
crap 4
rs 9.9
c 0
b 0
f 0
1
<?php
2
namespace CfdiUtils\Internals;
3
4
/**
5
 * This is a value object for BaseConverter containing the sequence
6
 *
7
 * NOTE: Changes will not be considering a bracking compatibility change since this utility is for internal usage only
8
 * @internal
9
 */
10
class BaseConverterSequence
11
{
12
    /** @var string */
13
    private $sequence;
14
15
    /** @var int */
16
    private $length;
17
18 23
    public function __construct(string $sequence)
19
    {
20 23
        self::checkIsValid($sequence);
21
22 18
        $this->sequence = $sequence;
23 18
        $this->length = strlen($sequence);
24 18
    }
25
26 1
    public function __toString(): string
27
    {
28 1
        return $this->sequence;
29
    }
30
31 10
    public function value(): string
32
    {
33 10
        return $this->sequence;
34
    }
35
36 15
    public function length(): int
37
    {
38 15
        return $this->length;
39
    }
40
41 1
    public static function isValid(string $value): bool
42
    {
43
        try {
44 1
            static::checkIsValid($value);
45 1
            return true;
46 1
        } catch (\UnexpectedValueException $exception) {
47 1
            return false;
48
        }
49
    }
50
51 24
    public static function checkIsValid(string $sequence)
52
    {
53 24
        $length = strlen($sequence);
54
55
        // is not empty
56 24
        if ($length < 2) {
57 3
            throw new \UnexpectedValueException('Sequence does not contains enough elements');
58
        }
59
60 22
        if ($length !== mb_strlen($sequence)) {
61 1
            throw new \UnexpectedValueException('Cannot use multibyte strings in dictionary');
62
        }
63
64 21
        $valuesCount = array_count_values(str_split(strtoupper($sequence)));
65
        $repeated = array_filter($valuesCount, function (int $count) {
66 21
            return ($count !== 1);
67 21
        });
68 21
        if ([] !== $repeated) {
69 3
            throw new \UnexpectedValueException(
70 3
                sprintf('The sequence has not unique values: "%s"', implode(', ', array_keys($repeated)))
71
            );
72
        }
73 19
    }
74
}
75