Completed
Pull Request — master (#9)
by Samuel
15:22
created

DateBehaviour::beforeUpdate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
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
    public function __construct(string $createdAtField = 'created_at', string $updatedAtField = 'updated_at')
21
    {
22
        $this->createdAtField = $createdAtField;
23
        $this->updatedAtField = $updatedAtField;
24
    }
25
26
    /**
27
     * @param array $data
28
     * @return array
29
     */
30
    public function beforeInsert(array $data): array
31
    {
32
        $now = new DateTime('now');
33
        if ($this->createdAtField) {
34
            $data[$this->createdAtField] = $now;
35
        }
36
        if ($this->updatedAtField) {
37
            $data[$this->updatedAtField] = $now;
38
        }
39
        return $data;
40
    }
41
42
    /**
43
     * @param ActiveRow $record
44
     * @param array $data
45
     * @return array
46
     */
47
    public function beforeUpdate(ActiveRow $record, array $data): array
48
    {
49
        if ($this->updatedAtField) {
50
            $data[$this->updatedAtField] = new DateTime('now');
51
        }
52
        return $data;
53
    }
54
}
55