*/ private array $memo = []; /** * Per-context token cache keyed by (hash|token). * * Caches individual token values per Context hash to eliminate redundant DB * queries (e.g. get_the_category, get_the_author_meta) across multiple fields. * * @var array */ private array $tokenCache = []; /** * Replace tokens in a template, memoized by context hash + field. * * Unknown tokens are stripped (replaced with ''). Custom tokens may be * injected via the `rankkernel/tokens` filter where `$map` is * token-name (no %%) => value. * * @param Context $ctx Request context. * @param string $template Template containing %%tokens%%. * @param string $field Field key for memoization (e.g. 'title', 'description'). * @return string Resolved template. */ public function replace( Context $ctx, string $template, string $field ): string { $key = $ctx->hash() . '|' . $field; if ( array_key_exists( $key, $this->memo ) ) { return $this->memo[ $key ]; } $result = $this->doReplace( $ctx, $template ); $this->memo[ $key ] = $result; return $result; } /** * Actual replacement logic (not memoized). * * @param Context $ctx Request context. * @param string $template Template. * @return string Resolved string. */ private function doReplace( Context $ctx, string $template ): string { // Performance optimization: fast-path check for token delimiters ('%%') before running regex scans. $hasTokenDelimiter = str_contains( $template, '%%' ); // A direct callback on this hook or a callback on the `all` hook, which // apply_filters() runs for every filter, can observe the map, so every // supported token is resolved for it. Otherwise only the tokens present // in the template are resolved. $hasFilter = function_exists( 'has_filter' ) && ( has_filter( 'rankkernel/tokens' ) || has_filter( 'all' ) ); // Fast-path: if the template contains no token delimiters and no token filter is hooked, // avoid preg_match_all, token resolution, filter calls, and preg_replace_callback. if ( ! $hasTokenDelimiter && ! $hasFilter ) { return $template; } $templateTokens = []; if ( $hasTokenDelimiter ) { // Parse the template for token placeholders and selectively resolve only tokens present in it, // avoiding expensive unneeded operations (e.g., category DB queries, author meta, excerpt formatting). preg_match_all( self::TOKEN_PATTERN, $template, $matches ); $templateTokens = ! empty( $matches[1] ) ? array_unique( $matches[1] ) : []; } $map = []; if ( $hasFilter ) { foreach ( self::SUPPORTED_TOKENS as $token ) { $map[ $token ] = $this->resolveToken( $token, $ctx ); } } else { foreach ( $templateTokens as $token ) { if ( in_array( $token, self::SUPPORTED_TOKENS, true ) ) { $map[ $token ] = $this->resolveToken( $token, $ctx ); } } } /** * Filter the token map. * * @param array $map Token map (name without %%) => value. * @param Context $context Current request context. */ $map = apply_filters( 'rankkernel/tokens', $map, $ctx ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- public hook name, part of the plugin API, must stay stable. if ( ! $hasTokenDelimiter ) { return $template; } if ( ! is_array( $map ) ) { $map = []; } $resolved = preg_replace_callback( self::TOKEN_PATTERN, static function ( array $matches ) use ( $map ): string { $token = $matches[1]; return isset( $map[ $token ] ) ? (string) $map[ $token ] : ''; }, $template ); return is_string( $resolved ) ? $resolved : $template; } /** * Resolve a single token with context-level memoization. * * Performance optimization: caches individual token values per Context hash to prevent * re-evaluating taxonomy queries or author metadata when replacing tokens across multiple fields. * * @param string $token Token name (without %%). * @param Context $ctx Request context. * @return string Resolved token value. */ private function resolveToken( string $token, Context $ctx ): string { $tokenKey = $ctx->hash() . '|' . $token; if ( array_key_exists( $tokenKey, $this->tokenCache ) ) { return $this->tokenCache[ $tokenKey ]; } $value = match ( $token ) { 'title' => $ctx->title(), 'sitename' => $ctx->siteName(), 'sep' => $ctx->separator(), 'excerpt' => $ctx->excerpt(), 'date' => $this->resolveDate( $ctx ), 'author' => $this->resolveAuthor( $ctx ), 'category' => $this->resolveCategory( $ctx ), 'page' => $this->resolvePage( $ctx ), 'currentdate' => $this->resolveCurrentDate(), default => '', }; $this->tokenCache[ $tokenKey ] = $value; return $value; } /** * Resolve %%date%% token. * * @param Context $ctx Context. * @return string The result. */ private function resolveDate( Context $ctx ): string { // Archives have no queried post, so the id is zero. get_the_date() // passes that through get_post(), and core resolves a missing post // to the current global, which on an archive is whichever post the // loop is sitting on. That put an unrelated post date into the page // title. Guarded exactly like resolveCategory(). $id = $ctx->queriedId(); if ( $id > 0 && function_exists( 'get_the_date' ) ) { $date = get_the_date( '', $id ); if ( is_string( $date ) ) { return $date; } } return ''; } /** * Resolve %%author%% token. * * @param Context $ctx Context. * @return string The result. */ private function resolveAuthor( Context $ctx ): string { // Author archives resolve the display name of the queried author, // never the author of an unrelated post sharing the queried id. if ( $ctx->isAuthorArchive() ) { $archiveName = $ctx->authorDisplayName(); if ( '' !== $archiveName ) { return $archiveName; } } // A term archive has no author. The queried id is the term id, and // the post lookup below reads post_author from whatever post happens // to share that number, so a term archive published an unrelated // author's name. Term and post ids both start at 1, so it fired on // the default configuration sitewide. Mirrors resolveCategory(), // which resolves the term name first and never falls through. if ( 'term' === $ctx->queriedType() ) { return ''; } // Prefer author of queried post. $id = $ctx->queriedId(); if ( $id > 0 && function_exists( 'get_post_field' ) ) { $authorId = get_post_field( 'post_author', $id ); if ( is_numeric( $authorId ) && (int) $authorId > 0 && function_exists( 'get_the_author_meta' ) ) { $name = get_the_author_meta( 'display_name', (int) $authorId ); if ( is_string( $name ) && '' !== $name ) { return $name; } } } // get_the_author() reads the global $authordata, which on an archive // is whichever post the loop last set, so it has the same exposure // the date token had. Only reached once the queried post has been // ruled out above, so the fallback is safe there and nowhere else. if ( $id > 0 && function_exists( 'get_the_author' ) ) { $author = get_the_author(); if ( is_string( $author ) ) { return $author; } } return ''; } /** * Resolve %%category%% token (first category name). * * @param Context $ctx Context. * @return string The result. */ private function resolveCategory( Context $ctx ): string { // Term archives resolve the queried term name, never a category // looked up against the term id as if it were a post. if ( 'term' === $ctx->queriedType() ) { $termName = $ctx->termName(); if ( '' !== $termName ) { return $termName; } } $id = $ctx->queriedId(); if ( $id > 0 && function_exists( 'get_the_category' ) ) { $cats = get_the_category( $id ); if ( is_array( $cats ) && [] !== $cats && isset( $cats[0] ) ) { $cat = $cats[0]; if ( is_object( $cat ) && isset( $cat->name ) ) { return (string) $cat->name; } if ( is_array( $cat ) && isset( $cat['name'] ) ) { return (string) $cat['name']; } } } return ''; } /** * Resolve %%page%% token. * * @param Context $ctx Context. * @return string The result. */ private function resolvePage( Context $ctx ): string { $paged = 0; $max = 0; if ( function_exists( 'get_query_var' ) ) { $paged = (int) get_query_var( 'paged', 0 ); $max = (int) get_query_var( 'max_num_pages', 0 ); } // Fallback to Context paginated info via query object. if ( 0 === $paged ) { $paged = $ctx->paginated() ? 2 : 0; } if ( $paged > 1 ) { if ( $max > 1 ) { return sprintf( /* translators: 1: current page number, 2: total page count */ __( 'Page %1$d of %2$d', 'rankkernel' ), $paged, $max ); } // Try to get max from global WP_Query. global $wp_query; if ( isset( $wp_query ) && isset( $wp_query->max_num_pages ) && (int) $wp_query->max_num_pages > 1 ) { return sprintf( /* translators: 1: current page number, 2: total page count */ __( 'Page %1$d of %2$d', 'rankkernel' ), $paged, (int) $wp_query->max_num_pages ); } return sprintf( /* translators: %d: current page number */ __( 'Page %d', 'rankkernel' ), $paged ); } return ''; } /** * Resolve %%currentdate%% token. * * @return string The result. */ private function resolveCurrentDate(): string { if ( function_exists( 'date_i18n' ) ) { $format = 'F j, Y'; if ( function_exists( 'get_option' ) ) { $opt = get_option( 'date_format', 'F j, Y' ); if ( is_string( $opt ) && '' !== $opt ) { $format = $opt; } } return (string) date_i18n( $format ); } return gmdate( 'F j, Y' ); } /** * Clear memo (useful in tests). */ public function clearMemo(): void { $this->memo = []; $this->tokenCache = []; } }