<?php

if ( ! function_exists( 'wp_php_filters_for_js_l10n' ) ) :
	function wp_php_filters_for_js_l10n( $json_translations, $file, $handle, $domain ) {
		$translations = json_decode( $json_translations, true );

		if ( is_array( $translations ) && isset( $translations['locale_data'], $translations['locale_data']['messages'] ) && is_array( $translations['locale_data']['messages'] ) ) {
			foreach ( $translations['locale_data']['messages'] as $original_string => &$translated_strings ) {
				if ( ! $original_string || ! is_array( $translated_strings ) ) {
					continue;
				}

				$context = '';

				if ( strpos( $original_string, chr( 4 ) ) ) {
					$with_context    = explode( chr( 4 ), $original_string );
					$context         = $with_context[0];
					$original_string = $with_context[1];
				}

				foreach ( $translated_strings as &$translated_string ) {
					if ( $context ) {
						$translated_string = apply_filters( 'gettext_with_context', $translated_string, $original_string, $context, $domain );
					} else {
						$translated_string = apply_filters( 'gettext', $translated_string, $original_string, $domain );
					}
				}
			}
		}

		return wp_json_encode( $translations );
	}
	add_filter( 'load_script_translation', 'wp_php_filters_for_js_l10n', 10, 4 );
endif;
