For truncate, Deprecated function: mb_strlen(): Passing null to parameter #1 ($string) of type string is deprecated in Drupal\Component\Utility\Unicode::truncate() (line 310)

Created on 17 October 2024, 4 months ago

Problem/Motivation

Deprecation notice is logged when truncating a field that is not set by feed.

Steps to reproduce

I have an iCal feed that maps the event Location to a text field. I add the Tamper "Truncate" plugin to that field (I want to truncate the text to max of 255 characters). When the Location is not set in the source feed, the message Deprecated function: mb_strlen(): Passing null to parameter #1 ($string) of type string is deprecated in Drupal\Component\Utility\Unicode::truncate() is logged. Traceback indicates the source is from modules/tamper/src/Plugin/Tamper/TruncateText.php(78).

Proposed resolution

The simplest resolution is probably to test the argument and, if null, just return an empty string. In TruncateText.php, lines 77-80, alter line 78 to:

public function tamper($data, TamperableItemInterface $item = NULL) {
    return empty($data)?'' : Unicode::truncate(
      $data,
      $this->getSetting(self::SETTING_NUM_CHAR),

An alternative would be to cast the argument of Unicode::truncate() to string - but I don't see that this adds any value:

public function tamper($data, TamperableItemInterface $item = NULL) {
    return Unicode::truncate(
      (string) $data,
      $this->getSetting(self::SETTING_NUM_CHAR),

Either of these resolves the issue for me.

🐛 Bug report
Status

Active

Component

Code

Created by

🇺🇸United States peter pulsifer

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

Comments & Activities

  • Issue created by @peter pulsifer
  • 🇳🇱Netherlands megachriz

    I think that something like solution #1 makes more sense. However, not with using empty() as that will make 0 into an empty string too. I think we can even apply solution #2 as well - in the case that an object is passed. Then the Tamper would attempt to cast that object to a string.

    This needs to be fixed in the Tamper project though, so moving this issue to that project.

  • 🇮🇳India abhishek_virasat

    I tried #2 approach, and it works. created patch. please review it once

  • 🇳🇱Netherlands megachriz

    @abhishek_gupta1
    Thanks for your contribution, but I think you picked the wrong file to adjust. The file to adjust is TruncateText.

    Also, I think that a test case needs to be added to \Drupal\Tests\tamper\Unit\Plugin\Tamper\TruncateTextTest to check if an empty string gets returned when NULL is passed to the plugin.

    Also note that the drupal.org testbot no longer evaluates patches. So before a fix can be accepted, it first needs to be in a merge request.

  • 🇳🇱Netherlands megachriz

    I guess I already addressed this issue before, I just did not finalize it yet: 🐛 PHP notice when passing NULL to the TruncateText plugin Needs review

Production build 0.71.5 2024