Deserializing indexed array of object in Symfony

I need to deserialize indexed array of objects from YAML file. The problem is that symfony thinks it’s a bunch of objects in items, but it’s array with indexes and there will always be different names(indexes). I couldn’t find the answer in docs (pretty sure I am just overlooking).

Any tips please ?

YAML:

items:
  darkvoice:
    display_name: Dark Voice
    price: 100
  phone:
    display_name: Mobile phone
    price: 100

mapping

$encoders = [ new YamlEncoder() ];
$normalizers = [
    new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
];
$serializer = new Serializer($normalizers, $encoders);
$test = $serializer->deserialize(file_get_contents(__DIR__.'/example.yml'), ItemList::class, 'yaml');

classes

class ItemList {

    /** @var Singleton[] */
    private array $items = [];

    /**
     * @return Singleton[]
     */
    public function getItems(): array
    {
        return $this->items;
    }

    /**
     * @param Singleton[] $items
     * @return ItemList
     */
    public function setItems($items): self
    {
        $this->items = $items;
        return $this;
    }
}

class Singleton {

    private string $display_name;
    private int $price = 0;

    /**
     * @return string
     */
    public function getDisplayName(): string
    {
        return $this->display_name;
    }

    /**
     * @param string $display_name
     * @return Singleton
     */
    public function setDisplayName($display_name):self
    {
        $this->display_name = $display_name;
        return $this;
    }

    /**
     * @return int
     */
    public function getPrice(): int
    {
        return $this->price;
    }

    /**
     * @param int $price
     * @return Singleton
     */
    public function setPrice(int $price): Singleton
    {
        $this->price = $price;
        return $this;
    }
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *