DrupalDateTime serialization issue

Created on 7 December 2020, about 4 years ago
Updated 3 March 2024, 10 months ago

Problem/Motivation

When serializing DrupalDateTime object the following exception is thrown:

LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep() (line 1574 of web/core/lib/Drupal/Core/Database/Connection.php).

This is caused by formatTranslationCache property of the object. If there is another language selected than English, this property will contain references to stringTranslation service that it its turn can have database service references if you use locale module.

Steps to reproduce

PHP version: 7.3.24
Web Server: Apache
OS: Centos 7

1. Install Drupal 8.9.x
1a. Add language other than "English".
1b. Make sure that there are translations of months, days of the weeks in the database.
2. Install Commerce module 2.21
3. Install Commerce Shipping module.
4. Use delivery_date property of ShippingRate class. I am not aware of any contrib module that does it, but my custom shipping method provides rates that depend on date. The instance of this class is added to ShippingRates widget that is displayed on checkout form.
5. Install Commerce Promotion or Commerce GiftCard module, so that it is possible to run ajax callbacks on checkout for.
6. Get to the step where you can select the shipping rate and use the language other than English.
7. Try to add coupon/card code.
8. Observe the exception described in the "Problem Motivation".
9. Change to English language, try to do the same, everything should work as expected.

I guess there are easier steps to reproduce, like creating a form with ajax callback that has DrupalDateTime object for any form element.

Proposed resolution

Implement __sleep() method in DrupalDateTime class like:

  public function __sleep() {
    return ['langcode', 'dateTimeObject'];
  }

Remaining tasks

Write tests, make sure that no other properties of the class are needed in serialized version of the instance.

User interface changes

None

API changes

None

Data model changes

None

Release notes snippet

Not needed.

๐Ÿ› Bug report
Status

Fixed

Version

10.2 โœจ

Component
Otherย  โ†’

Last updated 2 days ago

Created by

๐Ÿ‡ฉ๐Ÿ‡ชGermany a.dmitriiev

Live updates comments and jobs are added and updated live.

Missing content requested by

๐Ÿ‡ฆ๐Ÿ‡บAustralia dpi
11 months ago
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024