-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBehavior.php
75 lines (64 loc) · 1.75 KB
/
Behavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace Horat1us\Yii\StaticBehavior\Bootstrap;
use Horat1us\Yii\StaticBehavior;
use yii\base;
use yii\di;
/**
* Class Behavior
* @package Horat1us\Yii\StaticBehavior\Bootstrap
*/
class Behavior extends base\Behavior
{
/** @var array[]|string[]|StaticBehavior[] references */
public $behaviors = [];
/** @var string[] */
public $events = [
base\Module::EVENT_BEFORE_ACTION => 'beforeAction',
base\Module::EVENT_AFTER_ACTION => 'afterAction',
];
/**
* @throws base\InvalidConfigException
*/
public function init(): void
{
parent::init();
$this->behaviors = array_map(function ($reference): StaticBehavior {
/** @var StaticBehavior $behavior */
$behavior = di\Instance::ensure($reference, StaticBehavior::class);
return $behavior;
}, $this->behaviors);
foreach ($this->events as $action => $handler) {
if (!is_string($handler) || !method_exists($this, $handler)) {
throw new base\InvalidConfigException(
"Invalid handler for {$action}: only beforeAction and afterAction supported.",
1
);
}
}
}
public function events(): array
{
return $this->events;
}
/**
* Attach static behaviors
*
* @throws base\InvalidConfigException
*/
public function beforeAction(): void
{
foreach ($this->behaviors as $behavior) {
$behavior->attach();
}
}
/**
* Clean-up attached static behavior
*/
public function afterAction(): void
{
foreach ($this->behaviors as $behavior) {
$behavior->detach();
}
}
}