| 1 |
<?php |
| 2 |
|
| 3 |
namespace SureCart\BlockLibrary; |
| 4 |
|
| 5 |
/** |
| 6 |
* The product review form service. |
| 7 |
*/ |
| 8 |
class ProductReviewFormService { |
| 9 |
/** |
| 10 |
* Flag to track if template has been rendered. |
| 11 |
* |
| 12 |
* @var bool |
| 13 |
*/ |
| 14 |
private static $rendered = false; |
| 15 |
|
| 16 |
/** |
| 17 |
* Include review form template. |
| 18 |
* This needs to run before <head> so that blocks can add scripts and styles in wp_head(). |
| 19 |
* |
| 20 |
* @return void |
| 21 |
*/ |
| 22 |
public function render() { |
| 23 |
// Only render the template once per page load. |
| 24 |
if ( self::$rendered ) { |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
// do this before the footer so we can print late styles. |
| 29 |
$review_form_template = $this->getTemplate(); |
| 30 |
|
| 31 |
// add review form template to footer. |
| 32 |
add_action( |
| 33 |
'wp_footer', |
| 34 |
function () use ( $review_form_template ) { |
| 35 |
echo $review_form_template; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped |
| 36 |
} |
| 37 |
); |
| 38 |
|
| 39 |
// Mark template as rendered. |
| 40 |
self::$rendered = true; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Get the review form template. |
| 45 |
* |
| 46 |
* @return string |
| 47 |
*/ |
| 48 |
public function getTemplate() { |
| 49 |
// get review form block. |
| 50 |
$template = get_block_template( 'surecart/surecart//product-review-form', 'wp_template_part' ); |
| 51 |
if ( ! $template || empty( $template->content ) ) { |
| 52 |
return ''; |
| 53 |
} |
| 54 |
|
| 55 |
// WordPress 6.9+ dequeues styles for blocks when their parent returns empty content. |
| 56 |
// Since the review form is rendered in wp_footer (outside normal block flow), |
| 57 |
// we need to force WordPress to keep the block assets enqueued. |
| 58 |
// @see https://core.trac.wordpress.org/ticket/63676. |
| 59 |
add_filter( 'enqueue_empty_block_content_assets', '__return_true' ); |
| 60 |
|
| 61 |
ob_start(); |
| 62 |
|
| 63 |
// Render the product review form modal. |
| 64 |
echo do_blocks( $template->content ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped |
| 65 |
|
| 66 |
return trim( preg_replace( '/\s+/', ' ', ob_get_clean() ) ); |
| 67 |
} |
| 68 |
} |
| 69 |
|