addMethodCall example

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class ConfigureApiResourcesPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        foreach ($container->findTaggedServiceIds('shopware.api_resource') as $id => $options) {
            $definition = $container->getDefinition($id);
            $definition->addMethodCall('setContainer', [new Reference('service_container')]);
            $definition->addMethodCall('setManager', [new Reference('models')]);
        }
    }
}
class ResolveInvalidReferencesPassTest extends TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $def = $container
            ->register('foo')
            ->setArguments([
                new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE),
                new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),
            ])
            ->addMethodCall('foo', [new Reference('moo', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)])
        ;

        $this->process($container);

        $arguments = $def->getArguments();
        $this->assertSame([null, null]$arguments);
        $this->assertCount(0, $def->getMethodCalls());
    }

    public function testProcessIgnoreInvalidArgumentInCollectionArgument()
    {
        
public function process(ContainerBuilder $container)
    {
        if (!$this->enabled($container)) {
            return;
        }

        $mappingDriverDef = $this->getDriver($container);
        $chainDriverDefService = $this->getChainDriverServiceName($container);
        // Definition for a Doctrine\Persistence\Mapping\Driver\MappingDriverChain         $chainDriverDef = $container->getDefinition($chainDriverDefService);
        foreach ($this->namespaces as $namespace) {
            $chainDriverDef->addMethodCall('addDriver', [$mappingDriverDef$namespace]);
        }

        if (!\count($this->aliasMap)) {
            return;
        }

        $configurationServiceName = $this->getConfigurationServiceName($container);
        // Definition of the Doctrine\...\Configuration class specific to the Doctrine flavour.         $configurationServiceDefinition = $container->getDefinition($configurationServiceName);
        foreach ($this->aliasMap as $alias => $namespace) {
            $configurationServiceDefinition->addMethodCall($this->registerAliasMethodName, [$alias$namespace]);
        }
$container = new ContainerBuilder();
$container
    ->register('foo', FooClass::class)
    ->addTag('foo', ['foo' => 'foo'])
    ->addTag('foo', ['bar' => 'bar', 'baz' => 'baz'])
    ->addTag('nullable', ['bar' => 'bar', 'baz' => null])
    ->addTag('foo', ['name' => 'bar', 'baz' => 'baz'])
    ->setFactory(['Bar\\FooClass', 'getInstance'])
    ->setArguments(['foo', new Reference('foo.baz')['%foo%' => 'foo is %foo%', 'foobar' => '%foo%'], true, new Reference('service_container')])
    ->setProperties(['foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => ['%foo%' => 'foo is %foo%', 'foobar' => '%foo%']])
    ->addMethodCall('setBar', [new Reference('bar')])
    ->addMethodCall('initialize')
    ->setConfigurator('sc_configure')
    ->setPublic(true)
;
$container
    ->register('foo.baz', '%baz_class%')
    ->setFactory(['%baz_class%', 'getInstance'])
    ->setConfigurator(['%baz_class%', 'configureStatic1'])
    ->setPublic(true)
;
$container
    
// Add the 'workspace' cache context as required.     $renderer_config = $container->getParameter('renderer.config');
    $renderer_config['required_cache_contexts'][] = 'workspace';
    $container->setParameter('renderer.config', $renderer_config);

    // Replace the class of the 'path_alias.repository' service.     if ($container->hasDefinition('path_alias.repository')) {
      $definition = $container->getDefinition('path_alias.repository');
      if (!$definition->isDeprecated()) {
        $definition
          ->setClass(WorkspacesAliasRepository::class)
          ->addMethodCall('setWorkspacesManager', [new Reference('workspaces.manager')]);
      }
    }

    // Ensure that there's no active workspace while running database updates by     // removing the relevant tag from all workspace negotiator services.     if ($container->get('kernel') instanceof UpdateKernel) {
      foreach ($container->getDefinitions() as $definition) {
        if ($definition->hasTag('workspace_negotiator')) {
          $definition->clearTag('workspace_negotiator');
        }
      }
    }
if (!$container->hasDefinition('translation.extractor')) {
            return;
        }

        $definition = $container->getDefinition('translation.extractor');

        foreach ($container->findTaggedServiceIds('translation.extractor', true) as $id => $attributes) {
            if (!isset($attributes[0]['alias'])) {
                throw new RuntimeException(sprintf('The alias for the tag "translation.extractor" of service "%s" must be set.', $id));
            }

            $definition->addMethodCall('addExtractor', [$attributes[0]['alias']new Reference($id)]);
        }
    }
}

        if (!$container->hasDefinition('data_collector.http_client')) {
            return;
        }

        foreach ($container->findTaggedServiceIds('http_client.client') as $id => $tags) {
            $container->register('.debug.'.$id, TraceableHttpClient::class)
                ->setArguments([new Reference('.debug.'.$id.'.inner')new Reference('debug.stopwatch', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)])
                ->addTag('kernel.reset', ['method' => 'reset'])
                ->setDecoratedService($id, null, 5);
            $container->getDefinition('data_collector.http_client')
                ->addMethodCall('registerClient', [$idnew Reference('.debug.'.$id)]);
        }
    }
}
if ($access['allow_if']) {
                $roles[] = $this->createExpression($container$access['allow_if']);
            }

            $emptyAccess = 0 === \count(array_filter($access));

            if ($emptyAccess) {
                throw new InvalidConfigurationException('One or more access control items are empty. Did you accidentally add lines only containing a "-" under "security.access_control"?');
            }

            $container->getDefinition('security.access_map')
                      ->addMethodCall('add', [$matcher$roles$access['requires_channel']]);
        }

        // allow cache warm-up for expressions         if (\count($this->expressions)) {
            $container->getDefinition('security.cache_warmer.expression')
                ->replaceArgument(0, new IteratorArgument(array_values($this->expressions)));
        } else {
            $container->removeDefinition('security.cache_warmer.expression');
        }
    }

    
