getServiceIds example

$this->assertEquals([
            'ROLE_ADMIN' => ['ROLE_USER'],
            'ROLE_SUPER_ADMIN' => ['ROLE_USER', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'],
            'ROLE_REMOTE' => ['ROLE_USER', 'ROLE_ADMIN'],
        ]$container->getParameter('security.role_hierarchy.roles'));
    }

    public function testUserProviders()
    {
        $container = $this->getContainer('container1');

        $providers = array_values(array_filter($container->getServiceIds()fn ($key) => str_starts_with($key, 'security.user.provider.concrete')));

        $expectedProviders = [
            'security.user.provider.concrete.default',
            'security.user.provider.concrete.digest',
            'security.user.provider.concrete.basic',
            'security.user.provider.concrete.service',
            'security.user.provider.concrete.chain',
        ];

        $this->assertEquals([]array_diff($expectedProviders$providers));
        $this->assertEquals([]array_diff($providers$expectedProviders));

        
if (!$id) {
                throw new ServiceNotFoundException($id);
            }
            if (isset($container->syntheticIds[$id])) {
                throw new ServiceNotFoundException($id, null, null, []sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id));
            }
            if (isset($container->getRemovedIds()[$id])) {
                throw new ServiceNotFoundException($id, null, null, []sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id));
            }

            $alternatives = [];
            foreach ($container->getServiceIds() as $knownId) {
                if ('' === $knownId || '.' === $knownId[0]) {
                    continue;
                }
                $lev = levenshtein($id$knownId);
                if ($lev <= \strlen($id) / 3 || str_contains($knownId$id)) {
                    $alternatives[] = $knownId;
                }
            }

            throw new ServiceNotFoundException($id, null, null, $alternatives);
        }

        
return $dom;
    }

    private function getContainerServicesDocument(ContainerBuilder $container, string $tag = null, bool $showHidden = false, bool $showArguments = false, callable $filter = null, string $id = null): \DOMDocument
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->appendChild($containerXML = $dom->createElement('container'));

        $serviceIds = $tag
            ? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($tag))
            : $this->sortServiceIds($container->getServiceIds());
        if ($filter) {
            $serviceIds = array_filter($serviceIds$filter);
        }

        foreach ($serviceIds as $serviceId) {
            $service = $this->resolveServiceDefinition($container$serviceId);

            if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
                continue;
            }

            
