|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * @author Miroslav Koula |
| 4 | + * @copyright Copyright (c) 2018 Miroslav Koula, https://elcheco.it |
| 5 | + * @created 01/10/18 14:02 |
| 6 | + */ |
| 7 | + |
| 8 | +declare(strict_types=1); |
| 9 | + |
| 10 | +namespace ElCheco\Translator\NeonDictionary; |
| 11 | + |
| 12 | + |
| 13 | +use function is_array; |
| 14 | +use Nette\Neon\Neon; |
| 15 | +use ElCheco\Translator\Dictionary; |
| 16 | + |
| 17 | +final class NeonDictionary extends Dictionary |
| 18 | +{ |
| 19 | + |
| 20 | + /** |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + private $filename; |
| 24 | + |
| 25 | + /** |
| 26 | + * @var string |
| 27 | + */ |
| 28 | + private $cacheFilename; |
| 29 | + |
| 30 | + /** |
| 31 | + * @var string |
| 32 | + */ |
| 33 | + private $fallbackFilename; |
| 34 | + |
| 35 | + |
| 36 | + public function __construct(string $filename, string $cacheFilename, ?string $fallbackFilename = null) |
| 37 | + { |
| 38 | + if (!is_file($filename)) { |
| 39 | + |
| 40 | + throw NeonDictionaryException::fileNotFound($filename); |
| 41 | + } |
| 42 | + |
| 43 | + if ($fallbackFilename && !is_file($fallbackFilename)) { |
| 44 | + |
| 45 | + throw NeonDictionaryException::fileNotFound($fallbackFilename); |
| 46 | + } |
| 47 | + |
| 48 | + $this->filename = $filename; |
| 49 | + $this->cacheFilename = $cacheFilename; |
| 50 | + |
| 51 | + $this->fallbackFilename = $fallbackFilename; |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | + protected function lazyLoad() |
| 56 | + { |
| 57 | + if (!$this->isReady()) { |
| 58 | + |
| 59 | + if (is_file($this->cacheFilename)) { |
| 60 | + |
| 61 | + // load cache |
| 62 | + $this->setMessages(require $this->cacheFilename); |
| 63 | + |
| 64 | + } else { |
| 65 | + |
| 66 | + // load translations from neon file |
| 67 | + $fallbackDecoded = Neon::decode(file_get_contents($this->fallbackFilename)); |
| 68 | + $fallbackTranslations = is_array($fallbackDecoded) ? $fallbackDecoded: []; |
| 69 | + |
| 70 | + // load translations from neon file |
| 71 | + $decoded = Neon::decode(file_get_contents($this->filename)); |
| 72 | + $translations = is_array($decoded) ? $decoded: []; |
| 73 | + |
| 74 | + $translations = \array_merge($fallbackTranslations, $translations); |
| 75 | + |
| 76 | + // save cache |
| 77 | + $content = '<?php ' . PHP_EOL . 'return ' . var_export($translations, true) . ';' . PHP_EOL; |
| 78 | + file_put_contents("safe://$this->cacheFilename", $content); |
| 79 | + |
| 80 | + $this->setMessages($translations); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments