Preventing search engines from indexing the DEV version of the site

How to prevent indexing of the site by search engines, if it is a version of the site for development (DEV copy of the site).

Quite often the site has two or three versions in the web: DEV and PROD (sometimes also STAGE). DEV version should always be locked from indexing, this can be done in different ways. Often I see it locked with password .htpasswd, but it is not always convenient. Much more convenient to use the following code to close the site from indexing:

/**
 * Close from search engines indexing for dev, stage environment.
 *
 * @version 1.0
 */
final class WP_Kama_Disable_Dev_Env_Indexing {

	public static function init(): void {
		add_action( 'init', [ __CLASS__, 'disable_indexing' ] );
	}

	public static function disable_indexing(): void {

		if( ! self::is_blocking_on() ){
			return;
		}

		self::block_search_agents();

		add_filter( 'wp_headers', [ __CLASS__, '_HTTP_header' ] );
		add_filter( 'robots_txt', [ __CLASS__, '_robots_txt' ] );
		add_filter( 'wp_robots', [ __CLASS__, '_robots_meta_tag' ], 999 );
	}

	/**
	 * Checks whether we should disable indexing.
	 */
	private static function is_blocking_on(): bool {

		if( in_array( wp_get_environment_type(), [ 'production', 'local' ], true ) ){
			return false;
		}

		if( current_user_can( 'administrator' ) ){
			return false;
		}

		return true;
	}

	/**
	 * 403 response for search agents.
	 */
	private static function block_search_agents(): void {
		$robots = 'libwww|Wget|LWP|damnBot|BBBike|spider|crawl|google|bing|yandex|msnbot';
		$user_agent = ( $_SERVER['HTTP_USER_AGENT'] ?? '' );

		if( preg_match( "/$robots/i", $user_agent ) ) {
			http_response_code( 403 );

			die( 'Indexing of this site is Forbidden for robots.' );
		}
	}

	public static function _HTTP_header( array $headers ): array {
		$headers['X-Robots-Tag'] = 'noindex, nofollow';

		return $headers;
	}

	public static function _robots_txt(): string {
		return "User-agent: *\nDisallow: /";
	}

	/**
	 * Callback for hook `wp_robots`.
	 * Adds `<meta name='robots' content='noindex, follow' />` HTML meta tag.
	 */
	public static function _robots_meta_tag( array $robots ): array {
		$robots['noindex'] = true;
		$robots['nofollow'] = true;
		unset( $robots['follow'] );

		return $robots;
	}

}

Now let's just call this function somewhere in the mu-plugin, simple plugin or in the fucntions.php file:

WP_Kama_Disable_Dev_Env_Indexing::init();

IMPORTANT! For this code, you need to specify the WP_ENVIRONMENT_TYPE constant in wp-config.php. The value of the constant should be different in different environments.