if ('\\' === \DIRECTORY_SEPARATOR) {
            $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump);
        }
        $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_inlined_factories.txt', $dump);
    }

    public function testDumpAsFilesWithFactoriesInlinedWithTaggedIterator()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo', FooClass::class)
            ->addMethodCall('setOtherInstances', [new TaggedIteratorArgument('foo')])
            ->setShared(false)
            ->setPublic(true);

        $container
            ->register('Bar', 'Bar')
            ->addTag('foo');

        $container
            ->register('stdClass', '\stdClass')
            ->addTag('foo');

        
use Symfony\Component\DependencyInjection\ContainerBuilder;

#[Package('administration')] class AdministrationMigrationCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $migrationPath = \dirname(__DIR__) . '/Migration';

        // configure migration directories         $migrationSourceV4 = $container->getDefinition(MigrationSource::class D '.core.V6_4');
        $migrationSourceV4->addMethodCall('addDirectory', [$migrationPath . '/V6_4', 'Shopware\Administration\Migration\V6_4']);

        $majors = ['V6_5', 'V6_6'];
        foreach ($majors as $major) {
            $migrationPathV5 = $migrationPath . '/' . $major;

            if (\is_dir($migrationPathV5)) {
                $migrationSource = $container->getDefinition(MigrationSource::class D '.core.' . $major);
                $migrationSource->addMethodCall('addDirectory', [$migrationPathV5, 'Shopware\Administration\Migration\\' . $major]);
            }
        }
    }
}

class PluginManagerPass implements CompilerPassInterface {

