Проход компилятора - разрешить целевой объект не загружается - PullRequest
0 голосов
/ 08 ноября 2018

Я работаю над комплектом, и мне нужно загрузить доктрину resol_target_entities из параметра конфигурации.

Эта статья должна быть моим решением, дело в том, что при использовании комплектаКажется, не загружается «класс прохода компилятора».

Это мой класс связки

class PersonalBundle extends Bundle
{
    public function build(ContainerBuilder $container){
        parent::build($container);
        $container->addCompilerPass(new ResolveTargetEntitiesPass());
    }
}

Это класс ResolveTargetEntitiesPass

class ResolveTargetEntitiesPass implements CompilerPassInterface
{

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        // Gets the custom entity defined by the user (or the default one)
        $customEntityClass = $container->getParameter('personal.custom_class');
        // Skip the resolve_target_entities part if user has not defined a different entity
        if (DefaultClassInterface::DEFAULT_ENTITY_CLASS == $customEntityClass) {
            return;
        }
        // Throws exception if the class isn't found
        if (!class_exists($customEntityClass)) {
            throw new ClassNotFoundException(sprintf("Can't find class %s ", $customEntityClass));
        }

        // Get the doctrine ResolveTargetEntityListener
        $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
        // Adds the resolve_target_enitity parameter
        $def->addMethodCall('addResolveTargetEntity', array(
            DefaultClassInterface::DEFAULT_ENTITY_CLASS, $customEntityClass, array()
        ));
        // This was added due this problem
        // https://stackoverflow.com/a/46656413/7070573
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0 && !$def->hasTag('doctrine.event_listener')) {
            $def->addTag('doctrine.event_listener', array('event' => 'loadClassMetadata'));
        } elseif (!$def->hasTag('doctrine.event_subscriber')) {
            $def->addTag('doctrine.event_subscriber');
        }
    }
}

Когда я использую классвозникает эта ошибка

Ожидаемое значение типа «PersonalBundle \ Entity \ DefaultClass» для поля связи «PersonalBundle \ Entity \ Group # $ defaultClass», вместо этого получено «App \ Entity \ CustomClass».

Как я уже сказал, похоже, что не загружается ResolveTargetEntitiesPass ... Спасибо

1 Ответ

0 голосов
/ 09 ноября 2018

Итак, я решил проблему с изменением приоритета прохода компилятора. Я попытался переместить пакет сверху в config/bundle.php, и он начал работать, затем следуя этому https://symfony.com/blog/new-in-symfony-3-2-compiler-passes-improvements, я оставил тип по умолчанию, но увеличил приоритет (с 0, по умолчанию, до 1). Я не уверен, какой сервис был "понижен", поэтому, если у кого-то есть идея, это приветствуется.

<?php
// ...
use Symfony\Component\DependencyInjection\Compiler\PassConfig;

class PersonalBundle extends Bundle
{
    public function build(ContainerBuilder $container){
        parent::build($container);
        $container->addCompilerPass(new ResolveTargetEntitiesPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1);
    }
}
...