FileTranslator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 51
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A translate() 0 8 2
A __construct() 0 18 3
1
<?php
2
/**
3
 * Translator based on translation files containing an array with texts
4
 *
5
 * PHP version 5.5
6
 *
7
 * @category   OpCacheGUI
8
 * @package    I18n
9
 * @author     Pieter Hordijk <[email protected]>
10
 * @copyright  Copyright (c) 2013 Pieter Hordijk <https://github.com/PeeHaa>
11
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
12
 * @version    1.0.0
13
 */
14
namespace OpCacheGUI\I18n;
15
16
/**
17
 * Translator based on translation files containing an array with texts
18
 *
19
 * @category   OpCacheGUI
20
 * @package    I18n
21
 * @author     Pieter Hordijk <[email protected]>
22
 */
23
class FileTranslator implements Translator
24
{
25
    /**
26
     * @var array The translations
27
     */
28
    private $texts;
29
30
    /**
31
     * Creates instance
32
     *
33
     * @param string $translationDirectory The directory containing the translation files
34
     * @param string $languageCode         The language code of which to get the translations
35
     *
36
     * @throws \Exception When the language is not supported (i.e. no translation file can be found for the language)
37
     * @throws \Exception When the translation file is invalid (i.e. no `$texts` array present)
38
     */
39 5
    public function __construct($translationDirectory, $languageCode)
40
    {
41 5
        $translationFile = $translationDirectory . '/' . $languageCode . '.php';
42
43 5
        if (!file_exists($translationFile)) {
44 1
            throw new \Exception('Unsupported language (`' . $languageCode . '`).');
45
        }
46
47 4
        require $translationFile;
48
49 4
        if (!isset($texts)) {
50 1
            throw new \Exception(
51 1
                'The translation file (`' . $translationFile . '`) has an invalid format.'
52
            );
53
        }
54
55 3
        $this->texts = $texts;
56 3
    }
57
58
    /**
59
     * Gets the translation by key if any or a placeholder otherwise
60
     *
61
     * @param string $key The translation key for which to find the translation
62
     *
63
     * @return string The translation or a placeholder when no translation is available
64
     */
65 2
    public function translate($key)
66
    {
67 2
        if (array_key_exists($key, $this->texts)) {
68 1
            return $this->texts[$key];
69
        }
70
71 1
        return '{{' . $key . '}}';
72
    }
73
}
74