DateTimeCreatedTrait::getCreatedAtString()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RedRat\Entity;
6
7
use DateTimeInterface;
8
use Exception;
9
10
/**
11
 * DateTimeCreated Trait
12
 *
13
 * @package RedRat\Entity
14
 */
15
trait DateTimeCreatedTrait
16
{
17
    /**
18
     * @var DateTimeInterface
19
     */
20
    private $createdAt;
21
22
    /**
23
     * @var string
24
     */
25
    protected static $createdAtStringFormat = 'Y-m-d H:i:s';
26
27
    /**
28
     * @return DateTimeInterface|null
29
     */
30 8
    public function getCreatedAt(): ?DateTimeInterface
31
    {
32 8
        return $this->createdAt;
33
    }
34
35
    /**
36
     * @param string|null $format
37
     * @return string|null
38
     */
39 3
    public function getCreatedAtString(?string $format = null): ?string
40
    {
41 3
        if (!$this->hasCreatedAt()) {
42 1
            return null;
43
        }
44
45
        return $this
46 2
            ->getCreatedAt()
47 2
            ->format($format ?? self::$createdAtStringFormat)
48
        ;
49
    }
50
51
    /**
52
     * @return bool
53
     */
54 5
    public function hasCreatedAt(): bool
55
    {
56 5
        return $this->getCreatedAt() instanceof DateTimeInterface;
57
    }
58
59
    /**
60
     * @param DateTimeInterface $createdAt
61
     * @return void
62
     */
63 5
    public function setCreatedAt(DateTimeInterface $createdAt): void
64
    {
65 5
        $this->createdAt = $createdAt;
66 5
    }
67
68
    /**
69
     * @return void
70
     * @throws Exception
71
     */
72 1
    public function forgeCreatedAt(): void
73
    {
74 1
        $this->setCreatedAt(
75 1
            new \DateTime('now')
76
        );
77 1
    }
78
}
79