Completed
Push — master ( 468379...ad9d92 )
by Petr
23:49 queued 21:04
created

FileTranslator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 6
c 4
b 1
f 0
lcom 1
cbo 2
dl 0
loc 53
ccs 13
cts 13
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setLang() 0 4 1
A __construct() 0 5 1
A getTranslationsFromFile() 0 9 2
A translate() 0 6 2
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
16
/**
17
 * Simple file translator.
18
 *
19
 * @package     Grido
20
 * @subpackage  Translations
21
 * @author      Petr Bugyík
22
 */
23 1
class FileTranslator extends \Nette\Object implements \Nette\Localization\ITranslator
24
{
25
    /** @var array */
26
    protected $translations = [];
27
28
    /**
29
     * @param string $lang
30
     * @param array $translations
31
     */
32
    public function __construct($lang = 'en', array $translations = [])
33
    {
34 1
        $translations = $translations + $this->getTranslationsFromFile($lang);
35 1
        $this->translations = $translations;
36 1
    }
37
38
    /**
39
     * Sets language of translation.
40
     * @param string $lang
41
     */
42
    public function setLang($lang)
43
    {
44 1
        $this->translations = $this->getTranslationsFromFile($lang);
45 1
    }
46
47
    /**
48
     * @param string $lang
49
     * @throws Exception
50
     * @return array
51
     */
52
    protected function getTranslationsFromFile($lang)
53
    {
54 1
        $filename = __DIR__ . "/$lang.php";
55 1
        if (!file_exists($filename)) {
56 1
            throw new Exception("Translations for language '$lang' not found.");
57
        }
58
59 1
        return include ($filename);
60
    }
61
62
    /************************* interface \Nette\Localization\ITranslator **************************/
63
64
    /**
65
     * @param string $message
66
     * @param int $count plural
67
     * @return string
68
     */
69
    public function translate($message, $count = NULL)
70
    {
71 1
        return isset($this->translations[$message])
72 1
            ? $this->translations[$message]
73 1
            : $message;
74
    }
75
}
76