<?php
/**
 * Plugin Name: Slow Post Embeds
 * Description: This tests an (uncommon) scenario where a post embed iframe finishes loading before the host page is able to load wp-embed.js and fire the DOMContentLoaded event. In this scenario (filed as <a href="https://core.trac.wordpress.org/ticket/44306">#44306</a>), the embed will fail to get the height set since the host page missed the height message from the post embed window.
 * Author: Weston Ruter
 */

namespace Slow_Post_Embeds;

const QUERY_VAR = 'slow_redirect_url';

add_filter(
	'script_loader_src',
	static function ( $url, $handle ) {
		if ( 'wp-embed' === $handle ) {
			$url = add_query_arg(
				[
					QUERY_VAR    => rawurlencode( $url ),
					'cache_bust' => wp_rand(),
				],
				home_url( '/' )
			);
		}
		return $url;
	},
	10,
	2
);

add_action(
	'template_redirect',
	static function () {
		if ( ! isset( $_GET[ QUERY_VAR ] ) ) {
			return;
		}

		$url = wp_validate_redirect( wp_unslash( $_GET[ QUERY_VAR ] ) );
		if ( ! $url ) {
			return;
		}

		sleep( 3 );
		wp_redirect( $url, 302 );
		exit;
	}
);
