<?php


namespace AutoAdmin\Bundle\Content\DependencyInjection\Traits;


use AutoAdmin\Bundle\Content\Doctrine\Repository\ContainerRepositoryFactory;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

trait RegisterRepositoriesTrait
{
    function reRegisterRepositories(ContainerBuilder $container): void
    {
        // reset doctrine repositories with our default repositories
        // code from \Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass::process
        $def = $container->getDefinition($defId = 'doctrine.orm.container_repository_factory');
        $repoServiceIds = array_keys(
            $container->findTaggedServiceIds(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG)
        );
        $repoReferences = array_map(
            static function ($id) {
                return new Reference($id);
            },
            $repoServiceIds
        );
        $ref = ServiceLocatorTagPass::register($container, array_combine($repoServiceIds, $repoReferences));
        $def->replaceArgument(0, $ref);

        // override class
        $def->setClass(ContainerRepositoryFactory::class);

//        $container->setDefinition($defId, $def);
    }
}
