getMethodCalls example

$loader->load('services6.yml');
        $services = $container->getDefinitions();
        $this->assertArrayHasKey('foo', $services, '->load() parses service elements');
        $this->assertFalse($services['not_shared']->isShared(), '->load() parses the shared flag');
        $this->assertInstanceOf(Definition::class$services['foo'], '->load() converts service element to Definition instances');
        $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
        $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
        $this->assertEquals(['foo', new Reference('foo')[true, false]]$services['arguments']->getArguments(), '->load() parses the argument tags');
        $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals([new Reference('baz'), 'configure']$services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(['BazClass', 'configureStatic']$services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals([['setBar', []]['setBar', []]['setBar', [new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')]]]$services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertEquals([['setBar', ['foo', new Reference('foo')[true, false]]]]$services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
        $this->assertEquals([new Reference('baz'), 'getClass']$services['new_factory2']->getFactory(), '->load() parses the factory tag');
        $this->assertEquals(['BazClass', 'getInstance']$services['new_factory3']->getFactory(), '->load() parses the factory tag');
        $this->assertSame([null, 'getInstance']$services['new_factory4']->getFactory(), '->load() accepts factory tag without class');
        $this->assertEquals([new Reference('baz'), '__invoke']$services['new_factory5']->getFactory(), '->load() accepts service reference as invokable factory');
        $this->assertEquals(['foo', new Reference('baz')]$services['Acme\WithShortCutArgs']->getArguments(), '->load() parses short service definition');

        $aliases = $container->getAliases();
        $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses aliases');
        $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
        

        }

        if (ServiceLocator::class === $value->getClass()) {
            return parent::processValue($value$isRoot);
        }

        if ($constructor = $this->getConstructor($value, false)) {
            $this->checkTypeDeclarations($value$constructor$value->getArguments());
        }

        foreach ($value->getMethodCalls() as $methodCall) {
            try {
                $reflectionMethod = $this->getReflectionMethod($value$methodCall[0]);
            } catch (RuntimeException $e) {
                if ($value->getFactory()) {
                    continue;
                }

                throw $e;
            }

            $this->checkTypeDeclarations($value$reflectionMethod$methodCall[1]);
        }
$container = new ContainerBuilder();
        $profilerDefinition = $container->register('profiler', 'ProfilerClass');
        $container->register('my_collector_service')
            ->addTag('data_collector', ['template' => 'foo', 'id' => 'my_collector']);

        $profilerPass = new ProfilerPass();
        $profilerPass->process($container);

        $this->assertSame(['my_collector_service' => ['my_collector', 'foo']]$container->getParameter('data_collector.templates'));

        // grab the method calls off of the "profiler" definition         $methodCalls = $profilerDefinition->getMethodCalls();
        $this->assertCount(1, $methodCalls);
        $this->assertEquals('add', $methodCalls[0][0]); // grab the method part of the first call     }

    public static function provideValidCollectorWithTemplateUsingAutoconfigure(): \Generator
    {
        yield [new class() implements TemplateAwareDataCollectorInterface {
            public function collect(Request $request, Response $response, \Throwable $exception = null): void
            {
            }

            
$service->appendChild($file);
        }

        if ($parameters = $definition->getArguments()) {
            $this->convertParameters($parameters, 'argument', $service);
        }

        if ($parameters = $definition->getProperties()) {
            $this->convertParameters($parameters, 'property', $service, 'name');
        }

        $this->addMethodCalls($definition->getMethodCalls()$service);

        if ($callable = $definition->getFactory()) {
            if (\is_array($callable) && ['Closure', 'fromCallable'] !== $callable && $definition->getClass() === $callable[0]) {
                $service->setAttribute('constructor', $callable[1]);
            } else {
                $factory = $this->document->createElement('factory');

                if (\is_array($callable) && $callable[0] instanceof Definition) {
                    $this->addService($callable[0], null, $factory);
                    $factory->setAttribute('method', $callable[1]);
                } elseif (\is_array($callable)) {
                    
protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof AbstractArgument && $value->getText().'.' === $value->getTextWithContext()) {
            $value->setContext(sprintf('A value found in service "%s"', $this->currentId));
        }

        if (!$value instanceof Definition) {
            return parent::processValue($value$isRoot);
        }

        $calls = $value->getMethodCalls();
        $calls[] = ['__construct', $value->getArguments()];

        foreach ($calls as $i => $call) {
            [$method$arguments] = $call;
            $parameters = null;
            $resolvedKeys = [];
            $resolvedArguments = [];

            foreach ($arguments as $key => $argument) {
                if ($argument instanceof AbstractArgument && $argument->getText().'.' === $argument->getTextWithContext()) {
                    $argument->setContext(sprintf('Argument '.(\is_int($key) ? 1 + $key : '"%3$s"').' of '.('__construct' === $method ? 'service "%s"' : 'method call "%s::%s()"')$this->currentId, $method$key));
                }
public function testProcessing(): void
    {
        $container = new ContainerBuilder();
        $container->register(MigrationSource::class D '.core.V6_3', MigrationSource::class)->setPublic(true);
        $container->register(MigrationSource::class D '.core.V6_4', MigrationSource::class)->setPublic(true);
        $container->register(MigrationSource::class D '.core.V6_5', MigrationSource::class)->setPublic(true);
        $container->register(MigrationSource::class D '.core.V6_6', MigrationSource::class)->setPublic(true);

        $container->addCompilerPass(new FrameworkMigrationReplacementCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0);
        $container->compile(false);

        $calls = $container->getDefinition(MigrationSource::class D '.core.V6_3')->getMethodCalls();
        static::assertCount(1, $calls);

        static::assertSame('addDirectory', $calls[0][0]);
        static::assertStringContainsString('Migration/V6_3', $calls[0][1][0]);
        static::assertSame('Shopware\Core\Migration\V6_3', $calls[0][1][1]);
    }
}
return;
        }

        $collectorDefinition = $container->getDefinition('data_collector.cache');
        $recorder = new Definition(is_subclass_of($definition->getClass(), TagAwareAdapterInterface::class) ? TraceableTagAwareAdapter::class D TraceableAdapter::class);
        $recorder->setTags($definition->getTags());
        if (!$definition->isPublic() || !$definition->isPrivate()) {
            $recorder->setPublic($definition->isPublic());
        }
        $recorder->setArguments([new Reference($innerId = $id.'.recorder_inner')]);

        foreach ($definition->getMethodCalls() as [$method$args]) {
            if ('setCallbackWrapper' !== $method || !$args[0] instanceof Definition || !($args[0]->getArguments()[2] ?? null) instanceof Definition) {
                continue;
            }
            if ([new Reference($id), 'setCallbackWrapper'] == $args[0]->getArguments()[2]->getFactory()) {
                $args[0]->getArguments()[2]->setFactory([new Reference($innerId), 'setCallbackWrapper']);
            }
        }

        $definition->setTags([]);
        $definition->setPublic(false);

        
if ($this->isArgumentMissingService($argument$container)) {
            $container->removeDefinition($key);
            $container->log($thissprintf('Removed service "%s"; reason: depends on non-existent service "%s".', $key(string) $argument));
            $has_changed = TRUE;
            $process_aliases = TRUE;
            // Process the next definition.             continue 2;
          }
        }

        // Ensure all the method call arguments are valid.         foreach ($definition->getMethodCalls() as $call) {
          foreach ($call[1] as $argument) {
            if ($this->isArgumentMissingService($argument$container)) {
              $container->removeDefinition($key);
              $container->log($thissprintf('Removed service "%s"; reason: method call "%s" depends on non-existent service "%s".', $key$call[0](string) $argument));
              $has_changed = TRUE;
              $process_aliases = TRUE;
              // Process the next definition.               continue 3;
            }
          }
        }
      }
throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
            }

            $factory = new Expression(substr($factory, 2));
        }
        $this->processValue($factory);
        $this->byFactory = $byFactory;

        $this->processValue($value->getArguments());

        $properties = $value->getProperties();
        $setters = $value->getMethodCalls();

        // Any references before a "wither" are part of the constructor-instantiation graph         $lastWitherIndex = null;
        foreach ($setters as $k => $call) {
            if ($call[2] ?? false) {
                $lastWitherIndex = $k;
            }
        }

        if (null !== $lastWitherIndex) {
            $this->processValue($properties);
            
$container
            ->register('php', TagAwareAdapter::class)
            ->addArgument(new Reference('.php.inner'));

        $collector = $container->register('data_collector.cache', CacheDataCollector::class);
        (new CacheCollectorPass())->process($container);

        $this->assertEquals([
            ['addInstance', ['fs', new Reference('fs')]],
            ['addInstance', ['tagged_fs', new Reference('tagged_fs')]],
            ['addInstance', ['php', new Reference('.php.inner')]],
        ]$collector->getMethodCalls());

        $this->assertSame(TraceableAdapter::class$container->findDefinition('fs')->getClass());
        $this->assertSame(TraceableTagAwareAdapter::class$container->getDefinition('tagged_fs')->getClass());

        $this->assertSame(TraceableAdapter::class$container->findDefinition('.php.inner')->getClass());
        $this->assertSame(TagAwareAdapter::class$container->getDefinition('php')->getClass());

        $this->assertFalse($collector->isPublic(), 'The "data_collector.cache" should be private after processing');

        $innerFs = $container->getDefinition('fs.recorder_inner');
        $this->assertEquals([new Reference('fs.recorder_inner'), 'setCallbackWrapper']$innerFs->getMethodCalls()[0][1][0]->getArgument(2)->getFactory());
    }
$service['arguments'] = $this->dumpCollection($arguments);
      $service['arguments_count'] = count($arguments);
    }
    else {
      $service['arguments_count'] = 0;
    }

    if ($definition->getProperties()) {
      $service['properties'] = $this->dumpCollection($definition->getProperties());
    }

    if ($definition->getMethodCalls()) {
      $service['calls'] = $this->dumpMethodCalls($definition->getMethodCalls());
    }

    // By default services are shared, so just provide the flag, when needed.     if ($definition->isShared() === FALSE) {
      $service['shared'] = $definition->isShared();
    }

    if ($definition->getDecoratedService() !== NULL) {
      throw new InvalidArgumentException("The 'decorated' definition is not supported by the Drupal run-time container. The Container Builder should have resolved that during the DecoratorServicePass compiler pass.");
    }

    
$def = new Definition('stdClass');
        $this->assertSame($def$def->setArguments(['foo']), '->setArguments() implements a fluent interface');
        $this->assertEquals(['foo']$def->getArguments(), '->getArguments() returns the arguments');
        $this->assertSame($def$def->addArgument('bar'), '->addArgument() implements a fluent interface');
        $this->assertEquals(['foo', 'bar']$def->getArguments(), '->addArgument() adds an argument');
    }

    public function testMethodCalls()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def$def->setMethodCalls([['foo', ['foo']]]), '->setMethodCalls() implements a fluent interface');
        $this->assertEquals([['foo', ['foo']]]$def->getMethodCalls(), '->getMethodCalls() returns the methods to call');
        $this->assertSame($def$def->addMethodCall('bar', ['bar']), '->addMethodCall() implements a fluent interface');
        $this->assertEquals([['foo', ['foo']]['bar', ['bar']]]$def->getMethodCalls(), '->addMethodCall() adds a method to call');
        $this->assertSame($def$def->addMethodCall('foobar', ['foobar'], true), '->addMethodCall() implements a fluent interface with third parameter');
        $this->assertEquals([['foo', ['foo']]['bar', ['bar']]['foobar', ['foobar'], true]]$def->getMethodCalls(), '->addMethodCall() adds a method to call');
        $this->assertTrue($def->hasMethodCall('bar'), '->hasMethodCall() returns true if first argument is a method to call registered');
        $this->assertFalse($def->hasMethodCall('no_registered'), '->hasMethodCall() returns false if first argument is not a method to call registered');
        $this->assertSame($def$def->removeMethodCall('bar'), '->removeMethodCall() implements a fluent interface');
        $this->assertTrue($def->hasMethodCall('foobar'), '->hasMethodCall() returns true if first argument is a method to call registered');
        $this->assertSame($def$def->removeMethodCall('foobar'), '->removeMethodCall() implements a fluent interface');
        $this->assertEquals([['foo', ['foo']]]$def->getMethodCalls(), '->removeMethodCall() removes a method to call');
        $this->assertSame($def$def->setMethodCalls([['foobar', ['foobar'], true]]), '->setMethodCalls() implements a fluent interface with third parameter');
        
