eronn
eronn

Reputation: 1830

unserialize() Please specify classes allowed for unserialization in 2nd argument

In my Symfony application I have a User entity which is serialized. In the unserialize() method, I did this:

    public function unserialize($serialized)
    {
        [
            $this->id,
            $this->email,
            $this->password,
            $this->enabled
        ] = unserialize($serialized);
    }

But PhpStorm underlines in red unserialize($serialized) with the following message:

Please specify classes allowed for unserialization in 2nd argument.

I don't know what I'm supposed to use as a second argument. After some research, I saw that we could put this:

unserialize($serializeObj, ["allowed_classes" => true]);

But I also found this:

unserialize(
    $serializedData,
    ['allowed_classes' => ['Class1', 'Class2']]
);

I'm a little confused, I don't know what I should put in my case so that PhpStorm doesn't complain about this.

Upvotes: 4

Views: 4098

Answers (1)

yivi
yivi

Reputation: 47318

If you are actually serializing an array, and not a class instance, you just need to pass false as allowed classes.

 public function unserialize($serialized)
{
        [
            $this->id,
            $this->email,
            $this->password,
            $this->enabled
        ] = unserialize($serialized, ['allowed_classes' => false]);
}

If you are serializing the whole entity, you need to pass the class you expect to be instantiated from the unserialization

So let's assume the class is App\Entity\User,

public function unserialize($serialized) {

    $new = unserialize($serialized, ['allowed_classes' => [ User::class ]]);
    $this->id       = $new->getId();
    $this->$email   = $new->getEmail();
    $this->password = $new->getPassword();
    $this->enabled  = $new->isEnabled();

}

I'm assuming you have have getter methods in the entity for the sake of simplicity.

Upvotes: 7

Related Questions