Automattic\WooCommerce\EmailEditor\Engine\Renderer

Renderer::preserve_personalization_tagsprivateWC 1.0

Preserves personalization tags by replacing them with unique placeholders (not inside comments).

Method of the class: Renderer{}

No Hooks.

Returns

String.

Usage

// private - for code of main (parent) class only
$result = $this->preserve_personalization_tags( $template ): string;
$template(string) (required)
HTML template.

Renderer::preserve_personalization_tags() code WC 10.4.3

private function preserve_personalization_tags( string $template ): string {
	$all_registered_tags                    = $this->personalization_tags_registry->get_all();
	$this->personalization_tag_placeholders = array();
	$counter                                = 0;

	$base_tokens    = array(); // All the tokens used in the email, e.g. [woocommerce/customer-username].
	$token_prefixes = array(); // All the used prefixes, e.g. woocommerce, mailpoet, etc.
	foreach ( $all_registered_tags as $tag ) {
		$token                 = $tag->get_token(); // E.g. [woocommerce/customer-username].
		$base_tokens[ $token ] = true;
		// Remove brackets for regex matching, escape for regex.
		$token_prefixes[] = preg_quote( substr( $token, 1, -1 ), '/' );
	}

	if ( empty( $token_prefixes ) ) {
		return $template;
	}

	// Match all of the code comments that look like a personalization tags.
	$pattern = '/<!--\[(' . implode( '|', $token_prefixes ) . ')(?:\s+[^\]]*)?\]-->/';

	$template = preg_replace_callback(
		$pattern,
		function ( $matches ) use ( &$counter, $base_tokens ) {
			// $matches[1] is the token without brackets, add brackets for lookup.
			$base_token = '[' . $matches[1] . ']';
			if ( isset( $base_tokens[ $base_token ] ) ) {
				$placeholder = 'PERSONALIZATION_TAG_PLACEHOLDER_' . $counter;
				$this->personalization_tag_placeholders[ $placeholder ] = $matches[0];
				++$counter;
				return $placeholder;
			}
			return $matches[0];
		},
		$template
	);

	return $template ?? '';
}