<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Form\DataTransformer;

use Chill\DocStoreBundle\Entity\StoredObject;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Serializer\SerializerInterface;

class StoredObjectDataTransformer implements DataTransformerInterface
{
    public function __construct(
        private readonly SerializerInterface $serializer,
    ) {}

    public function transform(mixed $value): mixed
    {
        if (null === $value) {
            return '';
        }

        if ($value instanceof StoredObject) {
            return $this->serializer->serialize($value, 'json');
        }

        throw new UnexpectedTypeException($value, StoredObject::class);
    }

    public function reverseTransform(mixed $value): mixed
    {
        if ('' === $value || null === $value) {
            return null;
        }

        return $this->serializer->deserialize($value, StoredObject::class, 'json');
    }
}