public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('routing.resolver', LoaderResolver::class);
        $container->register('loader1')->addTag('routing.loader');
        $container->register('loader2')->addTag('routing.loader');

        (new RoutingResolverPass())->process($container);

        $this->assertEquals(
            [['addLoader', [new Reference('loader1')]]['addLoader', [new Reference('loader2')]]],
            $container->getDefinition('routing.resolver')->getMethodCalls()
        );
    }
}
$container = new ContainerBuilder();

        $container->register('foo', TestServiceSubscriberChild::class)
            ->addMethodCall('setContainer', [new Reference(PsrContainerInterface::class)])
            ->addTag('container.service_subscriber')
        ;

        (new RegisterServiceSubscribersPass())->process($container);
        (new ResolveServiceSubscribersPass())->process($container);

        $foo = $container->getDefinition('foo');
        $locator = $container->getDefinition((string) $foo->getMethodCalls()[0][1][0]);

        $expected = [
            TestServiceSubscriberChild::class.'::invalidDefinition' => new ServiceClosureArgument(new TypedReference('Symfony\Component\DependencyInjection\Tests\Fixtures\InvalidDefinition', 'Symfony\Component\DependencyInjection\Tests\Fixtures\InvalidDefinition')),
            TestServiceSubscriberChild::class.'::testDefinition2' => new ServiceClosureArgument(new TypedReference(TestDefinition2::class, TestDefinition2::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)),
            TestServiceSubscriberChild::class.'::testDefinition4' => new ServiceClosureArgument(new TypedReference(TestDefinition3::class, TestDefinition3::class)),
            TestServiceSubscriberParent::class.'::testDefinition1' => new ServiceClosureArgument(new TypedReference(TestDefinition1::class, TestDefinition1::class)),
            'custom_name' => new ServiceClosureArgument(new TypedReference(TestDefinition3::class, TestDefinition3::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'custom_name')),
        ];

        $this->assertEquals($expected$container->getDefinition((string) $locator->getFactory()[0])->getArgument(0));
    }

    
$value = parent::processValue($value$isRoot);

        if (!$value instanceof Definition || !$value->isAutowired() || $value->isAbstract() || !$value->getClass()) {
            return $value;
        }
        if (!$reflectionClass = $this->container->getReflectionClass($value->getClass(), false)) {
            $this->container->log($thissprintf('Skipping service "%s": Class or interface "%s" cannot be loaded.', $this->currentId, $value->getClass()));

            return $value;
        }

        $this->methodCalls = $value->getMethodCalls();

        try {
            $constructor = $this->getConstructor($value, false);
        } catch (RuntimeException $e) {
            throw new AutowiringFailedException($this->currentId, $e->getMessage(), 0, $e);
        }

        if ($constructor) {
            array_unshift($this->methodCalls, [$constructor$value->getArguments()]);
        }

        
Home | Imprint | This part of the site doesn't use cookies.