From 0ba9c619c763ca70af31ac94a214ac832130387e Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Thu, 9 Jan 2020 18:52:48 +0300 Subject: [PATCH] Fix #17760: Fix `JSON::encode()` for `\DateTimeInterface` under PHP 7.4 --- framework/CHANGELOG.md | 1 + framework/helpers/BaseJson.php | 12 ++++++++++-- tests/framework/helpers/JsonTest.php | 10 ++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index aae8789..9be8159 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -9,6 +9,7 @@ Yii Framework 2 Change Log - Bug #17762: PHP 7.4: Remove special condition for converting PHP errors to exceptions if they occurred inside of `__toString()` call (rob006) - Bug #17771: migrate/fresh was not returning exit code (samdark) - Bug #17767: Make `Formatter::formatNumber` method protected (TheCodeholic) +- Bug #17760: Fix `JSON::encode()` for `\DateTimeInterface` under PHP 7.4 (samdark) 2.0.31 December 18, 2019 diff --git a/framework/helpers/BaseJson.php b/framework/helpers/BaseJson.php index 7986fd4..0e3663e 100644 --- a/framework/helpers/BaseJson.php +++ b/framework/helpers/BaseJson.php @@ -151,9 +151,17 @@ class BaseJson $expressions['"' . $token . '"'] = $data->expression; return $token; - } elseif ($data instanceof \JsonSerializable) { + } + + if ($data instanceof \JsonSerializable) { return static::processData($data->jsonSerialize(), $expressions, $expPrefix); - } elseif ($data instanceof Arrayable) { + } + + if ($data instanceof \DateTimeInterface) { + return static::processData((array)$data, $expressions, $expPrefix); + } + + if ($data instanceof Arrayable) { $data = $data->toArray(); } elseif ($data instanceof \SimpleXMLElement) { $data = (array) $data; diff --git a/tests/framework/helpers/JsonTest.php b/tests/framework/helpers/JsonTest.php index 3952788..785b093 100644 --- a/tests/framework/helpers/JsonTest.php +++ b/tests/framework/helpers/JsonTest.php @@ -220,6 +220,16 @@ class JsonTest extends TestCase $expectedHtml = '["Error message. Here are some chars: < >","Error message. Here are even more chars: \"\""]'; $this->assertEquals($expectedHtml, Json::errorSummary($model, $options)); } + + /** + * @link https://github.com/yiisoft/yii2/issues/17760 + */ + public function testEncodeDateTime() + { + $input = new \DateTime('October 12, 2014', new \DateTimeZone('UTC')); + $output = Json::encode($input); + $this->assertEquals('{"date":"2014-10-12 00:00:00.000000","timezone_type":3,"timezone":"UTC"}', $output); + } } class JsonModel extends DynamicModel implements \JsonSerializable