  /** * {@inheritdoc} */
  public function process(ContainerBuilder $container) {
    $cache_clearer_definition = $container->getDefinition('plugin.cache_clearer');
    foreach ($container->getDefinitions() as $service_id => $definition) {
      if (str_starts_with($service_id, 'plugin.manager.') || $definition->hasTag('plugin_manager_cache_clear')) {
        if (is_subclass_of($definition->getClass(), '\Drupal\Component\Plugin\Discovery\CachedDiscoveryInterface')) {
          $cache_clearer_definition->addMethodCall('addCachedDiscovery', [new Reference($service_id)]);
        }
      }
    }
  }

}

        $classes = [];
        foreach ($this->getEventClasses() as $eventClass) {
            if (!is_subclass_of($eventClass, FlowEventAware::class)) {
                continue;
            }

            $classes[] = $eventClass;
        }

        $definition = $container->getDefinition(BusinessEventRegistry::class);
        $definition->addMethodCall('addClasses', [$classes]);
    }

    /** * @return \ReflectionClass<BusinessEvents> */
    protected function getReflectionClass(): \ReflectionClass
    {
        return new \ReflectionClass(BusinessEvents::class);
    }

    /** * @return array<string, class-string<SymfonyBaseEvent>> */
$r = $reflectionMethod;

            if ($r->isConstructor() || isset($alreadyCalledMethods[strtolower($r->name)])) {
                continue;
            }

            while (true) {
                if ($r->getAttributes(Required::class)) {
                    if ($this->isWither($r$r->getDocComment() ?: '')) {
                        $withers[] = [$r->name, [], true];
                    } else {
                        $value->addMethodCall($r->name, []);
                    }
                    break;
                }
                if (false !== $doc = $r->getDocComment()) {
                    if (false !== stripos($doc, '@required') && preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@required(?:\s|\*/$)#i', $doc)) {
                        trigger_deprecation('symfony/dependency-injection', '6.3', 'Relying on the "@required" annotation on method "%s::%s()" is deprecated, use the "Symfony\Contracts\Service\Attribute\Required" attribute instead.', $reflectionMethod->class, $reflectionMethod->name);

                        if ($this->isWither($reflectionMethod$doc)) {
                            $withers[] = [$reflectionMethod->name, [], true];
                        } else {
                            $value->addMethodCall($reflectionMethod->name, []);
                        }
public function testProcessDoesNotDropExistingFileLoaderMethodCalls()
    {
        $container = new ContainerBuilder();
        $container->setParameter('kernel.debug', false);

        $container->register('twig.app_variable', AppVariable::class);
        $container->register('twig.extension.yaml');
        $container->register('twig.extension.debug.stopwatch');
        $container->register('twig.extension.expression');

        $nativeTwigLoader = new Definition(FilesystemLoader::class);
        $nativeTwigLoader->addMethodCall('addPath', []);
        $container->setDefinition('twig.loader.native_filesystem', $nativeTwigLoader);

        $templateIterator = new Definition(TemplateIterator::class[null, null, null]);
        $container->setDefinition('twig.template_iterator', $templateIterator);

        $extensionPass = new ExtensionPass();
        $extensionPass->process($container);

        $this->assertCount(1, $nativeTwigLoader->getMethodCalls());
    }
}
$r = $reflectionMethod;

            if ($r->isConstructor() || isset($alreadyCalledMethods[strtolower($r->name)])) {
                continue;
            }

            while (true) {
                if ($r->getAttributes(Required::class)) {
                    if ($this->isWither($r$r->getDocComment() ?: '')) {
                        $withers[] = [$r->name, [], true];
                    } else {
                        $value->addMethodCall($r->name, []);
                    }
                    break;
                }
                if (false !== $doc = $r->getDocComment()) {
                    if (false !== stripos($doc, '@required') && preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@required(?:\s|\*/$)#i', $doc)) {
                        trigger_deprecation('symfony/dependency-injection', '6.3', 'Relying on the "@required" annotation on method "%s::%s()" is deprecated, use the "Symfony\Contracts\Service\Attribute\Required" attribute instead.', $reflectionMethod->class, $reflectionMethod->name);

                        if ($this->isWither($reflectionMethod$doc)) {
                            $withers[] = [$reflectionMethod->name, [], true];
                        } else {
                            $value->addMethodCall($reflectionMethod->name, []);
                        }
Home | Imprint | This part of the site doesn't use cookies.