| 1 |
<?php |
| 2 |
|
| 3 |
namespace Boxzilla; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Class Bootstrapper |
| 9 |
* @package Boxzilla |
| 10 |
* |
| 11 |
* @method void admin( callable $callback ) |
| 12 |
* @method void cron( callable $callback ) |
| 13 |
* @method void front( callable $callback ) |
| 14 |
* @method void ajax( callable $callback ) |
| 15 |
* @method void cli( callable $callback ) |
| 16 |
*/ |
| 17 |
class Bootstrapper { |
| 18 |
|
| 19 |
/** |
| 20 |
* @var array |
| 21 |
*/ |
| 22 |
private $bootstrappers = array( |
| 23 |
'admin' => array(), |
| 24 |
'ajax' => array(), |
| 25 |
'cli' => array(), |
| 26 |
'cron' => array(), |
| 27 |
'front' => array(), |
| 28 |
'global' => array(), |
| 29 |
); |
| 30 |
|
| 31 |
/** |
| 32 |
* @param string $section |
| 33 |
* @param callable $callable |
| 34 |
*/ |
| 35 |
public function register( $section, $callable ) { |
| 36 |
|
| 37 |
if( ! isset( $this->bootstrappers[ $section ] ) ) { |
| 38 |
throw new InvalidArgumentException( "Section $section is invalid." ); |
| 39 |
} |
| 40 |
|
| 41 |
if( ! is_callable( $callable ) ) { |
| 42 |
throw new InvalidArgumentException( 'Callable argument is not callable.' ); |
| 43 |
} |
| 44 |
|
| 45 |
$this->bootstrappers[ $section ][] = $callable; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* @param string $name |
| 50 |
* @param array $arguments |
| 51 |
*/ |
| 52 |
public function __call( $name, $arguments ) { |
| 53 |
if( isset( $this->bootstrappers[ $name ] ) ) { |
| 54 |
$this->register( $name, $arguments[0] ); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Run registered bootstrappers |
| 60 |
* |
| 61 |
* @param string $section |
| 62 |
*/ |
| 63 |
public function run( $section = '' ) { |
| 64 |
|
| 65 |
if( ! $section ) { |
| 66 |
$section = $this->section(); |
| 67 |
} |
| 68 |
|
| 69 |
foreach( $this->bootstrappers['global'] as $callback ) { |
| 70 |
$callback(); |
| 71 |
} |
| 72 |
|
| 73 |
foreach( $this->bootstrappers[ $section ] as $callback ) { |
| 74 |
$callback(); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Get currently active section. |
| 80 |
* |
| 81 |
* @return string |
| 82 |
*/ |
| 83 |
public function section() { |
| 84 |
if( is_admin() ) { |
| 85 |
if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { |
| 86 |
return 'ajax'; |
| 87 |
} else { |
| 88 |
return 'admin'; |
| 89 |
} |
| 90 |
} else { |
| 91 |
if( defined( 'DOING_CRON' ) && DOING_CRON ) { |
| 92 |
return 'cron'; |
| 93 |
} else if( defined( 'WP_CLI' ) && WP_CLI ) { |
| 94 |
return 'cli'; |
| 95 |
} else { |
| 96 |
return 'front'; |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
} |