Completed
Push — master ( 6067eb...3f355c )
by Samuel
15:57 queued 01:01
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
declare(strict_types=1);
4
5
namespace SimpleMapper\Behaviour;
6
7
use Nette\Utils\DateTime;
8
use SimpleMapper\ActiveRow;
9
10
class DateBehaviour extends AbstractBehaviour
11
{
12
    /** @var string */
13
    private $createdAtField;
14
15
    /** @var string */
16
    private $updatedAtField;
17
18
    /**
19
     * @param string $createdAtField
20
     * @param string $updatedAtField
21
     */
22
    public function __construct(string $createdAtField = 'created_at', string $updatedAtField = 'updated_at')
23
    {
24
        $this->createdAtField = $createdAtField;
25
        $this->updatedAtField = $updatedAtField;
26
    }
27
28
    /**
29
     * @param array $data
30
     * @return array
31
     */
32
    public function beforeInsert(array $data): array
33
    {
34
        $now = new DateTime('now');
35
        if ($this->createdAtField) {
36
            $data[$this->createdAtField] = $now;
37
        }
38
        if ($this->updatedAtField) {
39
            $data[$this->updatedAtField] = $now;
40
        }
41
        return $data;
42
    }
43
44
    /**
45
     * @param ActiveRow $record
46
     * @param array $data
47
     * @return array
48
     */
49
    public function beforeUpdate(ActiveRow $record, array $data): array
50
    {
51
        if ($this->updatedAtField) {
52
            $data[$this->updatedAtField] = new DateTime('now');
53
        }
54
        return $data;
55
    }
56
}
57