View source
<?php
namespace Drupal\Tests\Component\Render;
use Drupal\Component\Render\FormattableMarkup;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
class FormattableMarkupTest extends TestCase {
use ExpectDeprecationTrait;
protected $lastErrorMessage;
protected $lastErrorNumber;
public function testToString() {
$string = 'Can I please have a @replacement';
$formattable_string = new FormattableMarkup($string, [
'@replacement' => 'kitten',
]);
$text = (string) $formattable_string;
$this
->assertEquals('Can I please have a kitten', $text);
$text = $formattable_string
->jsonSerialize();
$this
->assertEquals('Can I please have a kitten', $text);
}
public function testCount() {
$string = 'Can I please have a @replacement';
$formattable_string = new FormattableMarkup($string, [
'@replacement' => 'kitten',
]);
$this
->assertEquals(strlen($string), $formattable_string
->count());
}
public function errorHandler($error_number, $error_message) {
$this->lastErrorNumber = $error_number;
$this->lastErrorMessage = $error_message;
}
public function testUnexpectedPlaceholder($string, $arguments, $error_number, $error_message) {
set_error_handler([
$this,
'errorHandler',
]);
$markup = new FormattableMarkup($string, $arguments);
$output = (string) $markup;
restore_error_handler();
$this
->assertEquals($string, $output);
$this
->assertEquals($error_number, $this->lastErrorNumber);
$this
->assertEquals($error_message, $this->lastErrorMessage);
}
public function providerTestUnexpectedPlaceholder() {
return [
[
'Non alpha starting character: ~placeholder',
[
'~placeholder' => 'replaced',
],
E_USER_WARNING,
'Invalid placeholder (~placeholder) with string: "Non alpha starting character: ~placeholder"',
],
[
'Alpha starting character: placeholder',
[
'placeholder' => 'replaced',
],
E_USER_WARNING,
'Invalid placeholder (placeholder) with string: "Alpha starting character: placeholder"',
],
[
'placeholder',
[
'placeholder' => 'replaced',
],
E_USER_WARNING,
'Invalid placeholder (placeholder) with string: "placeholder"',
],
];
}
public function testNoReplacementUnsupportedVariable() {
$this
->expectDeprecation('Support for keys without a placeholder prefix is deprecated in Drupal 9.1.0 and will be removed in Drupal 10.0.0. Invalid placeholder (foo) with string: "No replacements"');
$markup = new FormattableMarkup('No replacements', [
'foo' => 'bar',
]);
$output = (string) $markup;
}
}