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

Snapshot   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 47.06%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 9
eloc 17
c 3
b 1
f 0
dl 0
loc 48
ccs 8
cts 17
cp 0.4706
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getSnapshotBehavior() 0 5 1
A initializeSnapshot() 0 6 1
A setSnapshotBehavior() 0 3 1
A hasChangedCallback() 0 8 6
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;
13
14
use Phalcon\Mvc\Model;
15
use Zemit\Mvc\Model\AbstractTrait\AbstractEventsManager;
16
use Zemit\Mvc\Model\Behavior\Snapshot as SnapshotBehavior;
17
18
trait Snapshot
19
{
20
    use AbstractEventsManager;
21
    use Options;
22
    use Behavior;
23
    
24
    abstract protected function keepSnapshots(bool $keepSnapshot): void;
25
    
26
    /**
27
     * Initializing Snapshot
28
     */
29 2
    public function initializeSnapshot(?array $options = null): void
30
    {
31 2
        $options ??= $this->getOptionsManager()->get('snapshot') ?? [];
32
        
33 2
        $this->keepSnapshots($options['keepSnapshots'] ?? true);
34 2
        $this->setSnapshotBehavior(new SnapshotBehavior($options));
35
    }
36
    
37
    /**
38
     * Set Snapshot Behavior
39
     */
40 2
    public function setSnapshotBehavior(SnapshotBehavior $snapshotBehavior): void
41
    {
42 2
        $this->setBehavior('snapshot', $snapshotBehavior);
43
    }
44
    
45
    /**
46
     * Get Snapshot Behavior
47
     */
48
    public function getSnapshotBehavior(): SnapshotBehavior
49
    {
50
        $behavior = $this->getBehavior('snapshot');
51
        assert($behavior instanceof SnapshotBehavior);
52
        return $behavior;
53
    }
54
    
55
    /**
56
     * Check if the model has changed and return null otherwise
57
     */
58 2
    public function hasChangedCallback(callable $callback, bool $anyField = true): \Closure
59
    {
60 2
        return function (Model $model, $field) use ($callback, $anyField) {
61
            return (!$model->hasSnapshotData()
62
                || $model->hasChanged($anyField ? null : $field)
63
                || $model->hasUpdated($anyField ? null : $field))
64
                ? $callback($model, $field)
65
                : $model->readAttribute($field);
66 2
        };
67
    }
68
}
69