BasicAttribute   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 12
eloc 16
c 0
b 0
f 0
dl 0
loc 70
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A validatePattern() 0 4 2
A __toString() 0 3 1
A validateLength() 0 4 2
A __construct() 0 5 1
A setKey() 0 3 2
A getKey() 0 3 1
A validateChoice() 0 4 2
A getValue() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Bpost\BpostApiClient\Common;
5
6
use Bpost\BpostApiClient\Exception\BpostLogicException;
7
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidLengthException;
8
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidPatternException;
9
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidValueException;
10
11
abstract class BasicAttribute
12
{
13
    private mixed $value;
14
    private string $key;
15
16
    public function __construct(mixed $value, string $key = '')
17
    {
18
        $this->value = $value;
19
        $this->setKey($key);
20
        $this->validate();
21
    }
22
23
    public function getValue(): mixed
24
    {
25
        return $this->value;
26
    }
27
28
    private function setKey(string $key): void
29
    {
30
        $this->key = $key !== '' ? $key : $this->getDefaultKey();
31
    }
32
33
    public function getKey(): string
34
    {
35
        return $this->key;
36
    }
37
38
    public function __toString(): string
39
    {
40
        return (string) $this->getValue();
41
    }
42
43
    /**
44
     * @throws BpostInvalidLengthException
45
     */
46
    public function validateLength(int $length): void
47
    {
48
        if (mb_strlen((string) $this->getValue()) > $length) {
49
            throw new BpostInvalidLengthException($this->getKey(), mb_strlen((string) $this->getValue()), $length);
50
        }
51
    }
52
53
    /**
54
     * @throws BpostInvalidValueException
55
     */
56
    public function validateChoice(array $allowedValues): void
57
    {
58
        if (!in_array($this->getValue(), $allowedValues, true)) {
59
            throw new BpostInvalidValueException($this->getKey(), $this->getValue(), $allowedValues);
60
        }
61
    }
62
63
    /**
64
     * @throws BpostInvalidPatternException
65
     */
66
    public function validatePattern(string $regexPattern): void
67
    {
68
        if (!preg_match("/^$regexPattern$/", (string) $this->getValue())) {
69
            throw new BpostInvalidPatternException($this->getKey(), (string) $this->getValue(), $regexPattern);
70
        }
71
    }
72
73
    abstract protected function getDefaultKey(): string;
74
75
    /**
76
     * Each class must validate data
77
     * and throw BpostLogicException if crash
78
     * @throws BpostLogicException
79
     */
80
    abstract public function validate(): void;
81
}
82