VOOZH about

URL: https://deepwiki.com/hypervel/translation/5.1-file-based-loading

⇱ File-Based Loading | hypervel/translation | DeepWiki


Loading...
Menu

File-Based Loading

Purpose and Scope

This document covers the FileLoader class, which implements the file-based translation loading strategy. The FileLoader reads translation data from PHP array files and JSON files stored on disk, manages multiple search paths, handles namespace hints for package-specific translations, and implements vendor override mechanisms for customizing third-party translations.

For information about in-memory translation storage, see Memory-Based Loading. For the contract interface that FileLoader implements, see Loader Contract.


FileLoader Class Architecture

The FileLoader class src/FileLoader.php12 implements the Loader contract src/FileLoader.php12 and serves as the primary mechanism for loading translation files from the filesystem in production environments.

Core Components


Sources: src/FileLoader.php1-175

Property Definitions

PropertyTypePurposeLine Reference
$pathsarrayDefault search paths for standard translation filessrc/FileLoader.php17
$jsonPathsarrayDedicated paths for JSON translation filessrc/FileLoader.php22
$hintsarrayNamespace-to-directory mappings for package translationssrc/FileLoader.php27
$filesFilesystemFilesystem service for reading filessrc/FileLoader.php35

Sources: src/FileLoader.php14-27 src/FileLoader.php34-41


Path Management System

The FileLoader maintains three distinct path registries to support different translation loading strategies.

Path Types and Registration


Sources: src/FileLoader.php131-158

Standard Paths

The $paths array stores directories where standard translation files are located. Files are organized as {path}/{locale}/{group}.php.

Registration:


Retrieval:


JSON Paths

The $jsonPaths array stores directories specifically for JSON translation files, organized as {path}/{locale}.json.

Registration:


Retrieval:


Namespace Hints

The $hints array maps namespace identifiers to directory paths, enabling package-specific translations that don't conflict with application translations.

Registration:


Retrieval:


Sources: src/FileLoader.php131-174


Loading Strategies

The FileLoader implements four distinct loading strategies based on the combination of $group and $namespace parameters passed to the load() method src/FileLoader.php46-57

Load Method Dispatch Logic


Sources: src/FileLoader.php46-57

Standard Path Loading

When $namespace is null or '*', the loader searches through all registered standard paths src/FileLoader.php52-54

Method: loadPaths(array $paths, string $locale, string $group) src/FileLoader.php93-103

Algorithm:

  1. Iterate through each path in the $paths array
  2. Check if file exists at {path}/{locale}/{group}.php
  3. If exists, require the file and merge with accumulated output using array_replace_recursive
  4. Return merged array

File Resolution Pattern:

{path}/{locale}/{group}.php

Example:

/app/lang/en/messages.php
/app/lang/es/messages.php
/vendor/package/lang/en/validation.php

Sources: src/FileLoader.php93-103

Namespaced Loading

When $namespace is provided and not '*', the loader uses namespace hints to locate package-specific translations src/FileLoader.php56

Method: loadNamespaced(string $locale, string $group, string $namespace) src/FileLoader.php62-71

Algorithm:

  1. Check if namespace exists in $hints array
  2. Load translations from hint path using loadPaths()
  3. Apply vendor overrides using loadNamespaceOverrides()
  4. Return merged array (or empty array if namespace not registered)

File Resolution Pattern:

{hint_path}/{locale}/{group}.php

Example:

// Namespace: 'admin-panel'
// Hint: '/vendor/admin-panel/lang'
// Resolves to: /vendor/admin-panel/lang/en/messages.php

Sources: src/FileLoader.php62-71

Vendor Override Mechanism

The loadNamespaceOverrides() method src/FileLoader.php76-88 allows applications to customize package translations without modifying vendor code.

Algorithm:

  1. Start with base translations loaded from namespace hint
  2. Iterate through all standard paths
  3. Check for override file at {path}/vendor/{namespace}/{locale}/{group}.php
  4. If exists, merge recursively, with overrides taking precedence
  5. Return merged array

Override File Pattern:

{path}/vendor/{namespace}/{locale}/{group}.php

Example:

// Package translation:
/vendor/admin-panel/lang/en/messages.php
 ['welcome' => 'Welcome to Admin']

// Application override:
/app/lang/vendor/admin-panel/en/messages.php
 ['welcome' => 'Welcome to Dashboard']

// Result: 'Welcome to Dashboard' (override wins)

Sources: src/FileLoader.php76-88

JSON Loading

When both $group and $namespace are '*', the loader treats this as a request for JSON translations src/FileLoader.php48-50

Method: loadJsonPaths(string $locale) src/FileLoader.php110-126

Algorithm:

  1. Merge $jsonPaths and $paths arrays
  2. Iterate through combined paths
  3. Check if file exists at {path}/{locale}.json
  4. If exists, read file content and decode JSON
  5. Validate JSON structure (throw RuntimeException on invalid JSON)
  6. Merge with accumulated output using array_merge
  7. Return merged array

File Resolution Pattern:

