unserialize() of NULL deprecation returns to ViewsReferenceFieldFormatter

Created on 25 February 2024, 9 months ago
Updated 22 April 2024, 7 months ago

Problem/Motivation

Paragraphs with NULL 'data' keys are returning a PHP 8.1 deprecation error due to unserialize() being called on the NULL data. This was solved in 8.x-2.0-beta5 via πŸ› Passing null to parameter #1 ($data) of type string to unserialize() is deprecated Fixed but returned in 8.x-2.0-beta7 for ViewsReferenceFieldFormatter::viewElements() due to changes in πŸ› Issue 2919092 breaks BC and causes issues for existing sites Needs review . As a result, when a views reference field with a null 'data' key is rendered, you get the following deprecation warning:

Deprecated function: unserialize(): Passing null to parameter #1 ($data) of type string is deprecated in Drupal\viewsreference\Plugin\Field\FieldFormatter\ViewsReferenceFieldFormatter->viewElements() (line 98 of modules/contrib/viewsreference/src/Plugin/Field/FieldFormatter/ViewsReferenceFieldFormatter.php).

Steps to reproduce

I'm not sure of the exact steps to reproduce. I have a site with a couple dozen view references where table paragraph__field_views_display has NULL for the field_views_display_data column, all of which throw the above error when displayed. I suspect that this was once more of an optional field, and some subsequent change resulted in a more consistent value. Simple re-saving the problematic paragraphs causes serialized data to be added to the field and the deprecation error to go away. But the error will persist for all views reference fields that continue to have a NULL 'data' field.

The field definition reads 'Settings data for advanced use', which implies this is an optional field, so a NULL value is valid and the unserialize() function should anticipate that this is sometimes the case, even if going forward all views reference fields should be expected to have a value.

Proposed resolution

Avoid calling unserialize() with a null value, which is deprecated as of PHP 8.1. Two options are possible:

  1. Use the PHP null coalescing operator to send an empty string to unseralize():
    'data' => unserialize($item->getValue()['data'] ?? '', ['allowed_classes' => FALSE]),
  2. Check for a null value and only call unserialize() if a value exists:
    'data' => !empty($item->getValue()['data']) ? unserialize($item->getValue()['data'], ['allowed_classes' => FALSE]): [],

Based on the precedence in ViewsReferenceItem::setValue(), I propose the latter/second option.

Remaining tasks

Confirm optimal approach to possibly-null 'data' property.

User interface changes

None.

API changes

None.

Data model changes

None.

πŸ› Bug report
Status

Fixed

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States daletrexel Minnesota, USA

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024