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

DateBehaviour   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 47
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A beforeInsert() 0 11 3
A beforeUpdate() 0 7 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