removeDefinition example

class RemoveAbstractDefinitionsPass implements CompilerPassInterface
{
    /** * Removes abstract definitions from the ContainerBuilder. * * @return void */
    public function process(ContainerBuilder $container)
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if ($definition->isAbstract()) {
                $container->removeDefinition($id);
                $container->log($thissprintf('Removed service "%s"; reason: abstract.', $id));
            }
        }
    }
}
if (class_exists(InstalledVersions::class) && InstalledVersions::isInstalled('symfony/symfony') && 'symfony/symfony' !== (InstalledVersions::getRootPackage()['name'] ?? '')) {
            trigger_deprecation('symfony/symfony', '6.1', 'Requiring the "symfony/symfony" package is deprecated; replace it with standalone components instead.');
        }

        $loader->load('web.php');
        $loader->load('services.php');
        $loader->load('fragment_renderer.php');
        $loader->load('error_renderer.php');

        if (!ContainerBuilder::willBeAvailable('symfony/clock', ClockInterface::class['symfony/framework-bundle'])) {
            $container->removeDefinition('clock');
            $container->removeAlias(ClockInterface::class);
            $container->removeAlias(PsrClockInterface::class);
        }

        $container->registerAliasForArgument('parameter_bag', PsrContainerInterface::class);

        $loader->load('process.php');

        if (!class_exists(RunProcessMessageHandler::class)) {
            $container->removeDefinition('process.messenger.process_message_handler');
        }

        

    public function process(ContainerBuilder $container)
    {
        if ($container->has('security.expression_language')) {
            $definition = $container->findDefinition('security.expression_language');
            foreach ($container->findTaggedServiceIds('security.expression_language_provider', true) as $id => $attributes) {
                $definition->addMethodCall('registerProvider', [new Reference($id)]);
            }
        }

        if (!$container->hasDefinition('cache.system')) {
            $container->removeDefinition('cache.security_expression_language');
            $container->removeDefinition('cache.security_is_granted_attribute_expression_language');
        }
    }
}
$container = new ContainerBuilder();
        $container->set($idnew \stdClass());
        $container->setAlias($aliasId, 'another_service');

        $this->assertTrue($container->has('another_service'));
        $this->assertTrue($container->has($id));
        $this->assertTrue($container->hasAlias('alias_id'));
        $this->assertTrue($container->hasAlias($aliasId));

        $container->removeAlias($aliasId);
        $container->removeDefinition($id);
    }

    public function testErroredDefinition()
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Service "errored_definition" is broken.');
        $container = new ContainerBuilder();

        $container->register('errored_definition', 'stdClass')
            ->addError('Service "errored_definition" is broken.')
            ->setPublic(true);

        
      /** @var \Drupal\Core\DrupalKernelInterface $kernel */
      $kernel = \Drupal::service('kernel');
      $kernel->rebuildContainer();
      // 2) Fetch the in-situ container builder.       $container = ErrorServiceTestServiceProvider::$containerBuilder;
      // Ensure the compiler pass worked.       if (!$container) {
        throw new \Exception('Oh oh, monkeys stole the ServiceProvider.');
      }
      // Stop the theme manager from being found - and triggering error       // maintenance mode.       $container->removeDefinition('theme.manager');
      // Mash. Mash. Mash.       \Drupal::setContainer($container);
      throw new \Exception('Oh oh, bananas in the instruments.');
    }

    if (\Drupal::state()->get('error_service_test.break_logger')) {
      throw new \Exception('Deforestation');
    }

    return $this->app->handle($request$type$catch);
  }

}
$process_aliases = FALSE;
    // Loop over the defined services and remove any with unmet dependencies.     // The kernel cannot be booted if the container has such services. This     // allows modules to run their update hooks to enable newly added     // dependencies.     do {
      $has_changed = FALSE;
      foreach ($container->getDefinitions() as $key => $definition) {
        // Ensure all the definition's arguments are valid.         foreach ($definition->getArguments() as $argument) {
          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) {
            
/** * @internal */
#[Package('core')] class RemoveDeprecatedServicesPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if ($definition->isDeprecated()) {
                $container->removeDefinition($id);
            }
        }
    }
}
throw new ServiceNotFoundException($e->getId()$e->getSourceId(), null, [substr($e->getId(), 1)]);
                }

                throw $e;
            }
            if ($definition->isPublic()) {
                continue;
            }
            // Remove private definition and schedule for replacement             $definition->setPublic($target->isPublic());
            $container->setDefinition($definitionId$definition);
            $container->removeDefinition($targetId);
            $replacements[$targetId] = $definitionId;

            if ($target->isPublic() && $target->isDeprecated()) {
                $definition->addTag('container.private', $target->getDeprecation('%service_id%'));
            }
        }
        $this->replacements = $replacements;

        parent::process($container);
        $this->replacements = [];
    }

    
