VOOZH about

URL: https://deepwiki.com/hypervel/translation/2-core-translation-system

⇱ Core Translation System | hypervel/translation | DeepWiki


Loading...
Menu

Core Translation System

Purpose and Scope

This document provides a comprehensive overview of the Translator class, the central component of the translation system. The Translator class is responsible for:

  • Managing the current locale and fallback locale
  • Resolving translation keys to translated strings
  • Processing placeholder replacements in translated text
  • Caching loaded translation data
  • Coordinating with loaders to retrieve translation files
  • Handling missing translation keys

For information about the global helper functions that provide convenient access to the translator, see Global Helper Functions. For details on how translation files are loaded from disk or memory, see Translation Data Loading. For pluralization logic, see Message Selection and Pluralization.

Sources: src/Translator.php1-505


Translator Class Overview

The Translator class is defined at src/Translator.php19 and serves as the primary interface for all translation operations. It extends NamespacedItemResolver (from Hypervel/Support) to inherit key parsing functionality and implements the TranslatorContract interface.

Class Structure


Key Properties

PropertyTypePurpose
$loaderLoaderInterface to load translation files from various sources
$localestringDefault locale (used as fallback when context is empty)
$fallbackstringFallback locale when translation is missing in primary locale
$loadedarrayMulti-dimensional cache of loaded translations: [namespace][group][locale][key]
$selectorMessageSelectorHandles pluralization logic (lazily instantiated)
$determineLocalesUsingcallableOptional callback to customize the locale resolution order
$stringableHandlersarrayCustom handlers for converting objects to strings during replacements
$missingTranslationKeyCallbackcallableCallback invoked when translation keys are not found
$handleMissingTranslationKeysboolFlag to enable/disable missing key callback (prevents infinite loops)

Sources: src/Translator.php19-62


Locale Management

The Translator uses Hyperf's Context system to store the current locale, enabling request-level isolation in concurrent environments. Each coroutine/request can have its own locale without affecting others.

Locale Storage Architecture


Locale Methods

setLocale(string $locale): void

Sets the current locale in the Hyperf context. Validates that the locale string doesn't contain directory traversal characters (/ or \) to prevent security issues.

Implementation: src/Translator.php:440-447
Validation: Throws InvalidArgumentException if locale contains '/' or '\'
Storage: Context::set('__translator.locale', $locale)

getLocale(): string

Retrieves the current locale from context, falling back to the $locale property if the context is empty (e.g., during initial setup or in CLI contexts).

Implementation: src/Translator.php:430-433
Retrieval: Context::get('__translator.locale') ?? $this->locale
Type safety: Always returns string (casts to string)

getFallback(): string and setFallback(string $fallback): void

Manages the fallback locale, which is used when translations are missing in the primary locale. Unlike the primary locale, the fallback is stored directly in the instance property (not in context) and is shared across all requests.

Getter: src/Translator.php:452-455
Setter: src/Translator.php:460-463

Locale Resolution Array

The localeArray() method builds an ordered array of locales to check during translation resolution:


Implementation: src/Translator.php376-381

The determineLocalesUsing() method allows applications to customize locale resolution, enabling scenarios like:

  • Regional fallbacks: ['es-MX', 'es', 'en']
  • User preference chains: [user_locale, org_locale, default_locale]
  • A/B testing with locale variants

Sources: src/Translator.php376-389 src/Translator.php430-447


Translation Resolution Flow

The Translator employs a sophisticated multi-phase resolution strategy that checks JSON translations first, then falls back to namespace/group/item-based PHP translations.

Resolution Process


Phase 1: JSON Translation Lookup

JSON translations are single-level key-value pairs stored in files like lang/en.json. They're loaded once per locale and cached in $loaded['*']['*'][$locale].

Implementation: src/Translator.php122-124

Load: $this->load('*', '*', $locale)
Check: $this->loaded['*']['*'][$locale][$key]
Purpose: Enable simple __('Key') syntax without namespace/group structure

