Problem/Motivation
I tried to find related issues in the meta #3220021: [meta] Ensure compatibility of Drupal 9 with PHP 8.1 (as it evolves) but failed, sorry if this is a duplicate.
I'm upgrading an inherited project into PHP8.1 and I'm seeing deprecation messages such as
Deprecated function: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in Drupal\filter\Element\ProcessedText::preRenderText() (line 101 of core/modules/filter/src/Element/ProcessedText.php).
Steps to reproduce
- Create a render array of type '#processed_text' where the text value is NULL:
$build = [
'#type' => 'processed_text',
'#text' => NULL,
'#format' => 'filtered_html',
];
\Drupal::service('renderer')->renderRoot($build);
Proposed resolution
This is an instance of PHP 8.1: Passing null to non-nullable internal function parameters is deprecated and if we were to use string casting null is always converted to an empty string.
To ensure #text is always treated as a string while preserving error visibility if it’s not set, the following change is recommended:
$text = (string) $element['#text'];
For an example of why this is preferable, see this demonstration.