ProductPageWrapperService.php
89 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Migration; |
| 4 | |
| 5 | /** |
| 6 | * Product page wrapper service. |
| 7 | */ |
| 8 | class ProductPageWrapperService { |
| 9 | |
| 10 | /** |
| 11 | * Content of the page |
| 12 | * |
| 13 | * @var string |
| 14 | */ |
| 15 | protected $content = ''; |
| 16 | |
| 17 | /** |
| 18 | * Constructor |
| 19 | * |
| 20 | * @param string $content Content of the page. |
| 21 | * |
| 22 | * @return void |
| 23 | */ |
| 24 | public function __construct( $content ) { |
| 25 | $this->content = $content; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Has product page wrapper |
| 30 | * |
| 31 | * @return boolean |
| 32 | */ |
| 33 | public function hasProductPageWrapper() { |
| 34 | return preg_match( '/data-sc-block-id=(?:"product-page"|\'product-page\'|\\"product-page\\"|\\\'product-page\\\')/', $this->content ); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Has custom amount block |
| 39 | * |
| 40 | * @return boolean |
| 41 | */ |
| 42 | public function hasCustomAmountBlock() { |
| 43 | return preg_match( '/data-sc-block-id=(?:"custom-amount"|\'custom-amount\'|\\"custom-amount\\"|\\\'custom-amount\\\')/', $this->content ); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Add product page wrapper |
| 48 | * |
| 49 | * @return string |
| 50 | */ |
| 51 | public function addProductPageWrapper() { |
| 52 | return '<!-- wp:surecart/product-page -->' . $this->content . '<!-- /wp:surecart/product-page -->'; |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Add custom amount block |
| 57 | * |
| 58 | * @return string |
| 59 | */ |
| 60 | public function addCustomAmountBlock() { |
| 61 | return str_replace( |
| 62 | '<div class="wp-block-button has-custom-width wp-block-button__width-100 wp-block-surecart-product-buy-button"', |
| 63 | '<!-- wp:surecart/product-selected-price-ad-hoc-amount /-->' . PHP_EOL . '<div class="wp-block-button has-custom-width wp-block-button__width-100 wp-block-surecart-product-buy-button"', |
| 64 | $this->content |
| 65 | ); |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Handle product page wrapper |
| 70 | * |
| 71 | * @return string |
| 72 | */ |
| 73 | public function wrap(): string { |
| 74 | if ( ! is_singular( 'sc_product' ) ) { |
| 75 | return $this->content; |
| 76 | } |
| 77 | |
| 78 | if ( ! $this->hasProductPageWrapper() ) { |
| 79 | $this->content = $this->addProductPageWrapper(); |
| 80 | } |
| 81 | |
| 82 | if ( ! $this->hasCustomAmountBlock() ) { |
| 83 | $this->content = $this->addCustomAmountBlock(); |
| 84 | } |
| 85 | |
| 86 | return do_blocks( $this->content ); |
| 87 | } |
| 88 | } |
| 89 |