TranslationStringTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Drupal\KernelTests\Core\StringTranslation;
  3. use Drupal\Core\Site\Settings;
  4. use Drupal\KernelTests\KernelTestBase;
  5. use Drupal\language\Entity\ConfigurableLanguage;
  6. /**
  7. * Tests the TranslatableMarkup class.
  8. *
  9. * @group StringTranslation
  10. */
  11. class TranslationStringTest extends KernelTestBase {
  12. /**
  13. * Modules to enable.
  14. *
  15. * @var array
  16. */
  17. public static $modules = [
  18. 'language'
  19. ];
  20. /**
  21. * {@inheritdoc}
  22. */
  23. protected function setUp() {
  24. parent::setUp();
  25. ConfigurableLanguage::createFromLangcode('de')->save();
  26. }
  27. /**
  28. * Tests that TranslatableMarkup objects can be compared.
  29. */
  30. public function testComparison() {
  31. $this->rebootAndPrepareSettings();
  32. $a = \Drupal::service('string_translation')->translate('Example @number', ['@number' => 42], ['langcode' => 'de']);
  33. $this->rebootAndPrepareSettings();
  34. $b = \Drupal::service('string_translation')->translate('Example @number', ['@number' => 42], ['langcode' => 'de']);
  35. $c = \Drupal::service('string_translation')->translate('Example @number', ['@number' => 43], ['langcode' => 'de']);
  36. $d = \Drupal::service('string_translation')->translate('Example @number', ['@number' => 42], ['langcode' => 'en']);
  37. // The two objects have the same settings so == comparison will work.
  38. $this->assertEquals($a, $b);
  39. // The two objects are not the same object.
  40. $this->assertNotSame($a, $b);
  41. // TranslationWrappers which have different settings are not equal.
  42. $this->assertNotEquals($a, $c);
  43. $this->assertNotEquals($a, $d);
  44. }
  45. /**
  46. * Reboots the kernel to set custom translations in Settings.
  47. */
  48. protected function rebootAndPrepareSettings() {
  49. // Reboot the container so that different services are injected and the new
  50. // settings are picked.
  51. $kernel = $this->container->get('kernel');
  52. $kernel->shutdown();
  53. $kernel->boot();
  54. $settings = Settings::getAll();
  55. $settings['locale_custom_strings_de'] = ['' => ['Example @number' => 'Example @number translated']];
  56. // Recreate the settings static.
  57. new Settings($settings);
  58. }
  59. }