Completed
Push — master ( f7ceef...6986d0 )
by Alejandro
16s
created

ApiKey::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Entity;
5
6
use Cake\Chronos\Chronos;
7
use Doctrine\ORM\Mapping as ORM;
8
use Shlinkio\Shlink\Common\Entity\AbstractEntity;
9
use Shlinkio\Shlink\Common\Util\StringUtilsTrait;
10
11
/**
12
 * Class ApiKey
13
 * @author Shlink
14
 * @link http://shlink.io
15
 *
16
 * @ORM\Entity()
17
 * @ORM\Table(name="api_keys")
18
 */
19
class ApiKey extends AbstractEntity
20
{
21
    use StringUtilsTrait;
22
23
    /**
24
     * @var string
25
     * @ORM\Column(name="`key`", nullable=false, unique=true)
26
     */
27
    private $key;
28
    /**
29
     * @var Chronos|null
30
     * @ORM\Column(name="expiration_date", nullable=true, type="chronos_datetime")
31
     */
32
    private $expirationDate;
33
    /**
34
     * @var bool
35
     * @ORM\Column(type="boolean")
36
     */
37
    private $enabled;
38
39 13
    public function __construct(?Chronos $expirationDate = null)
40
    {
41 13
        $this->key = $this->generateV4Uuid();
42 13
        $this->expirationDate = $expirationDate;
43 13
        $this->enabled = true;
44 13
    }
45
46 4
    public function getExpirationDate(): ?Chronos
47
    {
48 4
        return $this->expirationDate;
49
    }
50
51 5
    public function isExpired(): bool
52
    {
53 5
        if ($this->expirationDate === null) {
54 4
            return false;
55
        }
56
57 1
        return $this->expirationDate->lt(Chronos::now());
58
    }
59
60 8
    public function isEnabled(): bool
61
    {
62 8
        return $this->enabled;
63
    }
64
65 3
    public function disable(): self
66
    {
67 3
        $this->enabled = false;
68 3
        return $this;
69
    }
70
71
    /**
72
     * Tells if this api key is enabled and not expired
73
     */
74 5
    public function isValid(): bool
75
    {
76 5
        return $this->isEnabled() && ! $this->isExpired();
77
    }
78
79 4
    public function __toString(): string
80
    {
81 4
        return $this->key;
82
    }
83
}
84