AbstractEntity::setId()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 10
ccs 5
cts 5
cp 1
cc 3
nc 2
nop 1
crap 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: davis
5
 * Date: 7/30/17
6
 * Time: 1:27 PM
7
 */
8
9
namespace DavisPeixoto\BlogCore\Entity;
10
11
use Ramsey\Uuid\Exception\InvalidUuidStringException;
12
use Ramsey\Uuid\Uuid;
13
use Ramsey\Uuid\UuidInterface;
14
use stdClass;
15
16
abstract class AbstractEntity extends stdClass
17
{
18
    const UUID_TYPE_RANDOM = 4;
19
20
    /**
21
     * @var UuidInterface
22
     */
23
    protected $id;
24
25
    /**
26
     * @return string
27
     */
28 9
    public function getId(): string
29
    {
30 9
        return $this->id->toString();
31
    }
32
33
    /**
34
     * @param string|null $id
35
     * @throws InvalidUuidStringException
36
     */
37 26
    public function setId(string $id = null)
38
    {
39 26
        if ($id === null || $id === '') {
40 23
            $this->id = Uuid::uuid4();
41
        } else {
42 13
            $this->id = $this->isVersionValid(Uuid::fromString($this->isValidString($id)));
43
        }
44 24
    }
45
46
    /**
47
     * @param string $id
48
     * @return string
49
     * @throws InvalidUuidStringException
50
     */
51 13
    private function isValidString(string $id): string
52
    {
53 13
        if (!Uuid::isValid($id)) {
54 1
            throw new InvalidUuidStringException('Invalid string');
55
        }
56
57 12
        return $id;
58
    }
59
60
    /**
61
     * @param UuidInterface $uuid
62
     * @return UuidInterface
63
     * @throws InvalidUuidStringException
64
     */
65 12
    private function isVersionValid(UuidInterface $uuid): UuidInterface
66
    {
67 12
        if ($uuid->getVersion() !== self::UUID_TYPE_RANDOM) {
68 1
            throw new InvalidUuidStringException('Not supported version: '.$uuid->getVersion());
69
        }
70
71 11
        return $uuid;
72
    }
73
}
74