<?php
/**
* Abstract Facet Block class.
*
* @since 4.7.0
* @package elasticpress
*/
namespace ElasticPress\Feature\Facets;
/**
* Abstract Facet Block class.
*/
abstract class Block {
/**
* Whether the current request is a facet block preview requested by the block editor.
*
* @since 5.3.7
* @var bool
*/
protected static $is_editor_preview_request = false;
/**
* Setup hooks and filters for facet block.
*/
abstract public function setup();
/**
* Register facet block.
*/
abstract public function register_block();
/**
* Render the block.
*
* @param array $attributes Block attributes.
* @return string
*/
abstract public function render_block( $attributes );
/**
* Check if facets should be enabled in the editor.
*
* @since 5.3.0
* @return boolean
*/
public function is_facet_enabled_in_editor(): bool {
global $pagenow;
$in_editor = in_array( $pagenow, [ 'post-new.php', 'post.php' ], true );
/**
* Filter if facet should be enabled in the editor. Default: false
*
* @hook ep_facet_enabled_in_editor
* @since 5.1.0
* @param {bool} $enabled
* @return {bool} If enabled or not
*/
return ! ( $in_editor && ! apply_filters( 'ep_facet_enabled_in_editor', false ) );
}
/**
* Add the hooks that detect facet block previews requested by the block editor.
*
* @since 5.3.7
* @return void
*/
public static function setup_editor_preview_detection() {
add_filter( 'rest_request_before_callbacks', [ __CLASS__, 'detect_editor_preview_request' ], 10, 3 );
add_filter( 'rest_request_after_callbacks', [ __CLASS__, 'reset_editor_preview_request' ] );
}
/**
* Flag requests to the block renderer endpoint for ElasticPress blocks.
*
* The endpoint only accepts the `edit` context and checks if the user can edit posts.
*
* @since 5.3.7
* @param mixed $response Response to replace the requested version with.
* @param array $handler Route handler used for the request.
* @param \WP_REST_Request $request Request used to generate the response.
* @return mixed
*/
public static function detect_editor_preview_request( $response, $handler, $request ) {
self::$is_editor_preview_request = 0 === strpos( $request->get_route(), '/wp/v2/block-renderer/elasticpress/' )
&& 'edit' === $request->get_param( 'context' );
return $response;
}
/**
* Remove the preview flag after the request callbacks run.
*
* @since 5.3.7
* @param mixed $response Response.
* @return mixed
*/
public static function reset_editor_preview_request( $response ) {
self::$is_editor_preview_request = false;
return $response;
}
/**
* Whether the block should be rendered as a preview.
*
* The `isPreview` attribute can also come from saved content, so it is only honored
* in the block editor preview.
*
* @since 5.3.7
* @param array $attributes Block attributes.
* @return bool
*/
public function is_preview( array $attributes ): bool {
return ! empty( $attributes['isPreview'] )
&& self::$is_editor_preview_request
&& current_user_can( 'edit_posts' );
}
}