Block.php
| 1 | <?php |
| 2 | /** |
| 3 | * ParsiDate Base Block |
| 4 | * |
| 5 | * Shared registration and rendering logic for Gutenberg blocks |
| 6 | */ |
| 7 | |
| 8 | namespace WPParsidate\Block; |
| 9 | |
| 10 | defined( 'ABSPATH' ) || exit; |
| 11 | |
| 12 | use WPParsidate\Helper\Assets; |
| 13 | use WPParsidate\Helper\Posts; |
| 14 | use WPParsidate\Settings\Settings; |
| 15 | |
| 16 | abstract class Block { |
| 17 | protected string $editorScript = ''; |
| 18 | |
| 19 | protected string $blockJsonPath = ''; |
| 20 | |
| 21 | protected string $scriptBaseName = ''; |
| 22 | |
| 23 | protected string $dataVar = ''; |
| 24 | |
| 25 | protected array $deps = array( |
| 26 | 'wp-blocks', |
| 27 | 'wp-element', |
| 28 | 'wp-block-editor', |
| 29 | 'wp-components', |
| 30 | 'wp-i18n', |
| 31 | 'wp-server-side-render' |
| 32 | ); |
| 33 | |
| 34 | public function __construct() { |
| 35 | add_action( 'init', array( $this, 'registerBlock' ) ); |
| 36 | } |
| 37 | |
| 38 | public function registerBlock(): void { |
| 39 | if ( ! function_exists( 'register_block_type' ) ) { |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | $debugName = WP_PARSI_DEBUG_MODE ? '' : '.min'; |
| 44 | |
| 45 | wp_register_script( |
| 46 | $this->editorScript, |
| 47 | Assets::url( 'js-admin/' . $this->scriptBaseName . $debugName . '.js' ), |
| 48 | $this->deps, |
| 49 | Assets::getVersion(), |
| 50 | array( 'in_footer' => true ) |
| 51 | ); |
| 52 | |
| 53 | register_block_type( Assets::path( $this->blockJsonPath ), array( |
| 54 | 'render_callback' => array( $this, 'renderBlock' ), |
| 55 | ) ); |
| 56 | |
| 57 | add_action( 'enqueue_block_editor_assets', array( $this, 'editorAssets' ) ); |
| 58 | } |
| 59 | |
| 60 | public function editorAssets(): void { |
| 61 | wp_add_inline_script( |
| 62 | $this->editorScript, |
| 63 | 'window.' . $this->dataVar . ' = ' . wp_json_encode( array( |
| 64 | 'postTypes' => $this->postTypeOptions(), |
| 65 | 'convPermalinks' => (bool) Settings::get( 'conv_permalinks', false ), |
| 66 | ) ) . ';', |
| 67 | 'before' |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | public function renderBlock( $attributes ): string { |
| 72 | if ( ! Settings::get( 'conv_permalinks', false ) ) { |
| 73 | return ''; |
| 74 | } |
| 75 | |
| 76 | return $this->renderContent( $attributes ); |
| 77 | } |
| 78 | |
| 79 | abstract protected function renderContent( $attributes ): string; |
| 80 | |
| 81 | protected function postTypeOptions(): array { |
| 82 | $options = array(); |
| 83 | |
| 84 | foreach ( Posts::getTypes() as $name => $label ) { |
| 85 | $options[] = array( 'label' => $label, 'value' => $name ); |
| 86 | } |
| 87 | |
| 88 | return $options; |
| 89 | } |
| 90 | } |
| 91 |