Overview
TheTranslator class is the main orchestrator for AI-powered translations. It manages the translation workflow, coordinates with the TranslationAgent, handles retry logic, and provides language detection capabilities.
Namespace: Mateffy\AiTranslations
Class Definition
Methods
getLanguages()
Retrieves available languages from the language directory or configuration.The path to the language directory (typically
lang_path())A collection of language codes (e.g.,
['en', 'es', 'fr'])Behavior
- First checks the
ai-translations.languagesconfig value - If not configured, scans the language directory for subdirectories
- Filters out
vendorandlangdirectories - Returns language codes as a collection
Example
translate()
Translates missing keys from a source language file to a target language file using AI.The source translation file containing the original translations
The target translation file where translations will be added
An array of dot-notated keys that need translation (e.g.,
['validation.email', 'auth.failed'])Whether to use the fast model configuration for quicker (but potentially less accurate) translations
Optional progress callback with signature:
function(int $completed, int $total, int $attempt): void$completed: Number of chunks completed$total: Total number of chunks to process$attempt: Current attempt number (0-2)
An associative array of translated keys and values in dot notation format
Behavior
- Processes translations in chunks using
TranslationAgent - Automatically retries up to 3 times for missing translations
- Handles nested array responses by flattening them
- Validates that all requested keys are translated
- Throws an exception if translations are still missing after 3 attempts
Example
The
translate() method uses intelligent retry logic. If the AI doesn’t return all required translations on the first attempt, it will automatically retry up to 3 times with refined prompts.Usage Workflow
Typical workflow for using theTranslator class:
Related Classes
- TranslationFile - Manages individual translation files
- TranslationAgent - Handles AI provider communication