Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty arrays aren't converted to Collections #810

Closed
ropi-bc opened this issue Jul 3, 2024 · 3 comments
Closed

Empty arrays aren't converted to Collections #810

ropi-bc opened this issue Jul 3, 2024 · 3 comments

Comments

@ropi-bc
Copy link

ropi-bc commented Jul 3, 2024

✏️ Describe the bug
While creating an instance of a DTO that has a collection, if the source had an empty array, the returning property will be an empty array, instead of an empty Collection, resulting in the error message: TestDTO::__construct(): Argument #1 ($items) must be of type Illuminate\Support\Collection, array given.

Line causing the issue

↪️ To Reproduce

class TestDTO extends Data
{
    public function __construct(
        /** @var Collection<int, string> $items */
        public readonly Collection $items
    ) {
    }
}

it('Empty array should return Collection too', function () {
    // Throws the above mentioned error
    $result = TestDTO::from(['items' => []]);
    expect($result->items)->toBeEmpty();
});

✅ Expected behavior
I expect the test to complete, and the expectations to be satisfied.

🖥️ Versions

Laravel: 11.4
Laravel Data: 4.5.0
PHP: 8.3

@inxilpro
Copy link

inxilpro commented Jul 5, 2024

We're running into the same issue. It looks like when the Enumerable cast was removed in #686 it broke casting empty arrays to empty collections. In the short term, we're able to add #[WithCast(EnumerableCast::class)] to force it, but the class is marked as deprecated and it seems like that's not a great long-term solution.

The main problem is that if you're relying on Laravel-Data within another package, you can't rely on cast_and_transform_iterables to be enabled, but now you also can't rely on the Enumerable cast to be enabled either.

The easiest solution, as far as I can tell, is to re-enable the Enumerable cast for now (until the next major version release), and add a comment next to the cast_and_transform_iterables config explaining that the cast should be disabled if that feature is turned on.

@rubenvanassche
Copy link
Member

The issue here is not that we've removed Enumerable but a bug in the new implementation, it should be cast into a Collection and not be kept as an array.

Fixed in next release (108e660)

@ropi-bc
Copy link
Author

ropi-bc commented Nov 21, 2024

Thank you, this is great news!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants