Completed
Pull Request — master (#9)
by Davis
02:21
created

AbstractEntity::setId()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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