TranslatorComponent   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 15
dl 0
loc 42
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A translate() 0 16 4
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2020 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
14
namespace App\Controller\Component;
15
16
use Cake\Controller\Component;
17
use Cake\Core\Configure;
18
use Cake\Http\Exception\InternalErrorException;
19
use Cake\Utility\Hash;
20
21
/**
22
 * Translator component. Provide utilities to translate texts.
23
 */
24
class TranslatorComponent extends Component
25
{
26
    /**
27
     * @inheritDoc
28
     */
29
    protected array $_defaultConfig = [
30
        'Translators' => [],
31
    ];
32
33
    /**
34
     * Translators engines registry
35
     *
36
     * @var array
37
     */
38
    protected array $registry = [];
39
40
    /**
41
     * Translate a text $text from language source $from to language target $to
42
     *
43
     * @param array $texts Array of texts to translate
44
     * @param string $from The source language
45
     * @param string $to The target language
46
     * @param string $translatorName The translator engine name
47
     * @return string The translation
48
     * @throws \Cake\Http\Exception\InternalErrorException when translator engine is not configured
49
     */
50
    public function translate(array $texts, string $from, string $to, string $translatorName): string
51
    {
52
        if (empty($this->registry[$translatorName])) {
53
            $translators = (array)Configure::read('Translators');
54
            $translator = (array)Hash::get($translators, $translatorName);
55
            if (empty($translator['class']) && empty($translator['options'])) {
56
                throw new InternalErrorException(sprintf('Translator engine "%s" not configured', $translatorName));
57
            }
58
            $class = $translator['class'];
59
            $options = $translator['options'];
60
            $translator = new $class();
61
            $translator->setup($options);
62
            $this->registry[$translatorName] = $translator;
63
        }
64
65
        return $this->registry[$translatorName]->translate($texts, $from, $to);
66
    }
67
}
68