return $this->$method(...$arguments);
    }

    public function setContainer(ContainerInterface $container): ?ContainerInterface
    {
        if (!$this->throwOnUnexpectedService) {
            return parent::setContainer($container);
        }

        $expected = self::getSubscribedServices();

        foreach ($container->getServiceIds() as $id) {
            if ('service_container' === $id) {
                continue;
            }
            if (!isset($expected[$id])) {
                throw new \UnexpectedValueException(sprintf('Service "%s" is not expected, as declared by "%s::getSubscribedServices()".', $id, AbstractController::class));
            }
            $type = substr($expected[$id], 1);
            if (!$container->get($id) instanceof $type) {
                throw new \UnexpectedValueException(sprintf('Service "%s" is expected to be an instance of "%s", as declared by "%s::getSubscribedServices()".', $id$type, AbstractController::class));
            }
        }

        
use Twig\Loader\ArrayLoader;

class WebProfilerExtensionTest extends TestCase
{
    private MockObject&KernelInterface $kernel;
    private ?ContainerBuilder $container;

    public static function assertSaneContainer(Container $container)
    {
        $removedIds = $container->getRemovedIds();
        $errors = [];
        foreach ($container->getServiceIds() as $id) {
            if (isset($removedIds[$id])) {
                continue;
            }
            try {
                $container->get($id);
            } catch (\Exception $e) {
                $errors[$id] = $e->getMessage();
            }
        }

        self::assertSame([]$errors);
    }

trait ServiceIdHashTrait {

  /** * Implements \Drupal\Component\DependencyInjection\ContainerInterface::getServiceIdMappings() */
  public function getServiceIdMappings(): array {
    @trigger_error(__METHOD__ . "() is deprecated in drupal:9.5.1 and is removed from drupal:11.0.0. Use the 'Drupal\Component\DependencyInjection\ReverseContainer' service instead. See https://www.drupal.org/node/3327942", E_USER_DEPRECATED);
    $mapping = [];
    foreach ($this->getServiceIds() as $service_id) {
      if ($this->initialized($service_id) && $service_id !== 'service_container') {
        $mapping[$this->generateServiceIdHash($this->get($service_id))] = $service_id;
      }
    }
    return $mapping;
  }

  /** * Implements \Drupal\Component\DependencyInjection\ContainerInterface::generateServiceIdHash() */
  public function generateServiceIdHash(object $object): string {
    @
public function testAliasCanBeFoundInTheDumpedContainerWhenBothTheAliasAndTheServiceArePublic()
    {
        $container = new ContainerBuilder();

        $container->register('foo', 'stdClass')->setPublic(true);
        $container->setAlias('bar', 'foo')->setPublic(true);

        $container->compile();

        // Bar is found in the compiled container         $service_ids = $container->getServiceIds();
        $this->assertContains('bar', $service_ids);

        $dumper = new PhpDumper($container);
        $dump = $dumper->dump(['class' => 'Symfony_DI_PhpDumper_AliasesCanBeFoundInTheDumpedContainer']);
        eval('?>'.$dump);

        $container = new \Symfony_DI_PhpDumper_AliasesCanBeFoundInTheDumpedContainer();

        // Bar should still be found in the compiled container         $service_ids = $container->getServiceIds();
        $this->assertContains('bar', $service_ids);
    }
private function createTypeAlternatives(ContainerBuilder $container, TypedReference $reference): string
    {
        // try suggesting available aliases first         if ($message = $this->getAliasesSuggestionForType($container$type = $reference->getType())) {
            return ' '.$message;
        }
        if (!isset($this->ambiguousServiceTypes)) {
            $this->populateAvailableTypes($container);
        }

        $servicesAndAliases = $container->getServiceIds();
        $autowiringAliases = $this->autowiringAliases[$type] ?? [];
        unset($autowiringAliases['']);

        if ($autowiringAliases) {
            return sprintf(' Did you mean to target%s "%s" instead?', 1 < \count($autowiringAliases) ? ' one of' : '', implode('", "', $autowiringAliases));
        }

        if (!$container->has($type) && false !== $key = array_search(strtolower($type)array_map('strtolower', $servicesAndAliases))) {
            return sprintf(' Did you mean "%s"?', $servicesAndAliases[$key]);
        } elseif (isset($this->ambiguousServiceTypes[$type])) {
            $message = sprintf('one of these existing services: "%s"', implode('", "', $this->ambiguousServiceTypes[$type]));
        }
EOF
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input$output);
        $errorIo = $io->getErrorStyle();

        $container = $this->getContainerBuilder($this->getApplication()->getKernel());
        $serviceIds = $container->getServiceIds();
        $serviceIds = array_filter($serviceIds$this->filterToServiceTypes(...));

        if ($search = $input->getArgument('search')) {
            $searchNormalized = preg_replace('/[^a-zA-Z0-9\x7f-\xff $]++/', '', $search);

            $serviceIds = array_filter($serviceIdsfn ($serviceId) => false !== stripos(str_replace('\\', '', $serviceId)$searchNormalized) && !str_starts_with($serviceId, '.'));

            if (!$serviceIds) {
                $errorIo->error(sprintf('No autowirable classes or interfaces found matching "%s"', $search));

                return 1;
            }


        if (1 === \count($matchingTags)) {
            return $matchingTags[0];
        }

        return $io->choice('Select one of the following tags to display its information', $matchingTags);
    }

    private function findServiceIdsContaining(ContainerBuilder $container, string $name, bool $showHidden): array
    {
        $serviceIds = $container->getServiceIds();
        $foundServiceIds = $foundServiceIdsIgnoringBackslashes = [];
        foreach ($serviceIds as $serviceId) {
            if (!$showHidden && str_starts_with($serviceId, '.')) {
                continue;
            }
            if (!$showHidden && $container->hasDefinition($serviceId) && $container->getDefinition($serviceId)->hasTag('container.excluded')) {
                continue;
            }
            if (false !== stripos(str_replace('\\', '', $serviceId)$name)) {
                $foundServiceIdsIgnoringBackslashes[] = $serviceId;
            }
            

        $showHidden = isset($options['show_hidden']) && $options['show_hidden'];

        $title = $showHidden ? 'Hidden services' : 'Services';
        if (isset($options['tag'])) {
            $title .= ' with tag `'.$options['tag'].'`';
        }
        $this->write($title."\n".str_repeat('=', \strlen($title)));

        $serviceIds = isset($options['tag']) && $options['tag']
            ? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($options['tag']))
            : $this->sortServiceIds($container->getServiceIds());
        $showArguments = isset($options['show_arguments']) && $options['show_arguments'];
        $services = ['definitions' => [], 'aliases' => [], 'services' => []];

        if (isset($options['filter'])) {
            $serviceIds = array_filter($serviceIds$options['filter']);
        }

        foreach ($serviceIds as $serviceId) {
            $service = $this->resolveServiceDefinition($container$serviceId);

            if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
                
parent::compile();

        foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) {
            if (!$definition->isPublic() || $definition->isPrivate()) {
                $this->removedIds[$id] = true;
            }
        }
    }

    public function getServiceIds(): array
    {
        return array_map('strval', array_unique(array_merge(array_keys($this->getDefinitions())array_keys($this->aliasDefinitions), parent::getServiceIds())));
    }

    /** * Gets removed service or alias ids. * * @return array<string, bool> */
    public function getRemovedIds(): array
    {
        return $this->removedIds;
    }

    
$definitionInstanceRegistry->expects(static::never())
            ->method('register');

        $container = new Container();
        $container->set(Connection::class$connection);
        $container->set(DefinitionInstanceRegistry::class$definitionInstanceRegistry);

        $registrar = new CustomEntityRegistrar($container);

        $registrar->register();

        static::assertCount(3, $container->getServiceIds());
    }

    public function testFetchesCustomEntitiesFromDbAndRegistersThemAtTheContainer(): void
    {
        $container = new Container();

        /** @var DynamicEntityDefinition[] $definitions */
        $definitions = [
            DynamicEntityDefinition::create('ce_test_one', [][]$container),
            DynamicEntityDefinition::create('ce_test_two', [][]$container),
        ];

        


            try {
                $class = $this->container->getParameterBag()->resolveValue($class);
            } catch (ParameterNotFoundException) {
            }

            $nodes[$id] = ['class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition']['style' => $definition->isShared() ? 'filled' : 'dotted'])];
            $container->setDefinition($idnew Definition('stdClass'));
        }

        foreach ($container->getServiceIds() as $id) {
            if (\array_key_exists($id$container->getAliases())) {
                continue;
            }

            if (!$container->hasDefinition($id)) {
                $nodes[$id] = ['class' => str_replace('\\', '\\\\', $container->get($id)::class), 'attributes' => $this->options['node.instance']];
            }
        }

        return $nodes;
    }

    
$this->container->get('late.service');
    $this->assertTrue($this->container->initialized('late.service_alias'), 'Late service is initialized after it was retrieved once.');
  }

  /** * Tests that Container::getServiceIds() works properly. * * @covers ::getServiceIds */
  public function testGetServiceIds() {
    $service_definition_keys = array_keys($this->containerDefinition['services']);
    $this->assertEquals($service_definition_keys$this->container->getServiceIds(), 'Retrieved service IDs match definition.');

    $mock_service = new MockService();
    $this->container->set('bar', $mock_service);
    $this->container->set('service.provider', $mock_service);
    $service_definition_keys[] = 'bar';

    $this->assertEquals($service_definition_keys$this->container->getServiceIds(), 'Retrieved service IDs match definition after setting new services.');
  }

  /** * Tests that raw type services arguments are resolved correctly. * * @covers ::get * @covers ::createService * @covers ::resolveServicesAndParameters */
Home | Imprint | This part of the site doesn't use cookies.