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
|
|
|
|