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\ModelInterface; |
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
|
|
|
|
22
|
|
|
public SnapshotBehavior $snapshotBehavior; |
23
|
|
|
|
24
|
|
|
abstract protected function keepSnapshots(bool $keepSnapshot): void; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Initializing Snapshot |
28
|
|
|
*/ |
29
|
|
|
public function initializeSnapshot(?array $options = null): void |
30
|
|
|
{ |
31
|
|
|
$options ??= $this->getOptionsManager()->get('snapshot') ?? []; |
|
|
|
|
32
|
|
|
$this->keepSnapshots($options['keepSnapshots'] ?? true); |
33
|
|
|
$this->addBehavior(new SnapshotBehavior($options)); |
|
|
|
|
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Set Snapshot Behavior |
38
|
|
|
*/ |
39
|
|
|
public function setSnapshotBehavior(SnapshotBehavior $snapshotBehavior): void |
40
|
|
|
{ |
41
|
|
|
$this->snapshotBehavior = $snapshotBehavior; |
42
|
|
|
$this->addBehavior($this->snapshotBehavior); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Get Snapshot Behavior |
47
|
|
|
*/ |
48
|
|
|
public function getSnapshotBehavior(): SnapshotBehavior |
49
|
|
|
{ |
50
|
|
|
return $this->snapshotBehavior; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Check if the model has changed and return null otherwise |
55
|
|
|
*/ |
56
|
|
|
public function hasChangedCallback(callable $callback, bool $anyField = true): \Closure |
57
|
|
|
{ |
58
|
|
|
return function (ModelInterface $model, $field) use ($callback, $anyField) { |
59
|
|
|
return (!$model->hasSnapshotData() |
|
|
|
|
60
|
|
|
|| $model->hasChanged($anyField ? null : $field) |
|
|
|
|
61
|
|
|
|| $model->hasUpdated($anyField ? null : $field)) |
|
|
|
|
62
|
|
|
? $callback($model, $field) |
63
|
|
|
: $model->readAttribute($field); |
|
|
|
|
64
|
|
|
}; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|