| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Hooks\Handlers\ShortCodes; |
| 4 |
|
| 5 |
use FluentCart\Api\Contracts\CanEnqueue; |
| 6 |
use FluentCart\App\App; |
| 7 |
use FluentCart\App\Services\Renderer\RenderContext; |
| 8 |
use FluentCart\Framework\Support\Arr; |
| 9 |
use FluentCart\Framework\Support\Str; |
| 10 |
|
| 11 |
abstract class ShortCode |
| 12 |
{ |
| 13 |
use CanEnqueue; |
| 14 |
|
| 15 |
protected static string $shortCodeName; |
| 16 |
protected ?array $shortCodeAttributes = null; |
| 17 |
protected ?string $slugPrefix = null; |
| 18 |
|
| 19 |
public function __construct(array $shortcodeAttributes = []) |
| 20 |
{ |
| 21 |
$this->shortCodeAttributes = $this->parseAttribute($shortcodeAttributes); |
| 22 |
$this->slugPrefix = App::config()->get('app.slug'); |
| 23 |
} |
| 24 |
|
| 25 |
abstract public function render(?array $viewData = null); |
| 26 |
|
| 27 |
|
| 28 |
public function renderShortcode($block = null) |
| 29 |
{ |
| 30 |
$this->enqueueAssets(); |
| 31 |
ob_start(null); |
| 32 |
$this->render( |
| 33 |
$this->viewData() |
| 34 |
); |
| 35 |
return ob_get_clean(); |
| 36 |
} |
| 37 |
|
| 38 |
public function parseAttribute(array $shortcodeAttributes): array |
| 39 |
{ |
| 40 |
return $shortcodeAttributes; |
| 41 |
} |
| 42 |
|
| 43 |
public function viewData(): ?array |
| 44 |
{ |
| 45 |
return $this->shortCodeAttributes; |
| 46 |
} |
| 47 |
|
| 48 |
public static function getShortCodeName(): string |
| 49 |
{ |
| 50 |
return static::$shortCodeName; |
| 51 |
} |
| 52 |
|
| 53 |
public static function register() |
| 54 |
{ |
| 55 |
add_shortcode(static::getShortCodeName(), function ($shortcodeAttributes, $content, $block) { |
| 56 |
// WordPress exposes no "shortcode currently rendering" signal, so |
| 57 |
// this is the one place that has to say so. Every ShortCode |
| 58 |
// subclass registers through here, so it is the only place. |
| 59 |
return RenderContext::declaring( |
| 60 |
RenderContext::SOURCE_SHORTCODE, |
| 61 |
static::getShortCodeName(), |
| 62 |
function () use ($shortcodeAttributes, $block) { |
| 63 |
return static::make($shortcodeAttributes)->renderShortcode($block); |
| 64 |
} |
| 65 |
); |
| 66 |
}); |
| 67 |
} |
| 68 |
|
| 69 |
protected function generateEnqueueSlug(): string |
| 70 |
{ |
| 71 |
return Str::of( |
| 72 |
$this->slugPrefix . '_' . static::getShortCodeName() |
| 73 |
)->snake('')->replace('-', '_')->toString(); |
| 74 |
} |
| 75 |
|
| 76 |
public static function make($shortcodeAttributes = null): ShortCode |
| 77 |
{ |
| 78 |
return new static( |
| 79 |
Arr::wrap($shortcodeAttributes) |
| 80 |
); |
| 81 |
} |
| 82 |
} |
| 83 |
|