Completed
Pull Request — master (#299)
by
unknown
18:21
created

FileTranslator::getTranslationsFromFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
ccs 3
cts 4
cp 0.75
cc 2
eloc 5
nc 2
nop 1
crap 2.0625
1
<?php
2
3
/**
4
 * This file is part of the Grido (http://grido.bugyik.cz)
5
 *
6
 * Copyright (c) 2011 Petr Bugyík (http://petr.bugyik.cz)
7
 *
8
 * For the full copyright and license information, please view
9
 * the file LICENSE.md that was distributed with this source code.
10
 */
11
12
namespace Grido\Translations;
13
14
use Grido\Exception;
15
use Nette;
16
17
/**
18
 * Simple file translator.
19
 *
20
 * @package     Grido
21
 * @subpackage  Translations
22
 * @author      Petr Bugyík
23
 */
24 1
class FileTranslator implements \Nette\Localization\ITranslator
25
{
26 1
    use Nette\SmartObject;
27
28
    /** @var array */
29
    protected $translations = [];
30
31
    /**
32
     * @param string $lang
33
     * @param array $translations
34
     */
35
    public function __construct($lang = 'en', array $translations = [])
36
    {
37 1
        $translations = $translations + $this->getTranslationsFromFile($lang);
38 1
        $this->translations = $translations;
39 1
    }
40
41
    /**
42
     * Sets language of translation.
43
     * @param string $lang
44
     */
45
    public function setLang($lang)
46
    {
47
        $this->translations = $this->getTranslationsFromFile($lang);
48
    }
49
50
    /**
51
     * @param string $lang
52
     * @throws Exception
53
     * @return array
54
     */
55
    protected function getTranslationsFromFile($lang)
56
    {
57 1
        $filename = __DIR__ . "/$lang.php";
58 1
        if (!file_exists($filename)) {
59
            throw new Exception("Translations for language '$lang' not found.");
60
        }
61
62 1
        return include ($filename);
63
    }
64
65
    /************************* interface \Nette\Localization\ITranslator **************************/
66
67
    /**
68
     * @param string $message
69
     * @param int $count plural
70
     * @return string
71
     */
72
    public function translate($message, $count = NULL)
73
    {
74 1
        return isset($this->translations[$message])
75 1
            ? $this->translations[$message]
76 1
            : $message;
77
    }
78
}
79