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