Translator::translations()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 4
eloc 7
c 2
b 1
f 1
nc 4
nop 1
dl 0
loc 14
ccs 4
cts 4
cp 1
crap 4
rs 10
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Utils;
13
14
use BlitzPHP\Utilities\Iterable\Arr;
15
16
/**
17
 * Translation of validation rules errors
18
 */
19
abstract class Translator
20
{
21
    /**
22
     * Translations
23
     *
24
     * @var array<string, array<string, string>>
25
     *
26
     * @example
27
     * ```
28
     * [
29
     *  'en' => [
30
     *      'home' => 'Home'
31
     *  ],
32
     *  'fr' => [
33
     *      'home' => 'Accueil'
34
     *  ]
35
     * ]
36
     * ```
37
     */
38
    private static array $translations = [];
39
40
    /**
41
     * Get the translation for the given key in the given locale.
42
     */
43
    public static function translate(string $key, string $locale, bool $strict = false): ?string
44
    {
45 132
        $translations = self::translations($locale);
46 132
        $translation  = Arr::getRecursive($translations, $key);
47 132
        $translation  = $translation ?? ($strict ? null : $key);
48
49 132
        return is_string($translation) ? $translation : null;
50
    }
51
52
    /**
53
     * Get the translations of a given locale
54
     */
55
    private static function translations(string $locale): array
56
    {
57 132
        $locale = strtolower(substr($locale, 0, 2));
58
59
        if (empty(self::$translations[$locale])) {
60
            foreach ([$locale, 'en'] as $lang) {
61
                if (file_exists($file = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $lang . '.php')) {
62 2
                    self::$translations[$locale] = require $file;
63 2
                    break;
64
                }
65
            }
66
        }
67
68 132
        return (array) (self::$translations[$locale] ?? []);
69
    }
70
}
71