CallableFilter   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 76
ccs 0
cts 23
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A afterAction() 0 10 3
A resultMatch() 0 4 2
A call() 0 12 3
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\filters;
10
11
use yii\base\Action;
12
use yii\base\ActionFilter;
13
use yii\web\Controller;
14
use yii\web\Response;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 2.0.0
19
 *
20
 * @property Controller $sender
21
 */
22
class CallableFilter extends ActionFilter
23
{
24
    use ActionTrait,
25
        FormatTrait;
26
27
    /**
28
     * @var array this property defines the transformers for each action.
29
     * Each action that should only support one transformer.
30
     *
31
     * You can use `'*'` to stand for all actions. When an action is explicitly
32
     * specified, it takes precedence over the specification given by `'*'`.
33
     *
34
     * For example,
35
     *
36
     * ```php
37
     * [
38
     *   'create' => function () {
39
     *      return 'foo';
40
     *   },
41
     *   '*' => function () {
42
     *      return $this->redirect('https://google.com');
43
     *   }
44
     * ]
45
     * ```
46
     */
47
    public $actions = [];
48
49
    /**
50
     * Allow redirection of a null result
51
     * @var bool
52
     */
53
    public $allowNull = false;
54
55
    /**
56
     * @param \yii\base\Action $action
57
     * @param mixed $result
58
     * @return mixed|Response
59
     */
60
    public function afterAction($action, $result)
61
    {
62
        if ($this->formatMatch($action->id) &&
63
            $this->resultMatch($result)
64
        ) {
65
            return $this->call($action, $result);
66
        }
67
68
        return parent::afterAction($action, $result);
69
    }
70
71
    /**
72
     * @param $result
73
     * @return bool
74
     */
75
    protected function resultMatch($result): bool
76
    {
77
        return $result !== null || ($this->allowNull === true);
78
    }
79
80
    /**
81
     * @param Action $action
82
     * @param $data
83
     * @return mixed
84
     */
85
    protected function call(Action $action, $data)
86
    {
87
        if (!$callable = $this->findAction($action->id)) {
88
            return $data;
89
        }
90
91
        if (is_callable($callable)) {
92
            return call_user_func_array($callable, [$data, $this]);
93
        }
94
95
        return $data;
96
    }
97
}
98