php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Cannot serialize IntlTimeZone objects

Open drjayvee opened this issue 4 years ago • 7 comments

Description

The following code:

<?php
$tz = IntlTimeZone::createTimeZone('Europe/Amsterdam');
$tz = unserialize(serialize($tz));

var_export($tz->getId());

Resulted in this output:

false

But I expected this output instead:

'Europe/Amsterdam'

It looks like the implementation of __serialize is broken, as the string doesn't contain any object data:

echo serialize(IntlTimeZone::createTimeZone('Europe/Amsterdam'));
// outputs O:12:"IntlTimeZone":0:{}

PHP Version

PHP 7.4.27 (cli) (built: Dec 21 2021 21:31:45) ( NTS )

Operating System

No response

drjayvee avatar Jan 13 '22 10:01 drjayvee

It doesn't look like IntlTimeZone supports serialization.

https://3v4l.org/jnXqP#v8.1.1

$tz = IntlTimeZone::createTimeZone('Europe/Amsterdam');
var_dump(serialize($tz));
string(24) "O:12:"IntlTimeZone":0:{}"

But we could throw an error or at least emit some warning.

iluuu1994 avatar Jan 13 '22 11:01 iluuu1994

Would it be difficult to implement serialization? Or do you worry about backwards compatibility?

drjayvee avatar Jan 13 '22 11:01 drjayvee

@drjayvee I know nothing about intl so I'm not sure. Compatibility shouldn't be a concern.

iluuu1994 avatar Jan 13 '22 13:01 iluuu1994

Would it be difficult to implement serialization?

I don't think it would be difficult, but what is the use case? I assume that IntlTimezone is most often used with IntlCalendar and IntlDateFormatter, but neither of these properly supports (un)serialization. Other classes of the intl extension might exhibit the same behavior.

cmb69 avatar Jan 15 '22 13:01 cmb69

I was under the admittedly naive assumption that every class supports serialization, unless it's especially tricky.

Our particular use case is:

class LocaleConfiguration {
  public IntlTimeZone $timeZone = null;
  public string $locale = 'en-US';
  public int $firstWeekDay = 1;
  // etc
}

And then cache the user's configuration in their session, memory cache, or elsewhere.

The simple yet awkward workaround is

public function __serialize(): array {
  return [
    'timeZone'     => $this->timeZone->getID(),
    'locale'       => $this->locale,
    'firstWeekDay' => $this->firstWeekDay,
    // etc
  ];
}

// reverse for __unserialize()

drjayvee avatar Jan 17 '22 09:01 drjayvee

Okay, for this case being able to (un)serialize IntlTimeZone objects would make sense.

Note, though, that a lot of internal classes don't support (un)serialization.

cmb69 avatar Jan 17 '22 10:01 cmb69

Serialization of these objects will be disallowed as of PHP 8.2.0. PRs to properly support (un)serialization (of individual classes) are welcome!

cmb69 avatar Feb 17 '22 14:02 cmb69