thephpleague / fractal

Output complex, flexible, AJAX/RESTful data structures.

Home Page:fractal.thephpleague.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Parsing includes for nested tranformers

MylesKingsnorth opened this issue · comments

I'm trying to figure out how I can parse includes for nested transformers, given the scenario below:

I have a controller which sets my ArraySerializer, parses includes for the OrderTransformer and then creates the data:

$data = (new Manager())
    ->setSerializer(new ArraySerializer())
    ->parseIncludes('dispatches')
    ->createData(new Collection($orders, new OrderTransformer()));

Inside my order transformer I have the include dispatches which I'm parsing from the above:

class OrderTransformer
{
    protected $availableIncludes = [
        'dispatches',
    ];

    public function transform($order)
    {
        return [];
    }

    public function includeDispatches($order)
    {
        return $this->collection($order->getDispatches(), new DispatchesTransformer());
    }
}

However where I'm getting stuck is inside my DispatchesTransformer:

class DispatchesTransformer
{
    protected $availableIncludes = [
        'product',
    ];

    public function transform($order)
    {
        return [];
    }

    public function includeProduct()
    {
        // ...
    }
}

I have an available include product I'd like to use. I don't want to make this a default include. How can I use that include?

I have tried something like this from my controller:

->parseIncludes(['dispatches', 'product'])

@MylesKingsnorth01 is this the code as it is in your application?

If so, a guess might be that in DispatchesTransformer, you misspelled availableIncludes, which might be a blocker.

@MylesKingsnorth01 is this the code as it is in your application?

If so, a guess might be that in DispatchesTransformer, you misspelled availableIncludes, which might be a blocker.

It is something I wrote to replicate what I'm trying to achieve so the typo isn't in my application but thanks for the spot.

from the docs:


These includes can be nested with dot notation too, to include resources within other resources.

E.g: /books?include=author,publishers.somethingelse

Note: publishers will also be included with somethingelse nested under it. This is shorthand for publishers,publishers.somethingelse.

So it looks like dot notation gets you what you want. In your case, you would do something such as:

?includes=dispatches,dispatches.product

or

$data = (new Manager())
    ->setSerializer(new ArraySerializer())
    ->parseIncludes('dispatches', 'dispatches.products')
    ->createData(new Collection($orders, new OrderTransformer()));

Let me know if that doesn't work. I have to start working here in a moment but I can look more deeply afterwards.

Perfect, that is exactly what I'm looking for. Can't believe I overlooked that, thanks.