Completed
Pull Request — master (#9)
by Samuel
03:17
created

DateBehaviour::beforeInsert()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 4
nop 1
crap 3
1
<?php
2
3
namespace SimpleMapper\Behaviour;
4
5
use Nette\Utils\DateTime;
6
use SimpleMapper\ActiveRow;
7
8
class DateBehaviour extends AbstractBehaviour
9
{
10
    /** @var string */
11
    private $createdAtField;
12
13
    /** @var string */
14
    private $updatedAtField;
15
16
    /**
17
     * @param string $createdAtField
18
     * @param string $updatedAtField
19
     */
20 68
    public function __construct(string $createdAtField = 'created_at', string $updatedAtField = 'updated_at')
21
    {
22 68
        $this->createdAtField = $createdAtField;
23 68
        $this->updatedAtField = $updatedAtField;
24 68
    }
25
26
    /**
27
     * @param array $data
28
     * @return array
29
     */
30 2
    public function beforeInsert(array $data): array
31
    {
32 2
        $now = new DateTime('now');
33 2
        if ($this->createdAtField) {
34 2
            $data[$this->createdAtField] = $now;
35
        }
36 2
        if ($this->updatedAtField) {
37 2
            $data[$this->updatedAtField] = $now;
38
        }
39 2
        return $data;
40
    }
41
42
    /**
43
     * @param ActiveRow $record
44
     * @param array $data
45
     * @return array
46
     */
47 2
    public function beforeUpdate(ActiveRow $record, array $data): array
48
    {
49 2
        if ($this->updatedAtField) {
50 2
            $data[$this->updatedAtField] = new DateTime('now');
51
        }
52 2
        return $data;
53
    }
54
}
55