StringTrait::toNative()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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