Skip to content

Commit 5406e5d

Browse files
authored
Fix #19766: Add support for PHP generators to JSON helper
1 parent 51208fc commit 5406e5d

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

framework/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Yii Framework 2 Change Log
44
2.0.48 under development
55
------------------------
66

7+
- Enh #19766: Add support for PHP generators to JSON helper (vladis84)
78
- Bug #19683: Updated `framework\mimeType.php` to the actual value. Fix typo in `build/controllers/MimeTypeController.php` (DeryabinSergey)
89
- Bug #19705: Add binary and other data type to `$typeMap` list for MySQL (sohelahmed7)
910
- Enh #19741: Added option to use a closure for `$variations` definition in `yii\filters\PageCache` (nadar)

framework/helpers/BaseJson.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,12 @@ protected static function processData($data, &$expressions, $expPrefix)
185185

186186
if ($data instanceof Arrayable) {
187187
$data = $data->toArray();
188+
} elseif ($data instanceof \Generator) {
189+
$_data = [];
190+
foreach ($data as $name => $value) {
191+
$_data[$name] = static::processData($value, $expressions, $expPrefix);
192+
}
193+
$data = $_data;
188194
} elseif ($data instanceof \SimpleXMLElement) {
189195
$data = (array) $data;
190196

tests/framework/helpers/JsonTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ public function testEncode()
9595
$data = new JsonModel();
9696
$data->data = (object) null;
9797
$this->assertSame('{}', Json::encode($data));
98+
99+
// Generator
100+
$data = function () {
101+
foreach (['a' => 1, 'b' => 2] as $name => $value) {
102+
yield $name => $value;
103+
}
104+
};
105+
106+
$this->assertSame('{"a":1,"b":2}', Json::encode($data()));
98107
}
99108

100109
public function testHtmlEncode()

0 commit comments

Comments
 (0)