StringTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 31
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A fromNative() 0 3 1
A toNative() 0 3 1
A toSchema() 0 5 1
1
<?php
2
namespace W2w\Lib\Apie\Plugins\ValueObject\ValueObjects;
3
4
use erasys\OpenApi\Spec\v3\Schema;
5
use ReflectionClass;
6
use W2w\Lib\Apie\Exceptions\InvalidValueForValueObjectException;
7
use W2w\Lib\Apie\OpenApiSchema\Factories\SchemaFactory;
8
9
trait StringTrait
10
{
11
    private $value;
12
13
    final public static function fromNative($value)
14
    {
15
        return new self((string) $value);
16
    }
17
18
    final public function __construct(string $value)
19
    {
20
        if (!$this->validValue($value)) {
21
            throw new InvalidValueForValueObjectException($value, __CLASS__);
22
        }
23
        $this->value = $this->sanitizeValue($value);
24
    }
25
26
    abstract protected function validValue(string $value): bool;
27
28
    abstract protected function sanitizeValue(string $value): string;
29
30
    final public function toNative()
31
    {
32
        return $this->value;
33
    }
34
35
    final static public function toSchema(): Schema
36
    {
37
        $refl = new ReflectionClass(__CLASS__);
38
        return SchemaFactory::createStringSchema(
39
            strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $refl->getShortName()))
40
        );
41
    }
42
}
43