Fail with a clearer error when a translation placeholder isn't a string

Created on 30 April 2019, over 5 years ago
Updated 18 November 2023, 10 months ago

If as a developer you accidentally pass something that's not a string as a translation placeholder value, e.g.

t('this @placeholder is great!', ['@placeholder' => $whoops_this_is_an_object])

then you get this error from the innards of PHP:

> Warning: htmlspecialchars() expects parameter 1 to be string, object given in core/lib/Drupal/Component/Utility/Html.php on line 424

We could throw a better error by checking in TranslatableMarkup::__construct(), which already checks that the first parameter to t() is ok:

    if (!is_string($string)) {
      $message = $string instanceof TranslatableMarkup ? '$string ("' . $string->getUntranslatedString() . '") must be a string.' : '$string ("' . (string) $string . '") must be a string.';
      throw new \InvalidArgumentException($message);
    }

Maybe something like this:

    foreach ($arguments as $placeholder => $argument) {
      if (!is_string($argument) && !($argument instanceof TranslatableMarkup)) {
        // dump($argument);
        $message = sprintf('Value for %s placeholder in translated string "%s" must be a string.',
          $placeholder,
          $string instanceof TranslatableMarkup ? $string->getUntranslatedString() : (string) $string
        );
        // throw new \InvalidArgumentException($message);
      }
  	}

Alternatively, make it an assert() so it only crashes tests, since currently we only get a warning?

📌 Task
Status

Active

Version

11.0 🔥

Component
Language system 

Last updated 1 day ago

  • Maintained by
  • 🇩🇪Germany @sun
Created by

🇬🇧United Kingdom joachim

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024