Skip to content

ArrayShapeFromConstantArrayReturnRector breaks when casting array to object #8017

@gitomato

Description

@gitomato

I'm using a trick to serialize empty associative arrays in JSON.
For that purpose I cast the array into an object before serializing it.

Here is an oversimplified example:

<?php

final class Foo
{
    /**
     * @return array<string, stdClass>
     */
    public static function cleanup(?string $value): array
    {
        return [
            // Ensure empty metadata is serialized as `{}` and not `[]`
            'metadata' => (object) array_filter([
                'foo' => $value,
            ]),
        ];
    }
}

assert(json_encode(Foo::cleanup('c')) === '{"metadata":{"foo":"c"}}');
assert(json_encode(Foo::cleanup(null)) === '{"metadata":{}}');

It breaks the ArrayShapeFromConstantArrayReturnRector rule.

Here is the demo:
https://getrector.com/demo/ab809a74-239e-4b46-af98-b33a60643aa3

PS: Thanks for your amazing tool!

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