3 namespace Drupal\Tests\Core\StringTranslation;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\StringTranslation\TranslationInterface;
7 use Drupal\Core\StringTranslation\TranslatableMarkup;
8 use Drupal\Tests\UnitTestCase;
11 * Tests the TranslatableMarkup class.
13 * @coversDefaultClass \Drupal\Core\StringTranslation\TranslatableMarkup
14 * @group StringTranslation
16 class TranslatableMarkupTest extends UnitTestCase {
19 * The error message of the last error in the error handler.
23 protected $lastErrorMessage;
26 * The error number of the last error in the error handler.
30 protected $lastErrorNumber;
33 * Custom error handler that saves the last error.
35 * We need this custom error handler because we cannot rely on the error to
36 * exception conversion as __toString is never allowed to leak any kind of
39 * @param int $error_number
41 * @param string $error_message
44 public function errorHandler($error_number, $error_message) {
45 $this->lastErrorNumber = $error_number;
46 $this->lastErrorMessage = $error_message;
50 * Tests that errors are correctly handled when a __toString() fails.
52 * @covers ::__toString
54 public function testToString() {
55 $translation = $this->getMock(TranslationInterface::class);
57 $string = 'May I have an exception please?';
58 $text = $this->getMockBuilder(TranslatableMarkup::class)
59 ->setConstructorArgs([$string, [], [], $translation])
60 ->setMethods(['_die'])
63 ->expects($this->once())
68 ->method('translateString')
70 ->willReturnCallback(function () {
71 throw new \Exception('Yes you may.');
74 // We set a custom error handler because of https://github.com/sebastianbergmann/phpunit/issues/487
75 set_error_handler([$this, 'errorHandler']);
76 // We want this to trigger an error.
78 restore_error_handler();
80 $this->assertEquals(E_USER_ERROR, $this->lastErrorNumber);
81 $this->assertRegExp('/Exception thrown while calling __toString on a .*Mock_TranslatableMarkup_.* object in .*TranslatableMarkupTest.php on line [0-9]+: Yes you may./', $this->lastErrorMessage);
85 * @covers ::__construct
87 public function testIsStringAssertion() {
88 $translation = $this->getStringTranslationStub();
89 $this->setExpectedException(\InvalidArgumentException::class, '$string ("foo") must be a string.');
90 new TranslatableMarkup(new TranslatableMarkup('foo', [], [], $translation));
94 * @covers ::__construct
96 public function testIsStringAssertionWithFormattableMarkup() {
97 $formattable_string = new FormattableMarkup('@bar', ['@bar' => 'foo']);
98 $this->setExpectedException(\InvalidArgumentException::class, '$string ("foo") must be a string.');
99 new TranslatableMarkup($formattable_string);