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

AbstractEntity   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 58
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getId() 0 4 1
A setId() 0 8 3
A isValidString() 0 8 2
A isVersionValid() 0 8 2
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