| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Elementor REST helpers for TableKit. |
| 5 |
* |
| 6 |
* @package TableKit |
| 7 |
*/ |
| 8 |
|
| 9 |
use TableBuilder\Shortcode\ShortcodeUtils; |
| 10 |
|
| 11 |
if (! defined('ABSPATH')) { |
| 12 |
exit; |
| 13 |
} |
| 14 |
|
| 15 |
class TableKit_Elementor_Rest |
| 16 |
{ |
| 17 |
public static function register(): void |
| 18 |
{ |
| 19 |
add_action('rest_api_init', array(__CLASS__, 'register_rest_routes')); |
| 20 |
} |
| 21 |
|
| 22 |
public static function register_rest_routes(): void |
| 23 |
{ |
| 24 |
register_rest_route( |
| 25 |
'tablekit/v1', |
| 26 |
'/table-blocks', |
| 27 |
array( |
| 28 |
'methods' => \WP_REST_Server::READABLE, |
| 29 |
'callback' => array(__CLASS__, 'rest_table_blocks'), |
| 30 |
'permission_callback' => static function (): bool { |
| 31 |
return current_user_can('edit_posts'); |
| 32 |
}, |
| 33 |
'args' => array( |
| 34 |
'table_id' => array( |
| 35 |
'required' => true, |
| 36 |
'validate_callback' => static function ($value): bool { |
| 37 |
return is_numeric($value) && (int) $value > 0; |
| 38 |
}, |
| 39 |
'sanitize_callback' => 'absint', |
| 40 |
), |
| 41 |
), |
| 42 |
) |
| 43 |
); |
| 44 |
} |
| 45 |
|
| 46 |
public static function rest_table_blocks(\WP_REST_Request $request) |
| 47 |
{ |
| 48 |
$table_id = (int) $request->get_param('table_id'); |
| 49 |
$post = get_post($table_id); |
| 50 |
$content = null; |
| 51 |
|
| 52 |
if ($post) { |
| 53 |
if ('publish' !== $post->post_status && !current_user_can('read_post', $table_id)) { |
| 54 |
return new \WP_Error( |
| 55 |
'tablekit_forbidden', |
| 56 |
__('You are not allowed to view this table.', 'tablekit'), |
| 57 |
array('status' => 403) |
| 58 |
); |
| 59 |
} |
| 60 |
|
| 61 |
$content = $post->post_content; |
| 62 |
} elseif (class_exists('\\TableBuilder\\Config\\CPT\\TableCPT') && method_exists('\\TableBuilder\\Config\\CPT\\TableCPT', 'get_inline_table_content')) { |
| 63 |
$inline = \TableBuilder\Config\CPT\TableCPT::instance() |
| 64 |
->get_inline_table_content($table_id); |
| 65 |
$content = $inline ?? null; |
| 66 |
} |
| 67 |
|
| 68 |
if (null === $content) { |
| 69 |
return new \WP_Error( |
| 70 |
'tablekit_not_found', |
| 71 |
__('Table not found.', 'tablekit'), |
| 72 |
array('status' => 404) |
| 73 |
); |
| 74 |
} |
| 75 |
|
| 76 |
$blocks = parse_blocks($content); |
| 77 |
$table_blocks = self::filter_table_blocks($blocks); |
| 78 |
$result = array(); |
| 79 |
|
| 80 |
foreach ($table_blocks as $index => $block) { |
| 81 |
$block_name = $block['blockName'] ?? ''; |
| 82 |
$result[] = array( |
| 83 |
'index' => $index, |
| 84 |
'label' => ShortcodeUtils::get_block_label($block_name), |
| 85 |
'block_name' => $block_name, |
| 86 |
); |
| 87 |
} |
| 88 |
|
| 89 |
return rest_ensure_response($result); |
| 90 |
} |
| 91 |
|
| 92 |
private static function filter_table_blocks(array $blocks): array |
| 93 |
{ |
| 94 |
return ShortcodeUtils::filter_table_blocks($blocks); |
| 95 |
} |
| 96 |
} |
| 97 |
|