Timestamps::onSave()   B
last analyzed

Complexity

Conditions 7
Paths 15

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 9
c 1
b 0
f 0
nc 15
nop 2
dl 0
loc 17
rs 8.8333
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm\Behaviour;
5
6
use Sirius\Orm\Action\ActionInterface;
7
use Sirius\Orm\Action\Insert;
8
use Sirius\Orm\Action\Update;
9
use Sirius\Orm\Mapper;
10
11
class Timestamps implements BehaviourInterface
12
{
13
14
    /**
15
     * @var string
16
     */
17
    protected $createColumn;
18
    /**
19
     * @var string
20
     */
21
    protected $updateColumn;
22
23
    public function __construct($createColumn = 'created_at', $updateColumn = 'updated_at')
24
    {
25
        $this->createColumn = $createColumn;
26
        $this->updateColumn = $updateColumn;
27
    }
28
29
    public function getName()
30
    {
31
        return 'timestamps';
32
    }
33
34
    public function onSave(/** @scrutinizer ignore-unused */Mapper $mapper, ActionInterface $action)
35
    {
36
        if ($action instanceof Insert) {
37
            if ($this->createColumn) {
38
                $action->addColumns([$this->createColumn => time()]);
39
            }
40
            if ($this->updateColumn) {
41
                $action->addColumns([$this->updateColumn => time()]);
42
            }
43
        }
44
        if ($action instanceof Update && $this->updateColumn) {
45
            if (! empty($action->getEntity()->getChanges())) {
46
                $action->addColumns([$this->updateColumn => time()]);
47
            }
48
        }
49
50
        return $action;
51
    }
52
}
53