VariantChoice.php
83 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace SureCart\BlockValidator; |
| 6 | |
| 7 | use \SureCartBlocks\Blocks\Product\VariantChoices\Block as VariantChoicesBlock; |
| 8 | |
| 9 | /** |
| 10 | * VariantChoice Block validator. |
| 11 | */ |
| 12 | class VariantChoice extends BlockValidator { |
| 13 | /** |
| 14 | * Has this run before? |
| 15 | * |
| 16 | * @var boolean |
| 17 | */ |
| 18 | protected static $has_run = false; |
| 19 | |
| 20 | /** |
| 21 | * The name of the block to validate. |
| 22 | * |
| 23 | * @var string |
| 24 | */ |
| 25 | protected $block_name = 'surecart/product-buy-button'; |
| 26 | |
| 27 | /** |
| 28 | * Validate block. |
| 29 | * |
| 30 | * @param string $block_content The block content. |
| 31 | * @param array $block The block. |
| 32 | * |
| 33 | * @return bool True if the block is valid, false otherwise. |
| 34 | */ |
| 35 | protected function isValid( string $block_content, array $block ): bool { |
| 36 | $product = get_query_var( 'surecart_current_product' ); |
| 37 | |
| 38 | // we have already run this. |
| 39 | if ( self::$has_run ) { |
| 40 | return true; |
| 41 | } |
| 42 | |
| 43 | // If not in product page return. |
| 44 | if ( empty( $product ) || ! $product instanceof \SureCart\Models\Product ) { |
| 45 | return true; |
| 46 | } |
| 47 | |
| 48 | // If no variant, return. |
| 49 | if ( ! count( $product->variants->data ?? [] ) ) { |
| 50 | return true; |
| 51 | } |
| 52 | |
| 53 | // If has block already exist, return. |
| 54 | if ( has_block( 'surecart/product-variant-choices' ) ) { |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | // We only want to run once. |
| 59 | self::$has_run = true; |
| 60 | |
| 61 | // We don't have a variant choice block. |
| 62 | return false; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Render block. |
| 67 | * |
| 68 | * @param string $block_content The block content. |
| 69 | * @param array $block The block. |
| 70 | * |
| 71 | * @return string |
| 72 | */ |
| 73 | protected function render( string $block_content, array $block ): string { |
| 74 | $appended_block = render_block( |
| 75 | [ |
| 76 | 'blockName' => 'surecart/product-variant-choices', |
| 77 | 'attrs' => [], |
| 78 | ] |
| 79 | ); |
| 80 | return $appended_block . $block_content; |
| 81 | } |
| 82 | } |
| 83 |