TranslatorCacheTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Config\Resource\SelfCheckingResourceInterface;
  13. use Symfony\Component\Translation\Loader\ArrayLoader;
  14. use Symfony\Component\Translation\Loader\LoaderInterface;
  15. use Symfony\Component\Translation\MessageCatalogue;
  16. use Symfony\Component\Translation\Translator;
  17. class TranslatorCacheTest extends TestCase
  18. {
  19. protected $tmpDir;
  20. protected function setUp()
  21. {
  22. $this->tmpDir = sys_get_temp_dir().'/sf_translation';
  23. $this->deleteTmpDir();
  24. }
  25. protected function tearDown()
  26. {
  27. $this->deleteTmpDir();
  28. }
  29. protected function deleteTmpDir()
  30. {
  31. if (!file_exists($dir = $this->tmpDir)) {
  32. return;
  33. }
  34. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->tmpDir), \RecursiveIteratorIterator::CHILD_FIRST);
  35. foreach ($iterator as $path) {
  36. if (preg_match('#[/\\\\]\.\.?$#', $path->__toString())) {
  37. continue;
  38. }
  39. if ($path->isDir()) {
  40. rmdir($path->__toString());
  41. } else {
  42. unlink($path->__toString());
  43. }
  44. }
  45. rmdir($this->tmpDir);
  46. }
  47. /**
  48. * @dataProvider runForDebugAndProduction
  49. */
  50. public function testThatACacheIsUsed($debug)
  51. {
  52. $locale = 'any_locale';
  53. $format = 'some_format';
  54. $msgid = 'test';
  55. // Prime the cache
  56. $translator = new Translator($locale, null, $this->tmpDir, $debug);
  57. $translator->addLoader($format, new ArrayLoader());
  58. $translator->addResource($format, [$msgid => 'OK'], $locale);
  59. $translator->addResource($format, [$msgid.'+intl' => 'OK'], $locale, 'messages+intl-icu');
  60. $translator->trans($msgid);
  61. $translator->trans($msgid.'+intl', [], 'messages+intl-icu');
  62. // Try again and see we get a valid result whilst no loader can be used
  63. $translator = new Translator($locale, null, $this->tmpDir, $debug);
  64. $translator->addLoader($format, $this->createFailingLoader());
  65. $translator->addResource($format, [$msgid => 'OK'], $locale);
  66. $translator->addResource($format, [$msgid.'+intl' => 'OK'], $locale, 'messages+intl-icu');
  67. $this->assertEquals('OK', $translator->trans($msgid), '-> caching does not work in '.($debug ? 'debug' : 'production'));
  68. $this->assertEquals('OK', $translator->trans($msgid.'+intl', [], 'messages+intl-icu'));
  69. }
  70. public function testCatalogueIsReloadedWhenResourcesAreNoLongerFresh()
  71. {
  72. /*
  73. * The testThatACacheIsUsed() test showed that we don't need the loader as long as the cache
  74. * is fresh.
  75. *
  76. * Now we add a Resource that is never fresh and make sure that the
  77. * cache is discarded (the loader is called twice).
  78. *
  79. * We need to run this for debug=true only because in production the cache
  80. * will never be revalidated.
  81. */
  82. $locale = 'any_locale';
  83. $format = 'some_format';
  84. $msgid = 'test';
  85. $catalogue = new MessageCatalogue($locale, []);
  86. $catalogue->addResource(new StaleResource()); // better use a helper class than a mock, because it gets serialized in the cache and re-loaded
  87. /** @var LoaderInterface|\PHPUnit_Framework_MockObject_MockObject $loader */
  88. $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
  89. $loader
  90. ->expects($this->exactly(2))
  91. ->method('load')
  92. ->will($this->returnValue($catalogue))
  93. ;
  94. // 1st pass
  95. $translator = new Translator($locale, null, $this->tmpDir, true);
  96. $translator->addLoader($format, $loader);
  97. $translator->addResource($format, null, $locale);
  98. $translator->trans($msgid);
  99. // 2nd pass
  100. $translator = new Translator($locale, null, $this->tmpDir, true);
  101. $translator->addLoader($format, $loader);
  102. $translator->addResource($format, null, $locale);
  103. $translator->trans($msgid);
  104. }
  105. /**
  106. * @dataProvider runForDebugAndProduction
  107. */
  108. public function testDifferentTranslatorsForSameLocaleDoNotOverwriteEachOthersCache($debug)
  109. {
  110. /*
  111. * Similar to the previous test. After we used the second translator, make
  112. * sure there's still a usable cache for the first one.
  113. */
  114. $locale = 'any_locale';
  115. $format = 'some_format';
  116. $msgid = 'test';
  117. // Create a Translator and prime its cache
  118. $translator = new Translator($locale, null, $this->tmpDir, $debug);
  119. $translator->addLoader($format, new ArrayLoader());
  120. $translator->addResource($format, [$msgid => 'OK'], $locale);
  121. $translator->trans($msgid);
  122. // Create another Translator with a different catalogue for the same locale
  123. $translator = new Translator($locale, null, $this->tmpDir, $debug);
  124. $translator->addLoader($format, new ArrayLoader());
  125. $translator->addResource($format, [$msgid => 'FAIL'], $locale);
  126. $translator->trans($msgid);
  127. // Now the first translator must still have a usable cache.
  128. $translator = new Translator($locale, null, $this->tmpDir, $debug);
  129. $translator->addLoader($format, $this->createFailingLoader());
  130. $translator->addResource($format, [$msgid => 'OK'], $locale);
  131. $this->assertEquals('OK', $translator->trans($msgid), '-> the cache was overwritten by another translator instance in '.($debug ? 'debug' : 'production'));
  132. }
  133. public function testGeneratedCacheFilesAreOnlyBelongRequestedLocales()
  134. {
  135. $translator = new Translator('a', null, $this->tmpDir);
  136. $translator->setFallbackLocales(['b']);
  137. $translator->trans('bar');
  138. $cachedFiles = glob($this->tmpDir.'/*.php');
  139. $this->assertCount(1, $cachedFiles);
  140. }
  141. public function testDifferentCacheFilesAreUsedForDifferentSetsOfFallbackLocales()
  142. {
  143. /*
  144. * Because the cache file contains a catalogue including all of its fallback
  145. * catalogues, we must take the set of fallback locales into consideration when
  146. * loading a catalogue from the cache.
  147. */
  148. $translator = new Translator('a', null, $this->tmpDir);
  149. $translator->setFallbackLocales(['b']);
  150. $translator->addLoader('array', new ArrayLoader());
  151. $translator->addResource('array', ['foo' => 'foo (a)'], 'a');
  152. $translator->addResource('array', ['bar' => 'bar (b)'], 'b');
  153. $this->assertEquals('bar (b)', $translator->trans('bar'));
  154. // Remove fallback locale
  155. $translator->setFallbackLocales([]);
  156. $this->assertEquals('bar', $translator->trans('bar'));
  157. // Use a fresh translator with no fallback locales, result should be the same
  158. $translator = new Translator('a', null, $this->tmpDir);
  159. $translator->addLoader('array', new ArrayLoader());
  160. $translator->addResource('array', ['foo' => 'foo (a)'], 'a');
  161. $translator->addResource('array', ['bar' => 'bar (b)'], 'b');
  162. $this->assertEquals('bar', $translator->trans('bar'));
  163. }
  164. public function testPrimaryAndFallbackCataloguesContainTheSameMessagesRegardlessOfCaching()
  165. {
  166. /*
  167. * As a safeguard against potential BC breaks, make sure that primary and fallback
  168. * catalogues (reachable via getFallbackCatalogue()) always contain the full set of
  169. * messages provided by the loader. This must also be the case when these catalogues
  170. * are (internally) read from a cache.
  171. *
  172. * Optimizations inside the translator must not change this behaviour.
  173. */
  174. /*
  175. * Create a translator that loads two catalogues for two different locales.
  176. * The catalogues contain distinct sets of messages.
  177. */
  178. $translator = new Translator('a', null, $this->tmpDir);
  179. $translator->setFallbackLocales(['b']);
  180. $translator->addLoader('array', new ArrayLoader());
  181. $translator->addResource('array', ['foo' => 'foo (a)'], 'a');
  182. $translator->addResource('array', ['foo' => 'foo (b)'], 'b');
  183. $translator->addResource('array', ['bar' => 'bar (b)'], 'b');
  184. $translator->addResource('array', ['baz' => 'baz (b)'], 'b', 'messages+intl-icu');
  185. $catalogue = $translator->getCatalogue('a');
  186. $this->assertFalse($catalogue->defines('bar')); // Sure, the "a" catalogue does not contain that message.
  187. $fallback = $catalogue->getFallbackCatalogue();
  188. $this->assertTrue($fallback->defines('foo')); // "foo" is present in "a" and "b"
  189. /*
  190. * Now, repeat the same test.
  191. * Behind the scenes, the cache is used. But that should not matter, right?
  192. */
  193. $translator = new Translator('a', null, $this->tmpDir);
  194. $translator->setFallbackLocales(['b']);
  195. $translator->addLoader('array', new ArrayLoader());
  196. $translator->addResource('array', ['foo' => 'foo (a)'], 'a');
  197. $translator->addResource('array', ['foo' => 'foo (b)'], 'b');
  198. $translator->addResource('array', ['bar' => 'bar (b)'], 'b');
  199. $translator->addResource('array', ['baz' => 'baz (b)'], 'b', 'messages+intl-icu');
  200. $catalogue = $translator->getCatalogue('a');
  201. $this->assertFalse($catalogue->defines('bar'));
  202. $fallback = $catalogue->getFallbackCatalogue();
  203. $this->assertTrue($fallback->defines('foo'));
  204. $this->assertTrue($fallback->defines('baz', 'messages+intl-icu'));
  205. }
  206. public function testRefreshCacheWhenResourcesAreNoLongerFresh()
  207. {
  208. $resource = $this->getMockBuilder('Symfony\Component\Config\Resource\SelfCheckingResourceInterface')->getMock();
  209. $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
  210. $resource->method('isFresh')->will($this->returnValue(false));
  211. $loader
  212. ->expects($this->exactly(2))
  213. ->method('load')
  214. ->will($this->returnValue($this->getCatalogue('fr', [], [$resource])));
  215. // prime the cache
  216. $translator = new Translator('fr', null, $this->tmpDir, true);
  217. $translator->addLoader('loader', $loader);
  218. $translator->addResource('loader', 'foo', 'fr');
  219. $translator->trans('foo');
  220. // prime the cache second time
  221. $translator = new Translator('fr', null, $this->tmpDir, true);
  222. $translator->addLoader('loader', $loader);
  223. $translator->addResource('loader', 'foo', 'fr');
  224. $translator->trans('foo');
  225. }
  226. protected function getCatalogue($locale, $messages, $resources = [])
  227. {
  228. $catalogue = new MessageCatalogue($locale);
  229. foreach ($messages as $key => $translation) {
  230. $catalogue->set($key, $translation);
  231. }
  232. foreach ($resources as $resource) {
  233. $catalogue->addResource($resource);
  234. }
  235. return $catalogue;
  236. }
  237. public function runForDebugAndProduction()
  238. {
  239. return [[true], [false]];
  240. }
  241. /**
  242. * @return LoaderInterface
  243. */
  244. private function createFailingLoader()
  245. {
  246. $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
  247. $loader
  248. ->expects($this->never())
  249. ->method('load');
  250. return $loader;
  251. }
  252. }
  253. class StaleResource implements SelfCheckingResourceInterface
  254. {
  255. public function isFresh($timestamp)
  256. {
  257. return false;
  258. }
  259. public function getResource()
  260. {
  261. }
  262. public function __toString()
  263. {
  264. return '';
  265. }
  266. }