BlockValidator.php
77 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace SureCart\BlockValidator; |
| 6 | |
| 7 | /** |
| 8 | * Class BlockValidator |
| 9 | * |
| 10 | * Validate and render blocks. |
| 11 | * |
| 12 | * @package SureCart\BlockValidator |
| 13 | */ |
| 14 | abstract class BlockValidator { |
| 15 | /** |
| 16 | * The name of the block to validate. |
| 17 | * |
| 18 | * @var string |
| 19 | */ |
| 20 | protected $block_name = ''; |
| 21 | |
| 22 | /** |
| 23 | * Validate block. |
| 24 | * |
| 25 | * The child class should implement this method. |
| 26 | * |
| 27 | * @param string $block_content The block content. |
| 28 | * @param array $block The block. |
| 29 | * |
| 30 | * @return bool |
| 31 | */ |
| 32 | abstract protected function isValid( string $block_content, array $block ): bool; |
| 33 | |
| 34 | /** |
| 35 | * Render block. |
| 36 | * |
| 37 | * The child class should implement this method. |
| 38 | * |
| 39 | * @param string $block_content The block content. |
| 40 | * @param array $block The block. |
| 41 | * |
| 42 | * @return string |
| 43 | */ |
| 44 | abstract protected function render( string $block_content, array $block ): string; |
| 45 | |
| 46 | /** |
| 47 | * Bootstrap the service. |
| 48 | * We only want to validate and render the block when the buy button renders. |
| 49 | * |
| 50 | * @return void |
| 51 | */ |
| 52 | public function bootstrap(): void { |
| 53 | if ( ! $this->block_name ) { |
| 54 | return; |
| 55 | } |
| 56 | add_action( 'render_block_' . $this->block_name, [ $this, 'validateAndRender' ], 10, 2 ); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Validate and render block. |
| 61 | * |
| 62 | * @param string $block_content The block content. |
| 63 | * @param array $block The block. |
| 64 | * |
| 65 | * @return string |
| 66 | */ |
| 67 | public function validateAndRender( string $block_content, array $block ): string { |
| 68 | // If the content is valid, return the original content. |
| 69 | if ( $this->isValid( $block_content, $block ) ) { |
| 70 | return $block_content; |
| 71 | } |
| 72 | |
| 73 | // Render the block - This should be implemented by the child class. |
| 74 | return $this->render( $block_content, $block ); |
| 75 | } |
| 76 | } |
| 77 |