Phase 2: Structured Translation Lookup

If no JSON translation exists, the system parses the key into namespace, group, and item components:

Key Parsing: src/Translator.php130 src/Translator.php362-371

Input: "messages.welcome" → [null, "messages", "welcome"]
 "package::auth.failed" → ["package", "auth", "failed"]
 "validation.required" → [null, "validation", "required"]

After parseKey():
 [null, "messages", "welcome"] → ["*", "messages", "welcome"]

The wildcard namespace * represents the application's default namespace.

Phase 3: Locale Fallback Chain

The system iterates through the locale array (primary + fallback) until a translation is found:

Implementation: src/Translator.php135-147


getLine() Method

The getLine() method retrieves a specific translation item from loaded translations:

Implementation: src/Translator.php204-222


Key Features:

  • Automatic loading: Ensures the translation group is loaded before access
  • Nested array support: Returns entire nested arrays when item points to a parent key
  • Recursive replacement: Applies placeholder replacement to all values in nested arrays
  • Null for missing: Returns null if the item doesn't exist, enabling fallback logic

Sources: src/Translator.php115-161 src/Translator.php204-222


Placeholder Replacement System

The makeReplacements() method processes placeholders in translated strings, supporting standard replacements, case variations, closure-based dynamic content, and custom object handlers.

Replacement Types


Standard Placeholder Syntax

Standard placeholders support three case variations automatically:

Implementation: src/Translator.php253-256

InputReplacement in StringExample
['name' => 'maria']:namemaria"Hello :name" → "Hello maria"
['name' => 'maria']:NameMaria"Hello :Name" → "Hello Maria"
['name' => 'maria']:NAMEMARIA"Hello :NAME" → "Hello MARIA"

Example:

Translation: "Welcome :name! Status: :status"
Replace: ['name' => 'john', 'status' => 'active']
Result: "Welcome john! Status: active"

Translation: "Welcome :Name! Status: :STATUS"
Replace: ['name' => 'john', 'status' => 'active']
Result: "Welcome John! Status: ACTIVE"

Closure-Based Dynamic Replacements

Closures enable dynamic content transformation based on the translated text within tags:

Implementation: src/Translator.php236-243

Pattern: <key>content</key>
Callback: function($capturedContent) { return transformed; }

Example:
Translation: "Click <link>here</link> to continue"
Replace: ['link' => fn($text) => "<a href='/page'>{$text}</a>"]
Result: "Click <a href='/page'>here</a> to continue"

The closure receives the content between the tags and returns the replacement. This enables:

  • Wrapping text with HTML tags
  • Conditional formatting based on content
  • Dynamic URL generation
  • Complex transformations

Custom Object Handlers

The stringable() method registers custom handlers for converting objects to strings during replacement:

Implementation: src/Translator.php476-486


Handler Resolution: src/Translator.php246-248

The system checks if a value is an object and if a handler exists for its class, then invokes the handler to convert it to a string.

Sources: src/Translator.php227-259 src/Translator.php476-486


Caching Strategy

The Translator uses an in-memory cache to avoid repeatedly loading the same translation files within a single application lifecycle.

Cache Structure


The cache is a four-dimensional array: $loaded[namespace][group][locale][key]

Load Method

Implementation: src/Translator.php276-288


Key Points:

  • Guard clause: The isLoaded() check prevents redundant file I/O
  • Loader delegation: Translation loading is delegated to the Loader interface implementation
  • Single load per group: Each namespace/group/locale combination is loaded at most once
  • Whole-group loading: Entire translation groups are loaded together, not individual keys

Cache Inspection Method

The isLoaded() method checks whether a specific translation group has been cached:

Implementation: src/Translator.php293-296


Manual Cache Population

The addLines() method allows programmatic addition of translations to the cache:

Implementation: src/Translator.php264-271


Use cases:

  • Testing with mock translations
  • Runtime translation injection
  • Dynamic content from databases
  • Overriding specific keys without modifying files

Sources: src/Translator.php264-296


