<?php

namespace AutoAdmin\Bundle\BrickBuilder\Helper;

use Doctrine\ORM\EntityManagerInterface;
use Exception;

class DatabaseBrickFormat
{
    public function __construct(
        protected EntityManagerInterface $em,
    )
    {
    }

    public function objectToString(?object $object): ?string
    {
        if (is_null($object) || empty($object->getId())) {
            return null;
        }

        return get_class($object) . '#' . $object->getId();
    }

    public function stringToObject(?string $stringObject): ?object
    {
        if (is_null($stringObject)) {
            return null;
        }

        [$class, $identifier] = explode('#', $stringObject);
        if (empty($class)) {
            throw new Exception('Could not extract class and identifier from "' . $stringObject . '"');
        }
        $repo = $this->em->getRepository($class);

        return $repo->find($identifier);
    }
}
