TranslatorCacheTest.php 11 KB

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