<?php
/**
 * Utility methods used across classes.
 *
 * @package Tasty_Roundups
 */

namespace Tasty_Roundups;

use Tasty\Framework\Utils\Vars;

/**
 * Utility methods used across classes.
 */
class Utils {

	/**
	 * Gets the URL to the base plugin directory with
	 * a trailing slash.
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	public static function plugin_url() {
		return plugin_dir_url( TASTY_ROUNDUPS_PLUGIN_FILE );
	}

	/**
	 * Gets the URL to the compiled assets directory.
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	public static function plugin_assets_url() {
		return self::plugin_url() . 'assets/dist/';
	}

	/**
	 * Gets the URL to the images directory.
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	public static function plugin_images_url() {
		return self::plugin_url() . 'assets/images/';
	}

	/**
	 * Get the plugin version.
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	public static function get_version() {
		return TASTY_ROUNDUPS_PLUGIN_VERSION;
	}

	/**
	 * Gets the Tasty Roundups blocks in the content.
	 *
	 * @param string $content Content to inspect.
	 * @return array
	 */
	public static function parse_roundup_blocks( $content ) {
		if ( false === stripos( $content, 'tasty-roundups/container' ) && false === stripos( $content, 'tasty-roundups/parent' ) ) {
			return array();
		}
		$blocks = array();
		foreach ( parse_blocks( $content ) as $block ) {
			if ( 'tasty-roundups/container' === $block['blockName'] || 'tasty-roundups/parent' === $block['blockName'] ) {
				$blocks[] = $block;
			}
		}
		return $blocks;
	}

	/**
	 * Returns true if the request is a REST API request.
	 *
	 * @since 2.0
	 *
	 * @todo: replace this function once core WP function is available: https://core.trac.wordpress.org/ticket/42061.
	 *
	 * @return bool
	 */
	public static function is_rest_api_request() {
		if ( defined( 'REST_REQUEST' ) ) {
			return REST_REQUEST;
		}

		$request_uri = Vars::server_param( 'REQUEST_URI' );
		if ( empty( $request_uri ) ) {
			return false;
		}

		$rest_prefix = trailingslashit( rest_get_url_prefix() );
		return str_contains( $request_uri, $rest_prefix );
	}
}
