Test Failed
Push — master ( ce60e5...378563 )
by Julien
12:41 queued 07:49
created

Updated::initializeUpdated()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1.0054

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 21
ccs 14
cts 17
cp 0.8235
rs 9.7998
cc 1
nc 1
nop 1
crap 1.0054
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Mvc\Model\Blameable;
13
14
use Zemit\Db\Column;
15
use Zemit\Mvc\Model\AbstractTrait\AbstractBehavior;
16
use Zemit\Mvc\Model\AbstractTrait\AbstractBlameable;
17
use Zemit\Mvc\Model\Behavior\Transformable;
18
use Zemit\Mvc\Model\Identity;
19
use Zemit\Mvc\Model\Options;
20
use Zemit\Mvc\Model\Snapshot;
21
use Zemit\Mvc\Model\SoftDelete;
22
23
trait Updated
24
{
25
    use AbstractBehavior;
26
    use AbstractBlameable;
27
    use Options;
28
    use Identity;
29
    use Snapshot;
30
    use SoftDelete;
31
    use BlameAt;
32
    
33
    /**
34
     * Initializing Updated
35
     */
36 2
    public function initializeUpdated(?array $options = null): void
37
    {
38 2
        $options ??= $this->getOptionsManager()->get('updated') ?? [];
39
        
40 2
        $fieldBy = $options['fieldBy'] ?? 'updatedBy';
41 2
        $fieldAs = $options['fieldAs'] ?? 'updatedAs';
42 2
        $fieldAt = $options['fieldAt'] ?? 'updatedAt';
43
        
44 2
        $this->addUserRelationship($fieldBy, 'UpdatedBy');
45 2
        $this->addUserRelationship($fieldAs, 'UpdatedAs');
46
        
47 2
        $this->setUpdatedBehavior(new Transformable([
48 2
            'beforeValidationOnUpdate' => [
49 2
                $fieldBy => $this->hasChangedCallback(function () {
50
                    return $this->getCurrentUserIdCallback(false)();
51 2
                }),
52 2
                $fieldAs => $this->hasChangedCallback(function () {
53
                    return $this->getCurrentUserIdCallback(true)();
54 2
                }),
55 2
                $fieldAt => $this->hasChangedCallback(function () {
56
                    return $this->getDateCallback(Column::DATETIME_FORMAT)();
57 2
                }),
58 2
            ],
59 2
        ]));
60
    }
61
    
62
    /**
63
     * Set Updated Behavior
64
     */
65 2
    public function setUpdatedBehavior(Transformable $updatedBehavior): void
66
    {
67 2
        $this->setBehavior('updated', $updatedBehavior);
68
    }
69
    
70
    /**
71
     * Get Updated Behavior
72
     */
73
    public function getUpdatedBehavior(): Transformable
74
    {
75
        $behavior = $this->getBehavior('updated');
76
        assert($behavior instanceof Transformable);
77
        return $behavior;
78
    }
79
}
80