| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* GutenbergBlock class for handling IvyForms Gutenberg block registration |
| 5 |
* |
| 6 |
* @copyright © TMS-Plugins. All rights reserved. |
| 7 |
* @licence See LICENCE.md for license details. |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace IvyForms\Services\Integrations\Gutenberg\Blocks; |
| 11 |
|
| 12 |
// phpcs:disable PSR1.Files.SideEffects |
| 13 |
if (!defined('ABSPATH')) { |
| 14 |
exit; // Exit if accessed directly |
| 15 |
} |
| 16 |
|
| 17 |
use IvyForms\Common\Exceptions\ValidationException; |
| 18 |
|
| 19 |
/** |
| 20 |
* Class GutenbergBlock |
| 21 |
* |
| 22 |
* @package IvyForms\Services\Blocks |
| 23 |
*/ |
| 24 |
class GutenbergBlock |
| 25 |
{ |
| 26 |
/** |
| 27 |
* Register the Gutenberg block |
| 28 |
* |
| 29 |
* @return void |
| 30 |
*/ |
| 31 |
public static function register(): void |
| 32 |
{ |
| 33 |
if (!function_exists('register_block_type')) { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
// Register custom block category |
| 38 |
// delegate category & assets registration to extracted helper |
| 39 |
GutenbergBlockAssets::registerBlockCategory(); |
| 40 |
GutenbergBlockAssets::registerBlockAssets(); |
| 41 |
|
| 42 |
// Check if block.json exists for WordPress 5.8+ compatibility |
| 43 |
$blockJsonPath = IVYFORMS_PATH . '/backend/src/Services/Integrations/Gutenberg/assets/block.json'; |
| 44 |
|
| 45 |
if (file_exists($blockJsonPath)) { |
| 46 |
register_block_type($blockJsonPath, [ |
| 47 |
'render_callback' => [self::class, 'render'], |
| 48 |
'editor_script' => 'ivyforms-gutenberg-block', |
| 49 |
'editor_style' => 'ivyforms-gutenberg-block-editor', |
| 50 |
]); |
| 51 |
return; |
| 52 |
} |
| 53 |
|
| 54 |
register_block_type('ivyforms/gutenberg-block', [ |
| 55 |
'render_callback' => [self::class, 'render'], |
| 56 |
'attributes' => BlockAttributes::getAttributes(), |
| 57 |
'api_version' => '2', |
| 58 |
]); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Render the Gutenberg block |
| 63 |
* |
| 64 |
* @param array<string, mixed> $attributes Block attributes |
| 65 |
* @return string Rendered block HTML |
| 66 |
* @throws ValidationException |
| 67 |
*/ |
| 68 |
public static function render(array $attributes): string |
| 69 |
{ |
| 70 |
$formId = GutenbergBlockRenderer::getFormIdFromAttributes($attributes); |
| 71 |
if ($formId === 0) { |
| 72 |
return GutenbergBlockRenderer::renderNoFormSelected(); |
| 73 |
} |
| 74 |
|
| 75 |
$form = GutenbergBlockRenderer::fetchPublishedForm($formId); |
| 76 |
if ($form === null) { |
| 77 |
return GutenbergBlockRenderer::renderFormNotFound(); |
| 78 |
} |
| 79 |
|
| 80 |
return GutenbergBlockRenderer::renderFormBlock($formId, $attributes); |
| 81 |
} |
| 82 |
} |
| 83 |
|