Pluralization Integration

While the detailed pluralization logic resides in MessageSelector (see Message Selection and Pluralization), the Translator class provides the choice() method as the entry point for pluralized translations.

Choice Method Flow


Number Type Handling

Implementation: src/Translator.php177-179

The choice() method accepts multiple number types:

TypeHandlingExample
intUsed directlychoice('key', 5)
floatUsed directlychoice('key', 2.5)
arrayCount elementschoice('key', $items) where $items = [1, 2, 3] → count=3
CountableCall count()choice('key', $collection)

Automatic :count Injection

Implementation: src/Translator.php181-183

The system automatically adds :count to the replacement array if not already present, allowing translations to reference the count without manual injection:

Translation: "{1} :count item|[2,*] :count items"
Call: choice('key', 3)
Result: "3 items"

Translation: "{1} one|[2,*] many (:count total)"
Call: choice('key', 5)
Result: "many (5 total)"

Locale Selection for Choice

Implementation: src/Translator.php194-199

The localeForChoice() method determines which locale to use for pluralization:


This ensures that pluralization rules from the correct locale are applied, falling back when translations don't exist in the primary locale.

Sources: src/Translator.php166-189 src/Translator.php194-199


Missing Translation Handling

The Translator provides a flexible system for handling missing translation keys, enabling custom logging, fallback strategies, or alternative resolution mechanisms.

Missing Key Callback

Implementation: src/Translator.php301-323 src/Translator.php328-333


Registering a Missing Key Handler


Callback Parameters:

ParameterTypeDescription
$keystringThe translation key that was not found
$replacearrayThe replacement values provided
$localestringThe locale that was requested
$fallbackboolWhether fallback was enabled

Return Value:

  • Return a string to use as the translation
  • Return null to use the default behavior (return the key itself)

Infinite Loop Prevention

Implementation: src/Translator.php94-100 src/Translator.php303-310 src/Translator.php320

The system includes protection against infinite loops in two scenarios:

  1. During has() checks: The handler is temporarily disabled when checking translation existence to avoid callbacks during the existence check itself.

  2. During callback execution: The handler is disabled before calling the callback and re-enabled afterward, preventing the callback from triggering itself if it attempts to resolve additional translations.


Sources: src/Translator.php87-110 src/Translator.php301-333


Additional Utility Methods

The Translator class provides several utility methods for managing the translation system's configuration and state.

Namespace and Path Management

These methods delegate to the underlying Loader implementation:

Implementation: src/Translator.php338-357

MethodPurpose
addNamespace(string $namespace, string $hint)Register a namespace hint for package translations
addPath(string $path)Add a path for loading standard PHP translation files
addJsonPath(string $path)Add a path for loading JSON translation files

Loader Access

Implementation: src/Translator.php414-417


Provides access to the underlying Loader instance for advanced customization or inspection.

Selector Management

Implementation: src/Translator.php394-409


The selector is lazily instantiated when first needed and can be replaced with a custom implementation if needed.

Compatibility Aliases

Implementation: src/Translator.php422-424 src/Translator.php491-494 src/Translator.php501-504

The Translator provides alias methods for compatibility with different frameworks and coding styles:

MethodDelegates ToPurpose
locale()getLocale()Laravel-style locale getter
trans($key, $replace, $locale)get($key, $replace, $locale)Alternative to get()
transChoice($key, $number, $replace, $locale)choice($key, $number, $replace, $locale)Alternative to choice()

Traits

The Translator class uses two traits:

Implementation: src/Translator.php21-22

  1. Macroable (from Hypervel/Support): Enables adding custom methods at runtime
  2. ReflectsClosures (from Hypervel/Support): Provides closure reflection utilities, used in stringable() method

Sources: src/Translator.php338-357 src/Translator.php394-424 src/Translator.php476-504


Complete Translation Resolution Example

This example demonstrates the full flow of translation resolution, from request to response:


Sources: All methods from src/Translator.php1-505

Refresh this wiki

On this page