| 1 |
<?php |
| 2 |
|
| 3 |
namespace YayMail\TemplateLibrary; |
| 4 |
|
| 5 |
use YayMail\Abstracts\BaseTemplate; |
| 6 |
use YayMail\Utils\Helpers; |
| 7 |
use YayMail\Utils\SingletonTrait; |
| 8 |
|
| 9 |
/** |
| 10 |
* Loader that auto-discovers and registers Template Library templates |
| 11 |
* from the Templates directory. Add new template classes under |
| 12 |
* Templates/{EmailType}/{TemplateName}.php and they will be registered automatically. |
| 13 |
* |
| 14 |
* @method static TemplateLibraryLoader get_instance() |
| 15 |
*/ |
| 16 |
class TemplateLibraryLoader { |
| 17 |
use SingletonTrait; |
| 18 |
|
| 19 |
private function __construct() { |
| 20 |
$this->load_templates_from_directory(); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Recursively scan a directory for PHP files and register template classes. |
| 25 |
* |
| 26 |
* @return void |
| 27 |
*/ |
| 28 |
protected function load_templates_from_directory() { |
| 29 |
$template_library_service = TemplateLibraryService::get_instance(); |
| 30 |
$templates_base_path = Helpers::get_plugin_path() . '/src/TemplateLibrary/Templates'; |
| 31 |
$templates_base_namespace = 'YayMail\\TemplateLibrary\\Templates'; |
| 32 |
|
| 33 |
if ( ! is_dir( $templates_base_path ) ) { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
$iterator = new \RecursiveIteratorIterator( |
| 38 |
new \RecursiveDirectoryIterator( $templates_base_path, \RecursiveDirectoryIterator::SKIP_DOTS ), |
| 39 |
\RecursiveIteratorIterator::SELF_FIRST |
| 40 |
); |
| 41 |
|
| 42 |
foreach ( $iterator as $fileinfo ) { |
| 43 |
if ( ! $fileinfo->isFile() || $fileinfo->getExtension() !== 'php' ) { |
| 44 |
continue; |
| 45 |
} |
| 46 |
|
| 47 |
$relative_path = substr( $fileinfo->getPathname(), strlen( $templates_base_path ) + 1 ); |
| 48 |
$relative_path = str_replace( '\\', '/', $relative_path ); |
| 49 |
$class_name = str_replace( '/', '\\', pathinfo( $relative_path, PATHINFO_DIRNAME ) . '/' . pathinfo( $relative_path, PATHINFO_FILENAME ) ); |
| 50 |
$class_name = trim( $class_name, '\\' ); |
| 51 |
$full_class = $templates_base_namespace . '\\' . $class_name; |
| 52 |
|
| 53 |
if ( class_exists( $full_class ) && is_subclass_of( $full_class, BaseTemplate::class, true ) ) { |
| 54 |
$template_library_service->register( $full_class::get_instance() ); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
do_action( 'yaymail_register_template_library', $template_library_service ); |
| 59 |
} |
| 60 |
} |
| 61 |
|