StringTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 12
c 2
b 1
f 1
dl 0
loc 35
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A toNative() 0 3 1
A fromNative() 0 9 3
A __toString() 0 3 1
A __construct() 0 6 2
1
<?php
2
3
4
namespace Apie\ValueObjects;
5
6
use Apie\ValueObjects\Exceptions\InvalidValueForValueObjectException;
7
8
trait StringTrait
9
{
10
    private $value;
11
12
    final public static function fromNative($value)
13
    {
14
        if ($value instanceof ValueObjectInterface) {
15
            $value = $value->toNative();
16
        }
17
        if (is_array($value)) {
18
            throw new InvalidValueForValueObjectException($value, static::class);
19
        }
20
        return new self((string) $value);
21
    }
22
23
    final public function __construct(string $value)
24
    {
25
        if (!$this->validValue($value)) {
26
            throw new InvalidValueForValueObjectException($value, static::class);
27
        }
28
        $this->value = $this->sanitizeValue($value);
29
    }
30
31
    abstract protected function validValue(string $value): bool;
32
33
    abstract protected function sanitizeValue(string $value): string;
34
35
    final public function toNative()
36
    {
37
        return $this->value;
38
    }
39
40
    final public function __toString(): string
41
    {
42
        return $this->toNative();
43
    }
44
}
45