json_encode 仅适用于带有自定义 toArray 的模型的 JSON_PARTIAL_OUTPUT_ON_ERROR

json_encode only works with JSON_PARTIAL_OUTPUT_ON_ERROR for Model with custom toArray

我有一个 Eloquent 模型,为此我创建了一个自定义 toArray() 方法,以包含元 table 中的字段(我使用 eloquent-meta 插件):

class User extends Model{

    // ... Other stuff
    public function toArray(){
        return array_merge(parent::toArray(), $this->getAllMeta()->toArray());
    }
}

当我现在尝试使用 Response::json(...) 将此模型作为 JSON 响应发送时,我得到:

UnexpectedValueException in Response.php line 403: The Response content must be a string or object implementing __toString(), "boolean" given.

我已将错误追溯到 JsonResponse.setData($data)-method,其中 json_encode-call returns 错误。 json_last_error()-方法returnsJSON_ERROR_SYNTAXjson_last_error_msg()-方法returnsSyntax error.

使用调试器,我在下面的行上停止并自己评估了语句。正如预期的那样,它不起作用,但是如果我这样调用它,它就会起作用:

json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);

这 returns 我期望的完整、有效 JSON,没有任何缺失值或 NULL 值。

更奇怪的是,如果我在 toArray() 方法中停止并将合并的数组提供给 json_encode,它工作正常,即使没有部分。

我是不是忽略了一些明显的东西??

问题出在 eloquent-meta plugin I used. Here's the relevant part from my issue:

I traced the error back to the Helpers.maybeDecode($value)-method:

The current implementation tries to parse the value with json_decode($value) and checks, whether that worked, by checking the json_last_error()-function. The problem is, that this doesn't reset the last error.

When the Helpers.maybeDecode($value)-method is called, while Laravel is encoding the model, and the value it tried to decode was not an valid json (for example, a simple string), the error code is set, causing the json_encode()-function to see it and return null. The problem is with the global nature of the error-variable.

My proposed workaround for this is to reset the json_last_error()-function after checking if decoing worked, and the only way I have found to do this is by decoding something valid (even if it's just an empty array).

这是 Pull Request 的修复。