,metadata:array>,fallback_scopes:list} */ private readonly array $snapshot; /** @param list $scopes */ public function __construct( UserCopyRuntimeReader $reader, string $locale, array $scopes ) { $this->snapshot = $reader->read($locale, $scopes); } public static function forPage( UserCopyRuntimeReader $reader, string $locale, string $page ): self { return new self($reader, $locale, $reader->scopesForPage($page)); } /** @param array $parameters */ public function text(string $key, array $parameters = []): string { if (!array_key_exists($key, $this->snapshot['messages']) || !isset($this->snapshot['metadata'][$key])) { throw new UserCopyCatalogException( 'Unknown user copy key: ' . $key ); } $message = $this->snapshot['messages'][$key]; $metadata = $this->snapshot['metadata'][$key]; if (($metadata['hidden'] ?? false) === true) { return ''; } $required = is_array($metadata['parameters'] ?? null) ? $metadata['parameters'] : []; $missing = array_values(array_diff($required, array_keys($parameters))); if ($missing !== []) { throw new UserCopyCatalogException( 'Missing user copy parameters for ' . $key . ': ' . implode(', ', $missing) ); } if (($metadata['format'] ?? 'plain_text') !== 'icu') { return $message; } $formatter = MessageFormatter::create( $this->snapshot['locale'], $message ); if (!$formatter instanceof MessageFormatter) { throw new UserCopyCatalogException( 'Unable to create user copy formatter for ' . $key . '.' ); } $result = $formatter->format($parameters); if (!is_string($result)) { throw new UserCopyCatalogException( 'Unable to format user copy for ' . $key . ': ' . $formatter->getErrorMessage() ); } return $result; } /** * @param array $parameters * @return array{title:string,body:string,tone:string} */ public function toast(string $baseKey, array $parameters = []): array { $titleKey = $baseKey . '.title'; $bodyKey = $baseKey . '.body'; if (!isset($this->snapshot['messages'][$bodyKey]) && isset($this->snapshot['messages'][$baseKey . '.message'])) { $bodyKey = $baseKey . '.message'; } $tone = $this->snapshot['metadata'][$bodyKey]['severity'] ?? $this->snapshot['metadata'][$titleKey]['severity'] ?? 'info'; return [ 'title' => $this->text($titleKey, $parameters), 'body' => $this->text($bodyKey, $parameters), 'tone' => is_string($tone) ? $tone : 'info', ]; } /** @return array */ public function catalog(): array { return $this->snapshot; } public function locale(): string { return $this->snapshot['locale']; } public function generation(): ?string { return $this->snapshot['generation']; } }