Passed
Push — master ( 91844f...3ae4be )
by Julien
07:39
created

Conditional   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 49
ccs 0
cts 20
cp 0
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getOption() 0 8 2
B notify() 0 25 7
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