Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove 'data' attribute from Fractal Transformer result?

Tags:

php

I try this code (via Fractal) to get result:

public static function doIt($array, $transformer)
{
    $manager = new Manager();

    $serializer = new \League\Fractal\Serializer\ArraySerializer();
    $manager->setSerializer($serializer);

    if ($array instanceof Collection) {
        $resource = new FractalCollection($array, new $transformer);
    } else {
        $resource = new FractalItem($array, new $transformer);
    }

    return $manager->createData( $resource )->toArray();
}

As you look, I added

$serializer = new \League\Fractal\Serializer\ArraySerializer();
$manager->setSerializer($serializer);

to remove 'data' attribute from result array.

array:3 [▼
  "key" => 1
  "title" => "First Level Title"
  "childrens" => array:1 [▼
    "data" => array:16 [▼          ←-------- it need remove!
      0 => array:2 [▼
        "key" => 2
        "title" => "Children Title"
      ]
      1 => array:2 [▶]
      2 => array:2 [▶]
      3 => array:2 [▶]
    ]
  ]
]

It's well work, but only for first level of array. How to do, for this to work for all nested arrays?

like image 435
Stanislav Avatar asked Dec 27 '16 11:12

Stanislav


2 Answers

I solved this problem. You need create own Serializer extends of DataArraySerializer. It have three methods and in each of them need change return values to this:

use League\Fractal\Serializer\DataArraySerializer;

class Serializer extends DataArraySerializer
{
    /**
     * Serialize a collection.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function collection($resourceKey, array $data)
    {
        return $data;
    }

    /**
     * Serialize an item.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function item($resourceKey, array $data)
    {
        return $data;
    }

    /**
     * Serialize null resource.
     *
     * @return array
     */
    public function null()
    {
        return [];
    }

}

Now we just set this serializer to the Manager instance we use.

$manager = new Manager();

$manager->setSerializer(new Serializer());
like image 102
Stanislav Avatar answered Nov 16 '22 03:11

Stanislav


You can use current() method, I hope it will solve your problem.

Example:

return current($manager->createData( $resource )->toArray());
like image 39
Sethu Avatar answered Nov 16 '22 04:11

Sethu