if ('ignore' === ($attributes['on_invalid'] ?? null)) {
                    $attributes['method'] = '?'.$attributes['method'];
                }

                $methods[$id][] = $attributes['method'];
            }
        }

        if (!$services) {
            $container->removeAlias('services_resetter');
            $container->removeDefinition('services_resetter');

            return;
        }

        $container->findDefinition('services_resetter')
            ->setArgument(0, new IteratorArgument($services))
            ->setArgument(1, $methods);
    }
}
throw new InvalidArgumentException(sprintf('Invalid "cache.pool" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus" and "reset", found "%s".', $idimplode('", "', array_keys($tags[0]))));
            }

            if (null !== $clearer) {
                $clearers[$clearer][$name] = new Reference($id$container::IGNORE_ON_UNINITIALIZED_REFERENCE);
            }

            $allPools[$name] = new Reference($id$container::IGNORE_ON_UNINITIALIZED_REFERENCE);
        }

        if (!$needsMessageHandler) {
            $container->removeDefinition('cache.early_expiration_handler');
        }

        $notAliasedCacheClearerId = $aliasedCacheClearerId = 'cache.global_clearer';
        while ($container->hasAlias('cache.global_clearer')) {
            $aliasedCacheClearerId = (string) $container->getAlias('cache.global_clearer');
        }
        if ($container->hasDefinition($aliasedCacheClearerId)) {
            $clearers[$notAliasedCacheClearerId] = $allPools;
        }

        foreach ($clearers as $id => $pools) {
            
return $this->state->get('views.view_route_names', []);
  }

  /** * {@inheritdoc} */
  public function remove() {
    $menu_links = $this->getMenuLinks();
    /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    foreach ($menu_links as $menu_link_id => $menu_link) {
      $menu_link_manager->removeDefinition("views_view:$menu_link_id");
    }
  }

}


    /** * @dataProvider getDebugModes */
    public function testDefaultConfig($debug)
    {
        $this->container->setParameter('kernel.debug', $debug);

        $extension = new WebProfilerExtension();
        $extension->load([[]]$this->container);
        $this->container->removeDefinition('web_profiler.controller.exception');

        $this->assertFalse($this->container->has('web_profiler.debug_toolbar'));

        self::assertSaneContainer($this->getCompiledContainer());
    }

    public static function getDebugModes()
    {
        return [
            ['debug' => false],
            ['debug' => true],
        ];
'parent' => '',
      'child-1' => 'child-2',
      'child-1-1' => 'child-1',
      'child-1-2' => 'child-1',
      'child-2' => 'parent',
    ];
    $this->assertMenuLinkParents($links$expected_hierarchy);

    // Start over, and delete child-1, and check that the children of child-1     // have been reassigned to the parent.     $links = $this->createLinkHierarchy($module);
    $this->menuLinkManager->removeDefinition($links['child-1']);

    $expected_hierarchy = [
      'parent' => FALSE,
      'child-1-1' => 'parent',
      'child-1-2' => 'parent',
      'child-2' => 'parent',
    ];
    $this->assertMenuLinkParents($links$expected_hierarchy);

    // Try changing the parent at the entity level.     $definition = $this->menuLinkManager->getDefinition($links['child-1-2']);
    
return null !== $class ? $configurator->class($class) : $configurator;
    }

    /** * Removes an already defined service definition or alias. * * @return $this */
    final public function remove(string $id)static
    {
        $this->container->removeDefinition($id);
        $this->container->removeAlias($id);

        return $this;
    }

    /** * Creates an alias. */
    final public function alias(string $id, string $referencedId): AliasConfigurator
    {
        $ref = static::processValue($referencedId, true);
        
use Symfony\Component\DependencyInjection\ContainerBuilder;

/** * @codeCoverageIgnore It's not possible to test without hacky solutions and relying on internals */
#[Package('core')] class RemoveDevServices implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        if (!InstalledVersions::isInstalled('symfony/web-profiler-bundle') || !$container->hasDefinition('profiler')) {
            $container->removeDefinition(ProfilerController::class);
        }
    }
}
Home | Imprint | This part of the site doesn't use cookies.