-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Open
Labels
Description
Problem description
In rest controller i have this method
public function actionTest() {
return ['test' => new MyModel()];
}
This return a empty array instead object
{
"test": []
}
expected
{
"a": {}
}
Possible solution
Apparently the problem is in the processData($data, &$expressions, $expPrefix) of BaseJson.php
In version 2.0.13 that I used, the if ($data === []) { return new \stdClass(); }
command was at the end, regardless of the type it was executed
if (is_object($data)) {
if ($data instanceof JsExpression) {
$token = "!{[$expPrefix=" . count($expressions) . ']}!';
$expressions['"' . $token . '"'] = $data->expression;
return $token;
} elseif ($data instanceof \JsonSerializable) {
return static::processData($data->jsonSerialize(), $expressions, $expPrefix);
} elseif ($data instanceof Arrayable) {
$data = $data->toArray();
} elseif ($data instanceof \SimpleXMLElement) {
$data = (array) $data;
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
In the most current versions it is replaced by
} else {
/*
* $data type is changed to array here and its elements will be processed further
* We must cast $data back to object later to keep intended dictionary type in JSON.
* Revert is only done when keepObjectType flag is provided to avoid breaking BC
*/
$revertToObject = static::$keepObjectType;
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
// Avoid empty objects to be returned as array (would break BC without keepObjectType flag)
if ($data === []) {
$revertToObject = true;
}
}
This way when $data
is an Arrayable it does not check if it is empty
Additional info
Yii version: 2.0.50
PHP version: 8.2
Operating system: Windows/Debian