Skip to main content

Overview

The TranslationFile class represents a single Laravel translation file. It provides methods for loading, saving, comparing, and manipulating translation data in both PHP array and JSON formats. Namespace: Mateffy\AiTranslations

Class Definition

namespace Mateffy\AiTranslations;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;

class TranslationFile
{
    public function __construct(
        public readonly string $language,
        public readonly string $domain,
        public array $translations,
        protected readonly string $basePath,
    ) {}
}

Constructor

public function __construct(
    string $language,
    string $domain,
    array $translations,
    string $basePath,
)
language
string
required
The language code (e.g., 'en', 'es', 'fr')
domain
string
required
The translation domain/file name (e.g., 'validation', 'auth', 'messages')
translations
array
required
The translations array (can be nested)
basePath
string
required
The base path to the language directory (typically lang_path())

Properties

language
string
The language code for this translation file
domain
string
The domain/file name for this translation file
translations
array
The translations array (mutable)
basePath
string
The base directory path for language files

Static Methods

path()

Generates the file path for a translation file.
public static function path(
    string $language,
    string $domain,
    string $basePath,
): string
language
string
required
The language code
domain
string
required
The translation domain
basePath
string
required
The base language directory path
string
string
The full file path (e.g., /path/to/lang/es/validation.php)

Example

use Mateffy\AiTranslations\TranslationFile;

$path = TranslationFile::path('es', 'validation', lang_path());
// Returns: "/path/to/app/lang/es/validation.php"

load()

Loads a translation file from disk.
public static function load(
    string $language,
    string $domain,
    ?string $basePath = null,
): static
language
string
required
The language code to load
domain
string
required
The translation domain to load
basePath
?string
default:"null"
Optional base path. Defaults to lang_path() if not provided
TranslationFile
static
A new TranslationFile instance. Returns an empty instance if the file doesn’t exist.

Example

use Mateffy\AiTranslations\TranslationFile;

// Load existing file
$file = TranslationFile::load('en', 'validation');

// Load from custom path
$file = TranslationFile::load('es', 'messages', '/custom/lang/path');

// Load non-existent file (returns empty instance)
$newFile = TranslationFile::load('fr', 'newdomain');

flatten()

Flattens a nested array into dot-notated keys (without values).
public static function flatten(array $array, string $prefix = ""): array
array
array
required
The nested array to flatten
prefix
string
default:"''"
Optional prefix for the keys
array
array<int, string>
An indexed array of dot-notated keys

Example

use Mateffy\AiTranslations\TranslationFile;

$nested = [
    'auth' => [
        'failed' => 'These credentials do not match our records.',
        'throttle' => 'Too many login attempts.'
    ],
    'welcome' => 'Welcome!'
];

$flattened = TranslationFile::flatten($nested);
// Result: ['auth.failed', 'auth.throttle', 'welcome']

flattenWithValues()

Flattens a nested array into dot-notated key-value pairs.
public static function flattenWithValues(
    array $array,
    string $prefix = "",
): array
array
array
required
The nested array to flatten
prefix
string
default:"''"
Optional prefix for the keys
array
array<string, string>
An associative array with dot-notated keys and their values

Example

use Mateffy\AiTranslations\TranslationFile;

$nested = [
    'validation' => [
        'required' => 'The :attribute field is required.',
        'email' => 'The :attribute must be a valid email.'
    ]
];

$flattened = TranslationFile::flattenWithValues($nested);
// Result: [
//   'validation.required' => 'The :attribute field is required.',
//   'validation.email' => 'The :attribute must be a valid email.'
// ]

Instance Methods

toJson()

Converts translations to JSON format with dot-notated keys.
public function toJson(): string
string
string
Pretty-printed JSON string with dot-notated keys. Returns "{}" for empty translations.

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('en', 'auth');
$json = $file->toJson();

// Output:
// {
//   "auth.failed": "These credentials do not match our records.",
//   "auth.throttle": "Too many login attempts."
// }

toPhpArray()

Converts translations to PHP array format suitable for Laravel language files.
public function toPhpArray(): string
string
string
A string containing PHP code with a properly formatted array declaration

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('en', 'validation');
$php = $file->toPhpArray();

// Output:
// <?php
//
// return [
//     'required' => "The :attribute field is required.",
//     'email' => "The :attribute must be a valid email address.",
// ];

get()

Retrieves a translation value by its dot-notated key.
public function get(string $key): ?string
key
string
required
The dot-notated key to retrieve (e.g., 'validation.required')
string|null
?string
The translation value, or null if not found

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('en', 'validation');

$value = $file->get('validation.required');
// "The :attribute field is required."

$missing = $file->get('validation.nonexistent');
// null

set()

Sets a translation value using dot notation.
public function set(string $key, string|array $value): void
key
string
required
The dot-notated key to set
value
string|array
required
The translation value. If an array, it will be flattened and each key will be set relative to the provided key.

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('es', 'validation');

// Set a single value
$file->set('validation.required', 'El campo :attribute es obligatorio.');

// Set multiple nested values
$file->set('auth', [
    'failed' => 'Estas credenciales no coinciden.',
    'throttle' => 'Demasiados intentos.'
]);

compare()

Compares this translation file with another to find missing keys.
public function compare(TranslationFile $file): array
file
TranslationFile
required
The translation file to compare against
array
array<int, string>
An array of dot-notated keys that exist in this file but are missing from the compared file

Example

use Mateffy\AiTranslations\TranslationFile;

$english = TranslationFile::load('en', 'validation');
$spanish = TranslationFile::load('es', 'validation');

$missingKeys = $english->compare($spanish);

// Result: ['validation.custom', 'validation.attributes.email']
foreach ($missingKeys as $key) {
    echo "Missing: {$key}\n";
}

apply()

Applies a set of translations to this file.
public function apply(array $translations): self
translations
array
required
An associative array of dot-notated keys and their translation values
self
TranslationFile
Returns the current instance for method chaining

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('fr', 'auth');

$newTranslations = [
    'auth.failed' => 'Ces identifiants ne correspondent pas.',
    'auth.throttle' => 'Trop de tentatives.'
];

$file->apply($newTranslations)->write();

write()

Writes the translation file to disk in PHP array format.
public function write(): void
This method automatically creates the directory structure if it doesn’t exist.

Example

use Mateffy\AiTranslations\TranslationFile;

$file = TranslationFile::load('de', 'messages');
$file->set('welcome', 'Willkommen!');
$file->set('goodbye', 'Auf Wiedersehen!');
$file->write();

// Creates/updates: lang/de/messages.php

Complete Usage Example

use Mateffy\AiTranslations\TranslationFile;

// Load existing translation file
$file = TranslationFile::load('es', 'validation');

// Get a specific translation
$required = $file->get('validation.required');

// Add new translations
$file->set('validation.custom_rule', 'Este campo no es válido.');

// Save changes
$file->write();

Build docs developers (and LLMs) love