|null */ private ?array $map = null; /** @param array $option_tokens */ public function __construct( private readonly \Blocks_Settings_Repository $settings, private readonly array $option_tokens, ) { } public function replace_html( string $content ): string { if ( false === \stripos( $content, 'blocks:' ) ) { return $content; } $replaced = \preg_replace_callback( '/\{\{\s*blocks:([A-Za-z0-9_]{1,40})\s*\}\}/i', fn ( array $matches ): string => \esc_html( $this->resolve( \strtolower( $matches[1] ) ) ), $content, ); return \is_string( $replaced ) ? $replaced : $content; } public function resolve( string $name ): string { return $this->map()[ \strtolower( $name ) ] ?? ''; } /** @return array */ public function public_variables(): array { $variables = array(); foreach ( $this->option_tokens as $option_name => $token_name ) { $variables[ $token_name ] = \str_ends_with( $token_name, '_url' ) ? $this->image_url( $option_name ) : $this->settings->get_string( $option_name ); } $site_title = $variables['site_title']; $tagline = $variables['tagline']; $date_format = \get_option( 'date_format' ); $date_format = \is_string( $date_format ) && '' !== $date_format ? $date_format : 'F j, Y'; return \array_merge( $variables, array( 'phone_plain' => (string) \preg_replace( '/[^0-9]/', '', $variables['phone'] ), 'site_title' => '' !== $site_title ? $site_title : (string) \get_bloginfo( 'name' ), 'tagline' => '' !== $tagline ? $tagline : (string) \get_bloginfo( 'description' ), 'site_url' => (string) \home_url( '/' ), 'year' => (string) \wp_date( 'Y' ), 'month' => (string) \wp_date( 'F' ), 'today' => (string) \wp_date( $date_format ), ), ); } public function flush(): void { $this->map = null; } /** @return array */ private function map(): array { if ( null === $this->map ) { $this->map = $this->public_variables(); } return $this->map; } private function image_url( string $option_name ): string { $attachment_id = $this->settings->get_int( $option_name ); if ( 0 >= $attachment_id ) { return ''; } $url = \wp_get_attachment_url( $attachment_id ); return \is_string( $url ) ? $url : ''; } }