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"',
      ],
      [
        'No replacements',
        [
          'foo' => 'bar',
        ],
        E_USER_WARNING,
        'Invalid placeholder (foo) with string: "No replacements"',
      ],
    ];
  }
}