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\Behavior; |
13
|
|
|
|
14
|
|
|
use Phalcon\Mvc\Model\Behavior; |
15
|
|
|
use Phalcon\Mvc\ModelInterface; |
16
|
|
|
use Zemit\Mvc\Model\Behavior\Traits\SkippableTrait; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Zemit\Mvc\Model\Traits\Behavior\Conditional |
20
|
|
|
* |
21
|
|
|
* Allows to automatically update a model’s attribute saving the datetime when a |
22
|
|
|
* record is created or updated |
23
|
|
|
*/ |
24
|
|
|
class Conditional extends Behavior |
25
|
|
|
{ |
26
|
|
|
use SkippableTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Listens for notifications from the models manager |
30
|
|
|
*/ |
31
|
|
|
public function notify(string $type, ModelInterface $model): ?bool |
32
|
|
|
{ |
33
|
|
|
if (!$this->isEnabled()) { |
34
|
|
|
return null; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if (!$this->mustTakeAction($type)) { |
38
|
|
|
return null; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$options = $this->getOptions($type); |
42
|
|
|
if (empty($options)) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$field = $this->getOption('field', $options, [$type, $model]); |
47
|
|
|
$condition = $this->getOption('condition', $options, [$type, $model, $field]); |
48
|
|
|
|
49
|
|
|
if (!empty($field) && is_string($field) && $condition === true) { |
50
|
|
|
$value = $this->getOption('value', $options, [$type, $model, $field]); |
51
|
|
|
$transformedValue = $this->getOption('transform', $options, [$type, $model, $field, $value]); |
52
|
|
|
$model->assign([$field => $transformedValue]); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return true; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string $key |
60
|
|
|
* @param array $options |
61
|
|
|
* @param array|null $params |
62
|
|
|
* |
63
|
|
|
* @return mixed|null |
64
|
|
|
*/ |
65
|
|
|
public function getOption(string $key, array $options, array $params = null): mixed |
66
|
|
|
{ |
67
|
|
|
$ret = $options[$key] ?? null; |
68
|
|
|
if (is_callable($ret)) { |
69
|
|
|
$ret = $ret(...$params); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $ret; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|