1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
use Silk\Event\Hook; |
4
|
|
|
|
5
|
|
|
if (! function_exists('on')) : |
6
|
|
|
/** |
7
|
|
|
* Create and set a new event listener. |
8
|
|
|
* |
9
|
|
|
* @param string $handle action or filter handle |
10
|
|
|
* @param callable $callback |
11
|
|
|
* @param int $priority |
12
|
|
|
* |
13
|
|
|
* @return Hook |
14
|
|
|
*/ |
15
|
|
|
function on($handle, callable $callback, $priority = 10) |
16
|
|
|
{ |
17
|
|
|
return Hook::on($handle, $priority) |
18
|
|
|
->setCallback($callback) |
19
|
|
|
->listen(); |
20
|
|
|
} |
21
|
|
|
endif; |
22
|
|
|
|
23
|
|
|
if (! function_exists('off')) : |
24
|
|
|
/** |
25
|
|
|
* Remove an event listener. |
26
|
|
|
* |
27
|
|
|
* If the callback cannot be removed immediately, attempt to remove it just-in-time as a fallback. |
28
|
|
|
* |
29
|
|
|
* @param string $handle action or filter handle |
30
|
|
|
* @param callable $callback |
31
|
|
|
* @param int $priority |
32
|
|
|
* |
33
|
|
|
* @return bool|Hook true if immediately removed, Hook instance otherwise |
34
|
|
|
*/ |
35
|
|
|
function off($handle, $callback, $priority = 10) |
36
|
|
|
{ |
37
|
|
|
if ($removed = remove_filter($handle, $callback, $priority)) { |
38
|
|
|
return $removed; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* If the hook was not able to be removed above, then it has not been set yet. |
43
|
|
|
* Here we add a new listener right before the hook is expected to fire, |
44
|
|
|
* so that if it is there, we can unhook it just in time. |
45
|
|
|
*/ |
46
|
|
|
return on($handle, function ($given = null) use ($handle, $callback, $priority) { |
47
|
|
|
remove_filter($handle, $callback, $priority); |
48
|
|
|
return $given; |
49
|
|
|
})->withPriority($priority - 1); |
50
|
|
|
} |
51
|
|
|
endif; |
52
|
|
|
|