Json and PHP serializers should throw exception on failure

Created on 13 February 2024, 8 months ago
Updated 17 September 2024, 11 days ago

Problem/Motivation

Currently the PhpSerialize and Json serialization classes do not provide indication of failure.

It is documented on the SerializationInterface API for \Drupal\Component\Serialization\Exception\InvalidDataTypeException to be thrown however neither implementation appears to to do so, as such errors are silently hidden which can lead to failure, The YAML serializer does raise exceptions on failure.

Setting as Critical per Priority as this can lead to Data Loss or Corruption.

Steps to reproduce

$serializer = \Drupal::service('serialization.json');
$data = $serializer->decode('s:8:"not json"');
var_dump($data); // NULL
$data= $serializer->decode('null');
var_dump($data); // NULL

Note: These serializers are part of the Base core install not part of the Serialization module.

Proposed resolution

  • Json: Use the JSON_THROW_ON_ERROR flag and catch \JsonException to raise \InvalidDataTypeException on both encode and decode. (Added PHP 7.3.0)
  • PHP: serialize() has no published fault scenario, unserialize() however will return FALSE on an error and set an error status. We can capture the FALSE and compare if the string matches a serialized FALSE, if not its a valid error. Inspired by discussions in ๐Ÿ› UserData only returns strings for scalar values Needs review

Sample versions of the above implementations with tests can be found in a contrib issue I'm working on.
https://git.drupalcode.org/issue/rabbitmq-3416009/-/commit/f12e4725e6110...

Remaining tasks

Patch

User interface changes

None

API changes

None

Data model changes

None

Release notes snippet

Json and PHP serilaizers will now detect faults and raise exception as indicated in the API specifications.

๐Ÿ› Bug report
Status

Needs work

Version

11.0 ๐Ÿ”ฅ

Component
Baseย  โ†’

Last updated 16 minutes ago

Created by

๐Ÿ‡บ๐Ÿ‡ธUnited States cmlara

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