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

DateBehaviour   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 47
ccs 15
cts 15
cp 1
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 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