diff --git a/src/Assets/BaseAsset.php b/src/Assets/BaseAsset.php new file mode 100644 index 0000000000..24bedb1ced --- /dev/null +++ b/src/Assets/BaseAsset.php @@ -0,0 +1,150 @@ +handle; + } + + /** + * Enqueue the asset within WordPress. + */ + public function enqueue(): void { + $this->defer_action( + $this->get_enqueue_action(), + $this->get_enqueue_closure(), + $this->enqueue_priority + ); + } + + /** + * Dequeue the asset within WordPress. + */ + public function dequeue(): void { + $this->defer_action( + $this->get_dequeue_action(), + $this->get_dequeue_closure(), + $this->dequeue_priority + ); + } + + /** + * Register a service. + */ + public function register(): void { + $this->defer_action( + $this->get_register_action(), + $this->get_register_closure(), + $this->registration_priority + ); + } + + /** + * Get the register action to use. + * + * @since 0.1.0 + * + * @return string Register action to use. + */ + protected function get_register_action(): string { + return $this->get_enqueue_action(); + } + + /** + * Get the enqueue action to use. + * + * @return string + */ + protected function get_enqueue_action(): string { + return 'wp_enqueue_scripts'; + } + + /** + * Get the enqueue action to use. + * + * @return string + */ + protected function get_dequeue_action(): string { + return 'wp_print_scripts'; + } + + /** + * Add a closure to an action, or run it immediately if the action has already fired. + * + * @param string $action + * @param Closure $closure + * @param int $priority + */ + protected function defer_action( string $action, Closure $closure, int $priority = 10 ): void { + if ( did_action( $action ) ) { + $closure(); + return; + } + + add_action( $action, $closure, $priority ); + } + + /** + * Get the enqueue closure to use. + * + * @return Closure + */ + abstract protected function get_register_closure(): Closure; + + /** + * Get the enqueue closure to use. + * + * @return Closure + */ + abstract protected function get_enqueue_closure(): Closure; + + /** + * Get the dequeue closure to use. + * + * @return Closure + */ + abstract protected function get_dequeue_closure(): Closure; +}