Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony serializer type casting while deserializing

Let's say I have a class

class MyObj
{
    /** @var int */
    private $myProp;

    public function getMyProp(): int
    {
        return $this->myProp;
    }

    public function setMyProp(int $myProp): self
    {
        $this->myProp = $myProp;

        return $this;
    }
}

If I want to deserialize following

$body = '{"myProp": "4"}';
$myObj = $serializer->deserialize($body, MyObj::class, 'json');

I obviously get an error saying that the types do not match.

The type of the "myProp" attribute for class "MyObj" must be one of "int" ("string" given).

Can I configure the serializer to typecast those values?

like image 635
Brucie Alpha Avatar asked Feb 21 '20 11:02

Brucie Alpha


1 Answers

The ObjectNormalizer has an option to disable type enforcement when denormalizing which you can pass via the context parameter.

# ... 
$myObj = $serializer->deserialize(
    $body,
    MyObj::class,
    'json',
    ['disable_type_enforcement' => true]
);
# ...

Since you are using a type hint in your setter, php will try to convert the given value to int.

like image 166
Niko Hadouken Avatar answered Sep 26 '22 18:09

Niko Hadouken