getCompiler example



        try {
            $container = null;
            $container = $this->buildContainer();
            $container->compile();
        } finally {
            if ($collectDeprecations) {
                restore_error_handler();

                @file_put_contents($buildDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
                @file_put_contents($buildDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
            }
        }

        $this->dumpContainer($cache$container$class$this->getContainerBaseClass());

        if ($lock) {
            flock($lock, \LOCK_UN);
            fclose($lock);
        }

        $this->container = require $cachePath;
        
/** * @dataProvider getTests */
    public function testCompile($node$source$environment = null, $isPattern = false)
    {
        $this->assertNodeCompilation($source$node$environment$isPattern);
    }

    public function assertNodeCompilation($source, Node $node, Environment $environment = null, $isPattern = false)
    {
        $compiler = $this->getCompiler($environment);
        $compiler->compile($node);

        if ($isPattern) {
            $this->assertStringMatchesFormat($sourcetrim($compiler->getSource()));
        } else {
            $this->assertEquals($sourcetrim($compiler->getSource()));
        }
    }

    protected function getCompiler(Environment $environment = null)
    {
        
$this->enableExpressionProcessing();
    }

    /** * Processes a ContainerBuilder object to populate the service reference graph. * * @return void */
    public function process(ContainerBuilder $container)
    {
        $this->container = $container;
        $this->graph = $container->getCompiler()->getServiceReferenceGraph();
        $this->graph->clear();
        $this->lazy = false;
        $this->byConstructor = false;
        $this->byFactory = false;
        $this->definitions = $container->getDefinitions();
        $this->aliases = $container->getAliases();

        foreach ($this->aliases as $id => $alias) {
            $targetId = $this->getDefinitionId((string) $alias);
            $this->graph->connect($id$alias$targetId, null !== $targetId ? $this->container->getDefinition($targetId) : null, null);
        }

        
private function getProxyDumper(): DumperInterface
    {
        return $this->proxyDumper ??= new LazyServiceDumper($this->class);
    }

    private function analyzeReferences(): void
    {
        (new AnalyzeServiceReferencesPass(false, $this->hasProxyDumper))->process($this->container);
        $checkedNodes = [];
        $this->circularReferences = [];
        $this->singleUsePrivateIds = [];
        foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) {
            if (!$node->getValue() instanceof Definition) {
                continue;
            }

            if ($this->isSingleUsePrivateNode($node)) {
                $this->singleUsePrivateIds[$id] = $id;
            }

            $this->collectCircularReferences($id$node->getOutEdges()$checkedNodes);
        }

        
protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if (!$value instanceof Reference) {
            return parent::processValue($value$isRoot);
        }
        if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $value->getInvalidBehavior() || $this->container->has($id = (string) $value)) {
            return $value;
        }

        $currentId = $this->currentId;
        $graph = $this->container->getCompiler()->getServiceReferenceGraph();

        if (isset($this->serviceLocatorContextIds[$currentId])) {
            $currentId = $this->serviceLocatorContextIds[$currentId];
            $locator = $this->container->getDefinition($this->currentId)->getFactory()[0];

            foreach ($locator->getArgument(0) as $k => $v) {
                if ($v->getValues()[0] === $value) {
                    if ($k !== $id) {
                        $currentId = $k.'" in the container provided to "'.$currentId;
                    }
                    throw new ServiceNotFoundException($id$currentId, null, $this->getAlternatives($id));
                }
$analyzedContainer = $container;
        }
        try {
            $notInlinableIds = [];
            $remainingInlinedIds = [];
            $this->connectedIds = $this->notInlinedIds = $container->getDefinitions();
            do {
                if ($this->analyzingPass) {
                    $analyzedContainer->setDefinitions(array_intersect_key($analyzedContainer->getDefinitions()$this->connectedIds));
                    $this->analyzingPass->process($analyzedContainer);
                }
                $this->graph = $analyzedContainer->getCompiler()->getServiceReferenceGraph();
                $notInlinedIds = $this->notInlinedIds;
                $notInlinableIds += $this->notInlinableIds;
                $this->connectedIds = $this->notInlinedIds = $this->inlinedIds = $this->notInlinableIds = [];

                foreach ($analyzedContainer->getDefinitions() as $id => $definition) {
                    if (!$this->graph->hasNode($id)) {
                        continue;
                    }
                    foreach ($this->graph->getNode($id)->getOutEdges() as $edge) {
                        if (isset($notInlinedIds[$edge->getSourceNode()->getId()])) {
                            $this->currentId = $id;
                            


        return $this->proxyDumper;
    }

    private function analyzeReferences()
    {
        (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container);
        $checkedNodes = [];
        $this->circularReferences = [];
        $this->singleUsePrivateIds = [];
        foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) {
            if (!$node->getValue() instanceof Definition) {
                continue;
            }

            if ($this->isSingleUsePrivateNode($node)) {
                $this->singleUsePrivateIds[$id] = $id;
            }

            $this->collectCircularReferences($id$node->getOutEdges()$checkedNodes);
        }

        
/** * Adds a compiler pass. * * @param string $type The type of compiler pass * @param int $priority Used to sort the passes * * @return $this */
    public function addCompilerPass(CompilerPassInterface $pass, string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION, int $priority = 0)static
    {
        $this->getCompiler()->addPass($pass$type$priority);

        $this->addObjectResource($pass);

        return $this;
    }

    /** * Returns the compiler pass config which can then be modified. */
    public function getCompilerPassConfig(): PassConfig
    {
        
$this->registerFunctions();
        foreach ($providers as $provider) {
            $this->registerProvider($provider);
        }
    }

    /** * Compiles an expression source code. */
    public function compile(Expression|string $expression, array $names = []): string
    {
        return $this->getCompiler()->compile($this->parse($expression$names)->getNodes())->getSource();
    }

    /** * Evaluate an expression. */
    public function evaluate(Expression|string $expression, array $values = []): mixed
    {
        return $this->parse($expressionarray_keys($values))->getNodes()->evaluate($this->functions, $values);
    }

    /** * Parses an expression. */

    private array $currentPath;
    private array $checkedNodes;

    /** * Checks the ContainerBuilder object for circular references. * * @return void */
    public function process(ContainerBuilder $container)
    {
        $graph = $container->getCompiler()->getServiceReferenceGraph();

        $this->checkedNodes = [];
        foreach ($graph->getNodes() as $id => $node) {
            $this->currentPath = [$id];

            $this->checkOutEdges($node->getOutEdges());
        }
    }

    /** * Checks for circular references. * * @param ServiceReferenceGraphEdge[] $edges An array of Edges * * @throws ServiceCircularReferenceException when a circular reference is found */
protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if (!$value instanceof Reference) {
            return parent::processValue($value$isRoot);
        }
        if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $value->getInvalidBehavior() || $this->container->has($id = (string) $value)) {
            return $value;
        }

        $currentId = $this->currentId;
        $graph = $this->container->getCompiler()->getServiceReferenceGraph();

        if (isset($this->serviceLocatorContextIds[$currentId])) {
            $currentId = $this->serviceLocatorContextIds[$currentId];
            $locator = $this->container->getDefinition($this->currentId)->getFactory()[0];

            foreach ($locator->getArgument(0) as $k => $v) {
                if ($v->getValues()[0] === $value) {
                    if ($k !== $id) {
                        $currentId = $k.'" in the container provided to "'.$currentId;
                    }
                    throw new ServiceNotFoundException($id$currentId, null, $this->getAlternatives($id));
                }
$aliased->addMethodCall('setBar', [new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]);
        $builder->setDefinition('aliased', $aliased);
        $builder->setAlias('alias', 'aliased');

        $this->assertEquals(new \stdClass()$builder->get('alias'));
    }

    public function testAddGetCompilerPass()
    {
        $builder = new ContainerBuilder();
        $builder->setResourceTracking(false);
        $defaultPasses = $builder->getCompiler()->getPassConfig()->getPasses();
        $builder->addCompilerPass($pass1 = $this->createMock(CompilerPassInterface::class), PassConfig::TYPE_BEFORE_OPTIMIZATION, -5);
        $builder->addCompilerPass($pass2 = $this->createMock(CompilerPassInterface::class), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10);

        $passes = $builder->getCompiler()->getPassConfig()->getPasses();
        $this->assertCount(\count($passes) - 2, $defaultPasses);
        // Pass 1 is executed later         $this->assertTrue(array_search($pass1$passes, true) > array_search($pass2$passes, true));
    }

    public function testCreateService()
    {
        
default => throw new InvalidArgumentException(sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))),
        };
    }

    private function compileContainer(): ContainerBuilder
    {
        $kernel = clone $this->getApplication()->getKernel();
        $kernel->boot();

        $method = new \ReflectionMethod($kernel, 'buildContainer');
        $container = $method->invoke($kernel);
        $container->getCompiler()->compile($container);

        return $container;
    }

    /** * Iterate over configuration until the last step of the given path. * * @throws LogicException If the configuration does not exist */
    private function getConfigForPath(array $config, string $path, string $alias): mixed
    {
        

        $pass = new UnusedTagsPass();

        $container = new ContainerBuilder();
        $container->register('foo')
            ->addTag('kenrel.event_subscriber');
        $container->register('bar')
            ->addTag('kenrel.event_subscriber');

        $pass->process($container);

        $this->assertSame([sprintf('%s: Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?', UnusedTagsPass::class)]$container->getCompiler()->getLog());
    }

    public function testMissingKnownTags()
    {
        if (\dirname((new \ReflectionClass(ContainerBuilder::class))->getFileName(), 3) !== \dirname(__DIR__, 5)) {
            $this->markTestSkipped('Tests are not run from the root symfony/symfony metapackage.');
        }

        $this->assertSame(UnusedTagsPassUtils::getDefinedTags()$this->getKnownTags(), 'The src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php file must be updated; run src/Symfony/Bundle/FrameworkBundle/Resources/bin/check-unused-known-tags.php.');
    }

    
/** * Adds a compiler pass. * * @param string $type The type of compiler pass * @param int $priority Used to sort the passes * * @return $this */
    public function addCompilerPass(CompilerPassInterface $pass, string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION, int $priority = 0)static
    {
        $this->getCompiler()->addPass($pass$type$priority);

        $this->addObjectResource($pass);

        return $this;
    }

    /** * Returns the compiler pass config which can then be modified. */
    public function getCompilerPassConfig(): PassConfig
    {
        
Home | Imprint | This part of the site doesn't use cookies.