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

Handle empty arrays passed to collections #26

Merged
merged 1 commit into from
Jul 21, 2017

Conversation

cviebrock
Copy link
Contributor

I was running into issues in my Laravel project using laravel-fractal with this code:

$items = [];
$fractal = fractal($items, $transformer, new ArraySerializer);

I traced it back to this line in fractalistic:

// src/Fractal.php

    public static function create($data = null, $transformer = null, $serializer = null)
    {
        $instance = new static(new Manager());

        $instance->data = $data ?: null;    // <--- HERE
        $instance->dataType = $instance->determineDataType($data);
        $instance->transformer = $transformer ?: null;
        $instance->serializer = $serializer ?: null;

        return $instance;
    }

If for whatever reason you end up passing an empty array as data, the ternary operator treats it as false, and $instance->data is set to null. Then $instance->dataType is set "collection" (since an array is passed to it). Eventually, this throws an exception:

Invalid argument supplied for foreach() /home/admin/domains/www.wareable.local/vendor/league/fractal/src/Scope.php
line 317

because it is trying to foreach over null (i.e. not an array).

This PR (plus accompanying test) fixes it but not trying to do any transformation on the data that gets passed to Fractal::create().

@freekmurze freekmurze merged commit 5f2931d into spatie:master Jul 21, 2017
@freekmurze
Copy link
Member

Perfect little PR, thanks!

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

Successfully merging this pull request may close these issues.

None yet

2 participants