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