| 1 |
<?php |
| 2 |
|
| 3 |
namespace YayMail\TemplateLibrary; |
| 4 |
|
| 5 |
use YayMail\Abstracts\BaseTemplate; |
| 6 |
use YayMail\Utils\SingletonTrait; |
| 7 |
|
| 8 |
/** |
| 9 |
* Service responsible for registering and exposing code-defined email templates |
| 10 |
* for the Template Library feature. |
| 11 |
*/ |
| 12 |
class TemplateLibraryService { |
| 13 |
use SingletonTrait; |
| 14 |
|
| 15 |
/** |
| 16 |
* @var BaseTemplate[] |
| 17 |
*/ |
| 18 |
protected $templates = []; |
| 19 |
|
| 20 |
/** |
| 21 |
* Constructor. |
| 22 |
* |
| 23 |
* @return void |
| 24 |
*/ |
| 25 |
protected function __construct() { |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Programmatically register a template class. |
| 30 |
* |
| 31 |
* @param BaseTemplate $template Template instance. |
| 32 |
* |
| 33 |
* @return void |
| 34 |
*/ |
| 35 |
public function register( BaseTemplate $template ) { |
| 36 |
if ( ! $template instanceof BaseTemplate ) { |
| 37 |
return; |
| 38 |
} |
| 39 |
|
| 40 |
if ( in_array( $template, $this->templates, true ) ) { |
| 41 |
return; |
| 42 |
} |
| 43 |
|
| 44 |
$template_key = $template->get_id(); |
| 45 |
|
| 46 |
$this->templates[ $template_key ] = $template; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Get list of template summaries for given email type |
| 51 |
* |
| 52 |
* @param string $email_type YayMail email/template name. Example: 'new_order'. |
| 53 |
* |
| 54 |
* @return array[] |
| 55 |
*/ |
| 56 |
public function get_list( $email_type ) { |
| 57 |
$results = []; |
| 58 |
|
| 59 |
foreach ( $this->templates as $template ) { |
| 60 |
if ( $template->get_email_type() !== $email_type ) { |
| 61 |
continue; |
| 62 |
} |
| 63 |
|
| 64 |
$results[] = $template->get_template_data(); |
| 65 |
} |
| 66 |
|
| 67 |
usort( |
| 68 |
$results, |
| 69 |
function( $a, $b ) { |
| 70 |
$pos_a = isset( $a['position'] ) ? (int) $a['position'] : 10; |
| 71 |
$pos_b = isset( $b['position'] ) ? (int) $b['position'] : 10; |
| 72 |
|
| 73 |
if ( $pos_a === $pos_b ) { |
| 74 |
return strcmp( (string) ( $a['name'] ?? '' ), (string) ( $b['name'] ?? '' ) ); |
| 75 |
} |
| 76 |
|
| 77 |
return $pos_a - $pos_b; |
| 78 |
} |
| 79 |
); |
| 80 |
|
| 81 |
return $results; |
| 82 |
} |
| 83 |
} |
| 84 |
|