Skip to content

Empty Object will be converted to empty array #86

@tsaiyihua

Description

@tsaiyihua

Hello,

I discover that while my object is empty, and with the N+1 report for JsonResponse, my empty object will be converted to empty array.
In my production with debug is false will not be converted, this will be ok.
but in my development with debug is true, empty object will be converted to empty array, it's a problem.

example:

    public function index()
    {
        $chapters = Chapter::where('book_id',1)->get();
        $data = [];
        $chapters->each(function (Chapter $chapter) use (&$data) {
            $data['book_name'] = (string) $chapter->book->name;
            $data['empty_object'] = (object) [];
        });
        return response()->json($data);
    }

my expectation output is

{"book_name":"Sunt sit.","empty_object":{},"warning_queries":[...]}

but output is

{"book_name":"Sunt sit.","empty_object":[],"warning_queries":[...]}

In Json.php with namespace BeyondCode\QueryDetector\Outputs

    public function output(Collection $detectedQueries, Response $response)
    {
        if ($response instanceof JsonResponse) {
            $data = $response->getData(true);
            if (! is_array($data)){
                $data = [ $data ];
            }

            $data['warning_queries'] = $detectedQueries;
            $response->setData($data);
        }
    }

change to

    public function output(Collection $detectedQueries, Response $response)
    {
        if ($response instanceof JsonResponse) {
            $data = $response->getData();
            if (! is_array($data)){
                $data = [$data];
            }

            $data['warning_queries'] = $detectedQueries;
            $response->setData($data);
        }
    }

will get my expectation output.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions