| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace RenzoJohnson\Blocks\Variables; |
| 6 |
|
| 7 |
\defined( 'ABSPATH' ) || exit; |
| 8 |
|
| 9 |
final class VariablesEverywhere { |
| 10 |
|
| 11 |
public const OPTION_NAME = 'blocks_variables_everywhere'; |
| 12 |
|
| 13 |
private bool $buffer_started = false; |
| 14 |
|
| 15 |
public function __construct( |
| 16 |
private readonly VariableResolver $resolver, |
| 17 |
private readonly \Blocks_Settings_Repository $settings, |
| 18 |
) { |
| 19 |
} |
| 20 |
|
| 21 |
public function register_hooks(): void { |
| 22 |
\add_filter( 'the_content', $this->filter_content( ... ), 12 ); |
| 23 |
\add_filter( 'widget_text', $this->filter_content( ... ), 12 ); |
| 24 |
\add_filter( 'widget_block_content', $this->filter_content( ... ), 12 ); |
| 25 |
\add_filter( 'bricks/frontend/render_data', $this->filter_content( ... ), 12 ); |
| 26 |
\add_filter( 'breakdance_singular_content', $this->filter_content( ... ), 12 ); |
| 27 |
\add_action( 'template_redirect', $this->start_output_pass( ... ), 2 ); |
| 28 |
} |
| 29 |
|
| 30 |
public function enabled(): bool { |
| 31 |
return $this->settings->get_bool( self::OPTION_NAME ); |
| 32 |
} |
| 33 |
|
| 34 |
public function filter_content( mixed $content ): mixed { |
| 35 |
if ( ! \is_string( $content ) || '' === $content || ! $this->enabled() ) { |
| 36 |
return $content; |
| 37 |
} |
| 38 |
|
| 39 |
return $this->resolver->replace_html( $content ); |
| 40 |
} |
| 41 |
|
| 42 |
public function start_output_pass(): void { |
| 43 |
if ( ! $this->should_start_output_pass() ) { |
| 44 |
return; |
| 45 |
} |
| 46 |
|
| 47 |
$this->buffer_started = true; |
| 48 |
\ob_start( $this->filter_output( ... ) ); |
| 49 |
} |
| 50 |
|
| 51 |
public function filter_output( string $html ): string { |
| 52 |
foreach ( \headers_list() as $header ) { |
| 53 |
if ( 0 !== \stripos( $header, 'Content-Type:' ) ) { |
| 54 |
continue; |
| 55 |
} |
| 56 |
|
| 57 |
if ( false === \stripos( $header, 'text/html' ) && false === \stripos( $header, 'application/xhtml+xml' ) ) { |
| 58 |
return $html; |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
return $this->resolver->replace_html( $html ); |
| 63 |
} |
| 64 |
|
| 65 |
private function should_start_output_pass(): bool { |
| 66 |
if ( $this->buffer_started || ! $this->enabled() ) { |
| 67 |
return false; |
| 68 |
} |
| 69 |
|
| 70 |
if ( |
| 71 |
\is_admin() |
| 72 |
|| \is_feed() |
| 73 |
|| \is_robots() |
| 74 |
|| \is_trackback() |
| 75 |
|| \wp_doing_ajax() |
| 76 |
|| ( \defined( 'REST_REQUEST' ) && REST_REQUEST ) |
| 77 |
|| ( \defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) |
| 78 |
) { |
| 79 |
return false; |
| 80 |
} |
| 81 |
|
| 82 |
$status = \http_response_code(); |
| 83 |
|
| 84 |
if ( \is_int( $status ) && ( 204 === $status || 304 === $status ) ) { |
| 85 |
return false; |
| 86 |
} |
| 87 |
|
| 88 |
return (bool) \apply_filters( 'blocks_variables_output_buffer_enabled', true ); |
| 89 |
} |
| 90 |
} |
| 91 |
|