| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Yatra\Core\Assets; |
| 6 |
|
| 7 |
/** |
| 8 |
* Base Asset Manager |
| 9 |
* |
| 10 |
* Handles asset enqueuing for different page types |
| 11 |
*/ |
| 12 |
abstract class BaseAssetManager |
| 13 |
{ |
| 14 |
/** |
| 15 |
* Page type this manager handles |
| 16 |
*/ |
| 17 |
protected string $page_type; |
| 18 |
|
| 19 |
/** |
| 20 |
* Asset handles to enqueue |
| 21 |
*/ |
| 22 |
protected array $styles = []; |
| 23 |
protected array $scripts = []; |
| 24 |
|
| 25 |
/** |
| 26 |
* Localize data for scripts |
| 27 |
*/ |
| 28 |
protected array $localize_data = []; |
| 29 |
|
| 30 |
/** |
| 31 |
* Constructor |
| 32 |
*/ |
| 33 |
public function __construct(string $page_type) |
| 34 |
{ |
| 35 |
$this->page_type = $page_type; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Enqueue assets for this page type |
| 40 |
*/ |
| 41 |
public function enqueueAssets(): void |
| 42 |
{ |
| 43 |
$this->enqueueStyles(); |
| 44 |
$this->enqueueScripts(); |
| 45 |
$this->localizeScripts(); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Enqueue styles |
| 50 |
*/ |
| 51 |
protected function enqueueStyles(): void |
| 52 |
{ |
| 53 |
foreach ($this->styles as $handle) { |
| 54 |
wp_enqueue_style($handle); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Enqueue scripts |
| 60 |
*/ |
| 61 |
protected function enqueueScripts(): void |
| 62 |
{ |
| 63 |
foreach ($this->scripts as $handle) { |
| 64 |
wp_enqueue_script($handle); |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Localize scripts with data |
| 70 |
*/ |
| 71 |
protected function localizeScripts(): void |
| 72 |
{ |
| 73 |
foreach ($this->localize_data as $script_handle => $data) { |
| 74 |
wp_localize_script($script_handle, $data['object_name'], $data['data']); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Add style to enqueue |
| 80 |
*/ |
| 81 |
protected function addStyle(string $handle): void |
| 82 |
{ |
| 83 |
$this->styles[] = $handle; |
| 84 |
} |
| 85 |
|
| 86 |
/** |
| 87 |
* Add script to enqueue |
| 88 |
*/ |
| 89 |
protected function addScript(string $handle): void |
| 90 |
{ |
| 91 |
$this->scripts[] = $handle; |
| 92 |
} |
| 93 |
|
| 94 |
/** |
| 95 |
* Add localization data |
| 96 |
*/ |
| 97 |
protected function addLocalization(string $script_handle, string $object_name, array $data): void |
| 98 |
{ |
| 99 |
$this->localize_data[$script_handle] = [ |
| 100 |
'object_name' => $object_name, |
| 101 |
'data' => $data |
| 102 |
]; |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Get page type |
| 107 |
*/ |
| 108 |
public function getPageType(): string |
| 109 |
{ |
| 110 |
return $this->page_type; |
| 111 |
} |
| 112 |
} |
| 113 |
|