{path}/{locale}.json

Example:

/app/lang/en.json
/custom/json/en.json

Error Handling:

If JSON is malformed, the method throws a RuntimeException src/FileLoader.php118-119:


Sources: src/FileLoader.php110-126


File Format Requirements

The FileLoader supports two file formats, each with specific structural requirements.

PHP Array Files

PHP translation files must return an array from the file src/FileLoader.php98

Structure:


Loading: Files are loaded using Filesystem::getRequire() src/FileLoader.php98 which requires the file and returns the returned value.

Merging: Multiple PHP files are merged using array_replace_recursive() src/FileLoader.php98 meaning:

  • Scalar values in later files override earlier files
  • Nested arrays are merged recursively
  • Keys not present in later files are preserved from earlier files

JSON Files

JSON translation files must contain a valid JSON object src/FileLoader.php110-126

Structure:


Loading: Files are read using Filesystem::get() and decoded with json_decode() src/FileLoader.php115

Validation: The loader checks for valid JSON structure using json_last_error() src/FileLoader.php117

Merging: Multiple JSON files are merged using array_merge() src/FileLoader.php121 meaning later keys override earlier keys without recursion.

Limitations:

  • JSON files support only single-level key-value pairs
  • No nested structures allowed
  • Used primarily for simple string-to-string mappings

Sources: src/FileLoader.php93-126


Loading Execution Flow

The following diagram illustrates how translation loading requests flow through the FileLoader system to resolve files.


Sources: src/FileLoader.php46-126


Factory Integration

The LoaderFactory src/LoaderFactory.php12-28 creates FileLoader instances with properly configured paths.

Factory Implementation


Sources: src/LoaderFactory.php1-28

Path Initialization

The factory initializes the FileLoader with two paths src/LoaderFactory.php20-26:

  1. Package Path: dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lang'

    • Points to the lang directory within the translation package itself
    • Contains default translations shipped with the package
    • Typically includes validation messages and other system translations
  2. Application Path: Determined by container type

    • If container implements ApplicationContract: uses $container->langPath() src/LoaderFactory.php17
    • Otherwise: uses BASE_PATH . DIRECTORY_SEPARATOR . 'lang' src/LoaderFactory.php18
    • Contains application-specific translations
    • Takes precedence over package translations due to merge order

Path Priority:

Since paths are passed as [packagePath, appPath] src/LoaderFactory.php22-25 and loadPaths() uses array_replace_recursive() src/FileLoader.php98 the application path takes precedence:


Sources: src/LoaderFactory.php14-27


Path Resolution Examples

The following table illustrates how different translation keys resolve to file paths.

Translation KeyNamespaceLocaleFile Path Resolution
messages.welcomenullen{path}/en/messages.php
validation.requirednulles{path}/es/validation.php
admin::auth.loginadminen{hint[admin]}/en/auth.php
then check {path}/vendor/admin/en/auth.php
Welcome* (JSON)fr{jsonPath}/fr.json
package::errors.404packagede{hint[package]}/de/errors.php
then check {path}/vendor/package/de/errors.php

Sources: src/FileLoader.php46-126


Error Handling

The FileLoader implements minimal error handling, focused on data integrity.

JSON Validation

When loading JSON files, the loader validates JSON structure src/FileLoader.php117-119:


Validation Checks:

  • is_null($decoded): Catches null return from json_decode()
  • json_last_error() !== JSON_ERROR_NONE: Catches any JSON parsing errors

Exception Type: RuntimeException

Exception Message: Includes full file path for debugging

Missing Files

Missing translation files are silently ignored src/FileLoader.php97 src/FileLoader.php114:

  • loadPaths(): Checks $this->files->exists() before loading
  • loadJsonPaths(): Checks $this->files->exists() before loading
  • If file doesn't exist, continues to next path
  • Returns empty array or partial results if no files found

Missing Namespaces

When a namespace is not registered in $hints, loadNamespaced() returns an empty array src/FileLoader.php70:


Sources: src/FileLoader.php70 src/FileLoader.php97 src/FileLoader.php114 src/FileLoader.php117-119


Performance Considerations

The FileLoader implements several design patterns that affect performance:

Lazy Loading

Translation files are loaded on-demand when requested by the Translator src/FileLoader.php46 Files are not preloaded during FileLoader construction.

No Internal Caching

The FileLoader does not cache loaded translations. Each call to load() reads from disk (via the Filesystem service). Caching is implemented at the Translator level (documented in Core Translation System).

Multiple File System Calls

The loader makes sequential file existence checks for each path src/FileLoader.php97 src/FileLoader.php114:

  • Standard loading: checks each path in $paths array
  • Namespaced loading: checks hint path + override paths
  • JSON loading: checks each path in merged $jsonPaths and $paths

Recursive Array Merging

PHP array files use array_replace_recursive() src/FileLoader.php98 which recursively processes nested arrays. For deeply nested translation files, this can be computationally expensive.

Sources: src/FileLoader.php46 src/FileLoader.php93-126