| 1 |
<?php |
| 2 |
/** |
| 3 |
* OpenStation App Framework — standalone Hooks adapter. |
| 4 |
* |
| 5 |
* A minimal in-process hook bus with the same semantics as |
| 6 |
* WordPress's: filters return the value, actions return nothing, |
| 7 |
* callbacks run in ascending priority then registration order. |
| 8 |
* |
| 9 |
* @package OpenStation |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace OpenStation\App\Standalone; |
| 13 |
|
| 14 |
use OpenStation\App\Contracts\Hooks as HooksContract; |
| 15 |
|
| 16 |
// Direct access, unless a standalone host is booting on bare PHP. |
| 17 |
if ( ! defined( 'ABSPATH' ) ) { |
| 18 |
defined( 'OPENSTATION_STANDALONE' ) || exit; |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* In-process hook bus. |
| 23 |
*/ |
| 24 |
final class Hooks implements HooksContract { |
| 25 |
|
| 26 |
/** |
| 27 |
* `hook => priority => callable[]`. |
| 28 |
* |
| 29 |
* @var array<string,array<int,callable[]>> |
| 30 |
*/ |
| 31 |
private $callbacks = array(); |
| 32 |
|
| 33 |
/** |
| 34 |
* Register a callback for a filter or an action. |
| 35 |
* |
| 36 |
* @param string $hook Hook name. |
| 37 |
* @param callable $callback Callback. |
| 38 |
* @param int $priority Lower runs first. Default 10. |
| 39 |
* @return void |
| 40 |
*/ |
| 41 |
public function add( $hook, callable $callback, $priority = 10 ) { |
| 42 |
$this->callbacks[ $hook ][ (int) $priority ][] = $callback; |
| 43 |
ksort( $this->callbacks[ $hook ] ); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Drop every callback registered for a hook. |
| 48 |
* |
| 49 |
* @param string $hook Hook name. |
| 50 |
* @return void |
| 51 |
*/ |
| 52 |
public function remove_all( $hook ) { |
| 53 |
unset( $this->callbacks[ $hook ] ); |
| 54 |
} |
| 55 |
|
| 56 |
/** {@inheritDoc} */ |
| 57 |
public function filter( $hook, $value, ...$args ) { |
| 58 |
if ( empty( $this->callbacks[ $hook ] ) ) { |
| 59 |
return $value; |
| 60 |
} |
| 61 |
foreach ( $this->callbacks[ $hook ] as $callbacks ) { |
| 62 |
foreach ( $callbacks as $callback ) { |
| 63 |
$value = call_user_func( $callback, $value, ...$args ); |
| 64 |
} |
| 65 |
} |
| 66 |
return $value; |
| 67 |
} |
| 68 |
|
| 69 |
/** {@inheritDoc} */ |
| 70 |
public function action( $hook, ...$args ) { |
| 71 |
if ( empty( $this->callbacks[ $hook ] ) ) { |
| 72 |
return; |
| 73 |
} |
| 74 |
foreach ( $this->callbacks[ $hook ] as $callbacks ) { |
| 75 |
foreach ( $callbacks as $callback ) { |
| 76 |
call_user_func( $callback, ...$args ); |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|