| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles fetching assets like images. |
| 4 |
* |
| 5 |
* @since 1.0.0 |
| 6 |
* |
| 7 |
* @package SolidWP\Performance |
| 8 |
*/ |
| 9 |
|
| 10 |
declare( strict_types=1 ); |
| 11 |
|
| 12 |
namespace SolidWP\Performance\Assets; |
| 13 |
|
| 14 |
/** |
| 15 |
* Handles fetching assets like images. |
| 16 |
* |
| 17 |
* @since 1.0.0 |
| 18 |
* |
| 19 |
* @package SolidWP\Performance |
| 20 |
*/ |
| 21 |
final class Asset { |
| 22 |
|
| 23 |
/** |
| 24 |
* The URL to the plugin's main folder. |
| 25 |
* |
| 26 |
* @var string |
| 27 |
*/ |
| 28 |
private string $plugin_url; |
| 29 |
|
| 30 |
/** |
| 31 |
* The server path to the plugin's main folder. |
| 32 |
* |
| 33 |
* @var string |
| 34 |
*/ |
| 35 |
private string $plugin_dir; |
| 36 |
|
| 37 |
/** |
| 38 |
* @param string $plugin_url The URL to the plugin's main folder. |
| 39 |
* @param string $plugin_dir The server path to the plugin's main folder. |
| 40 |
*/ |
| 41 |
public function __construct( string $plugin_url, string $plugin_dir ) { |
| 42 |
$this->plugin_url = $plugin_url; |
| 43 |
$this->plugin_dir = $plugin_dir; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Get an asset URL. |
| 48 |
* |
| 49 |
* @param string $path A relative path to an asset. |
| 50 |
* |
| 51 |
* @return string The full URL to the asset. |
| 52 |
*/ |
| 53 |
public function get_url( string $path = '' ): string { |
| 54 |
return $this->plugin_url . $path; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Get an asset directory path. |
| 59 |
* |
| 60 |
* @param string $path A relative path to an asset. |
| 61 |
* |
| 62 |
* @return string |
| 63 |
*/ |
| 64 |
public function get_dir( string $path = '' ): string { |
| 65 |
return $this->plugin_dir . $path; |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Get the asset meta. |
| 70 |
* |
| 71 |
* @param string $path The filepath without extension, e.g. build/settings. |
| 72 |
* |
| 73 |
* @return array{dependencies?: string[], version?: string }; |
| 74 |
*/ |
| 75 |
public function get_meta( string $path = '' ): array { |
| 76 |
$asset_path = realpath( $this->get_dir() . $path . '.asset.php' ); |
| 77 |
|
| 78 |
return file_exists( $asset_path ) ? include $asset_path : []; |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Enqueue a script. |
| 83 |
* |
| 84 |
* @param string $name The name of the script. |
| 85 |
* @param string $path The relative path to the script, without extension, e.g. build/settings. |
| 86 |
* |
| 87 |
* @return void |
| 88 |
*/ |
| 89 |
public function enqueue_script( string $name, string $path ): void { |
| 90 |
$meta = $this->get_meta( $path ); |
| 91 |
|
| 92 |
wp_enqueue_script( $name, $this->get_url( "$path.js" ), $meta['dependencies'] ?? [], $meta['version'] ?? '', true ); |
| 93 |
} |
| 94 |
} |
| 95 |
|