| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Yatra\Shortcodes; |
| 6 |
|
| 7 |
use Yatra\Services\SettingsService; |
| 8 |
|
| 9 |
/** |
| 10 |
* Base Shortcode Class |
| 11 |
* |
| 12 |
* Provides common functionality for all Yatra shortcodes |
| 13 |
*/ |
| 14 |
abstract class BaseShortcode |
| 15 |
{ |
| 16 |
/** |
| 17 |
* The shortcode tag |
| 18 |
*/ |
| 19 |
protected string $tag; |
| 20 |
|
| 21 |
/** |
| 22 |
* Default attributes for the shortcode |
| 23 |
*/ |
| 24 |
protected array $default_attributes = []; |
| 25 |
|
| 26 |
/** |
| 27 |
* Constructor |
| 28 |
*/ |
| 29 |
public function __construct(string $tag, array $default_attributes = []) |
| 30 |
{ |
| 31 |
$this->tag = $tag; |
| 32 |
$this->default_attributes = $default_attributes; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Register the shortcode |
| 37 |
*/ |
| 38 |
public function register(): void |
| 39 |
{ |
| 40 |
add_shortcode($this->tag, [$this, 'render']); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Render the shortcode |
| 45 |
*/ |
| 46 |
public function render(array $atts = []): string |
| 47 |
{ |
| 48 |
$atts = shortcode_atts($this->default_attributes, $atts, $this->tag); |
| 49 |
|
| 50 |
try { |
| 51 |
return $this->renderContent($atts); |
| 52 |
} catch (\Exception $e) { |
| 53 |
if (defined('WP_DEBUG') && WP_DEBUG) { |
| 54 |
return sprintf( |
| 55 |
'<div class="yatra-error">Shortcode Error: %s</div>', |
| 56 |
esc_html($e->getMessage()) |
| 57 |
); |
| 58 |
} |
| 59 |
return ''; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Render the shortcode content |
| 65 |
* Must be implemented by child classes |
| 66 |
*/ |
| 67 |
abstract protected function renderContent(array $atts): string; |
| 68 |
|
| 69 |
/** |
| 70 |
* Get the shortcode tag |
| 71 |
*/ |
| 72 |
public function getTag(): string |
| 73 |
{ |
| 74 |
return $this->tag; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Load a template file |
| 79 |
*/ |
| 80 |
protected function loadTemplate(string $template_path, array $data = []): string |
| 81 |
{ |
| 82 |
$full_path = $this->getTemplatePath($template_path); |
| 83 |
|
| 84 |
if (!file_exists($full_path)) { |
| 85 |
if (defined('WP_DEBUG') && WP_DEBUG) { |
| 86 |
return sprintf( |
| 87 |
'<div class="yatra-error">Template not found: %s</div>', |
| 88 |
esc_html($full_path) |
| 89 |
); |
| 90 |
} |
| 91 |
return ''; |
| 92 |
} |
| 93 |
|
| 94 |
// Extract data to make variables available in template |
| 95 |
if (!empty($data)) { |
| 96 |
extract($data); |
| 97 |
} |
| 98 |
|
| 99 |
ob_start(); |
| 100 |
include $full_path; |
| 101 |
return ob_get_clean(); |
| 102 |
} |
| 103 |
|
| 104 |
/** |
| 105 |
* Get plugin template path |
| 106 |
*/ |
| 107 |
protected function getTemplatePath(string $template): string |
| 108 |
{ |
| 109 |
return YATRA_PLUGIN_PATH . 'templates/' . $template; |
| 110 |
} |
| 111 |
} |
| 112 |
|