use fractal to decode from array to custom PHP object

1.2k Views Asked by At

using League/fractal, i am attempting to transform data from array to my PHP object...in the following way

final class StatusDeserializer extends AbstractTransformer
{


    public function transform(Status $status)
    {
        return new StatusObject(
            $status['name'],
            $status['message']
        );
    }
}

my object definition

final class StatusObject
{

    private $name;
    private $message;

    public function __construct($name, $message)
    {
        $this->name = $name;
        $this->message = $message;
    }
}

test implementation here

$data = [ 'name' => 'foo', 'message' => 'bar' ]
$this->fractalManager->createData($data, new StatusDeserializer());

But i get this error

Fatal error: Uncaught TypeError: Argument 1 passed to League\Fractal\Scope::filterFieldsets() must be of the type array, object given

Edit 1

I tried wrapping the array into Fractals collection, i.e

$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);

and it now returns an instance of League\Fractal\Scope instead of my StatusObject instance

Edit 2

Adding ->toArray() brought me back to the first error

$this->fractalManager->createData($data, new StatusDeserializer())->toArray();

see screen shot : https://gmkr.io/s/5a0b755c683d0d77313ff0fa/0

1

There are 1 best solutions below

4
Philipp On

FractalManager wants an instance of ResourceInterface as first argument. So you just want to change your code like this

$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
$this->fractalManager->createData($data, new StatusDeserializer());