File: /var/www/html/insiders/wp-load/wp-content/plugins/gutenmate/block-supports/class-block-style.php
<?php
class GTM_Block_Style {
private static $instance;
public $block_styles = [];
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct() {
}
public function init() {
add_filter( 'render_block', [$this, 'render_block'], 10, 2 );
// Ideally styles should be loaded in the head, but blocks may be parsed
// after that, so loading in the footer for now.
// See https://core.trac.wordpress.org/ticket/53494.
add_filter( 'wp_head', [$this, 'render_css'], 11 );
}
public function render_block( $block_content, $block ) {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
// Some blocks has no block stype (such as "core/comments-query-loop"), can skip it.
// Some blocks has no attrs (core/page-list)
if ( ! empty( $block_type ) && isset( $block['attrs'] ) ) {
$attrs = gtm_apply_block_attribute_defaults( $block['attrs'], $block_type->attributes );
$block_style = gtm_do_compile_block_style( $block_type, $attrs );
if ( $block_style !== false ) {
// Add basic class for using in higher specificity
// Only in case of the block has some style to be rendered
if ( ! empty( $block_style['classes'] ) ) {
array_unshift( $block_style['classes'], 'gtm-style' );
}
// Add style id class if there are some style to be rendered
$style_class = wp_unique_id( 'gtm-style-' );
if ( ! empty( $block_style['style'] ) ) {
array_unshift( $block_style['classes'], $style_class );
}
if ( ! empty( $block_style['style'] ) ) {
// Replace block id
$styles = [];
foreach ( $block_style['style'] as $selector => $props ) {
$selector = str_replace( '{{BLOCK}}', '.' . $style_class . '{{BLOCK}}:not(#\9)', $selector );
$styles[$selector] = $props;
}
$this->block_styles[] = $styles;
}
// This assumes the hook only applies to blocks with a single wrapper.
// I think this is a reasonable limitation for that particular hook.
if ( ! empty( $block_style['classes'] ) ) {
$block_content = preg_replace(
'/' . preg_quote( 'class="', '/' ) . '([^"]*)"/',
'class="$1 ' . implode( ' ', $block_style['classes'] ) . '"',
$block_content,
1
);
}
}
}
return $block_content;
}
public function render_css() {
if ( ! empty( $this->block_styles ) ) {
// Merge all style to single media query
$all_styles = [];
foreach ( $this->block_styles as $block_style ) {
$all_styles = array_merge_recursive( $all_styles, $block_style );
}
echo '<style id="gtm-block-styles">';
$css_template = gtm_css_compileCssTemplate( $all_styles );
echo wp_strip_all_tags( gtm_css_generateCss( $css_template, ['suppress-import' => false] ) );
echo '</style>';
}
}
}