HasLifecycleTrait::generateStage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 1
b 0
f 1
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Nip\Controllers\Events;
4
5
use Closure;
6
7
/**
8
 * Trait HasLifecycleTrait
9
 * @package Nip\Controllers\Traits
10
 */
11
trait HasLifecycleTrait
12
{
13
    /**
14
     * @var StageCallbacks[]
15
     */
16
    protected $stages = [];
17
18
    /**
19
     * @param $stage
20
     * @param callable $callback
21
     */
22
    protected function on(string $stage, callable $callback)
23
    {
24
        $this->stage($stage)->add($callback);
25
    }
26
27
    /**
28
     * @param Closure $callback
29
     */
30
    protected function onParseRequest(callable $callback)
31
    {
32
        $this->on('parseRequest', $callback);
33
    }
34
35
    /**
36
     * @param Closure $callback
37
     */
38
    protected function before(callable $callback)
39
    {
40
        $this->on('beforeAction', $callback);
41
    }
42
43
    /**
44
     * @param Closure $callback
45
     */
46
    protected function after(callable $callback)
47
    {
48
        $this->on('afterAction', $callback);
49
    }
50
51
    /**
52
     * @param string $stage
53
     */
54 1
    protected function invokeStage(string $stage)
55
    {
56 1
        if (method_exists($this, $stage)) {
57 1
            $this->{$stage}();
58
        }
59 1
        $this->stage($stage)->run();
60 1
    }
61
62
    /**
63
     * @param string $name
64
     * @return StageCallbacks
65
     */
66 1
    protected function stage($name)
67
    {
68 1
        if (!isset($this->stages[$name])) {
69 1
            $this->stages[$name] = $this->generateStage($name);
70
        }
71 1
        return $this->stages[$name];
72
    }
73
74
    /**
75
     * @param $name
76
     * @return StageCallbacks
77
     */
78 1
    protected function generateStage($name)
79
    {
80 1
        return new StageCallbacks();
81
    }
82
}
83