hasTag example

public function testRoutingRouteLoaderTagIsAdded()
    {
        $frameworkExtension = $this->createMock(ExtensionInterface::class);
        $frameworkExtension
            ->expects($this->atLeastOnce())
            ->method('getAlias')
            ->willReturn('framework');
        $container = new ContainerBuilder();
        $container->registerExtension($frameworkExtension);
        $kernel = $this->kernel = new ConcreteMicroKernel('test', false);
        $kernel->registerContainerConfiguration(new ClosureLoader($container));
        $this->assertTrue($container->getDefinition('kernel')->hasTag('routing.route_loader'));
    }

    public function testFlexStyle()
    {
        $kernel = new FlexStyleMicroKernel('test', false);
        $kernel->boot();

        $request = Request::create('/');
        $response = $kernel->handle($request);

        $this->assertEquals('Have a great day!', $response->getContent());

        
public function process(ContainerBuilder $container): void
    {
        foreach ($container->getDefinitions() as $definition) {
            if ($this->accept($definition) && $reflectionClass = $container->getReflectionClass($definition->getClass(), false)) {
                $this->processClass($definition$reflectionClass);
            }
        }
    }

    private function accept(Definition $definition): bool
    {
        return !$definition->hasTag('container.ignore_attributes') && $definition->isAutowired();
    }

    private function processClass(Definition $definition, \ReflectionClass $reflectionClass): void
    {
        foreach ($reflectionClass->getAttributes(AsDecorator::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
            $attribute = $attribute->newInstance();

            $definition->setDecoratedService($attribute->decorates, null, $attribute->priority, $attribute->onInvalid);
        }
    }
}
$definition = new Definition('class-string');
        foreach ($listeners as $listener) {
            $definition->addTag('kernel.event_listener', $listener);
        }

        $builder->addDefinitions(['class-string' => $definition]);

        RemoveEventListener::remove($builder, 'class-string', [$remove]);

        if ($expected === []) {
            static::assertFalse($definition->hasTag('kernel.event_listener'));

            return;
        }

        static::assertTrue($definition->hasTag('kernel.event_listener'));

        $current = $definition->getTag('kernel.event_listener');

        static::assertEquals($expected$current, \print_r($current, true));
    }

    
/** * Compiler pass to register tagged services that require a service locator. * * @author Nicolas Grekas <p@tchwork.com> */
class RegisterServiceSubscribersPass extends AbstractRecursivePass
{
    protected bool $skipScalars = true;

    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if (!$value instanceof Definition || $value->isAbstract() || $value->isSynthetic() || !$value->hasTag('container.service_subscriber')) {
            return parent::processValue($value$isRoot);
        }

        $serviceMap = [];
        $autowire = $value->isAutowired();

        foreach ($value->getTag('container.service_subscriber') as $attributes) {
            if (!$attributes) {
                $autowire = true;
                continue;
            }
            
$connection = $this->container->get('database');
    $query = $connection->select($table);
    $query->addExpression('COUNT([cid])', 'cid');
    return (int) $query->execute()->fetchField();
  }

  /** * Test that the service "cache_tags.invalidator.checksum" is backend overridable. */
  public function testCacheTagsInvalidatorChecksumIsBackendOverridable() {
    $definition = $this->container->getDefinition('cache_tags.invalidator.checksum');
    $this->assertTrue($definition->hasTag('backend_overridable'));
  }

  /** * Test that the service "cache.backend.database" is backend overridable. */
  public function testCacheBackendDatabaseIsBackendOverridable() {
    $definition = $this->container->getDefinition('cache.backend.database');
    $this->assertTrue($definition->hasTag('backend_overridable'));
  }

}
$io->title('Autowirable Types');
        $io->text('The following classes & interfaces can be used as type-hints when autowiring:');
        if ($search) {
            $io->text(sprintf('(only showing classes/interfaces matching <comment>%s</comment>)', $search));
        }
        $hasAlias = [];
        $all = $input->getOption('all');
        $previousId = '-';
        $serviceIdsNb = 0;
        foreach ($serviceIds as $serviceId) {
            if ($container->hasDefinition($serviceId) && $container->getDefinition($serviceId)->hasTag('container.excluded')) {
                continue;
            }
            $text = [];
            $resolvedServiceId = $serviceId;
            if (!str_starts_with($serviceId$previousId.' $')) {
                $text[] = '';
                $previousId = preg_replace('/ \$.*/', '', $serviceId);
                if ('' !== $description = Descriptor::getClassDescription($previousId$resolvedServiceId)) {
                    if (isset($hasAlias[$previousId])) {
                        continue;
                    }
                    


        if (str_starts_with($originalClass->getFilename(), __FILE__)) {
            $interfaces = $classGenerator->getImplementedInterfaces();
            array_pop($interfaces);
            $classGenerator->setImplementedInterfaces(array_merge($interfaces$originalClass->getInterfaceNames()));
        }
    }

    public function getProxifiedClass(Definition $definition): ?string
    {
        if (!$definition->hasTag('proxy')) {
            if (!($class = $definition->getClass()) || !(class_exists($class) || interface_exists($class, false))) {
                return null;
            }

            return (new \ReflectionClass($class))->name;
        }
        if (!$definition->isLazy()) {
            throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": setting the "proxy" tag on a service requires it to be "lazy".', $definition->getClass()));
        }
        $tags = $definition->getTag('proxy');
        if (!isset($tags[0]['interface'])) {
            
/** * Confirms that a query has a tag added to it. */
  public function testHasTag() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');

    $query->addTag('test');

    $this->assertTrue($query->hasTag('test'), 'hasTag() returned true.');
    $this->assertFalse($query->hasTag('other'), 'hasTag() returned false.');
  }

  /** * Tests query tagging "has all of these tags" functionality. */
  public function testHasAllTags() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');

    
$this->assertEquals([]$def->getTags(), '->clearTags() removes all current tags');
    }

    public function testClearTag()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def$def->clearTags(), '->clearTags() implements a fluent interface');
        $def->addTag('1foo1', ['foo1' => 'bar1']);
        $def->addTag('2foo2', ['foo2' => 'bar2']);
        $def->addTag('3foo3', ['foo3' => 'bar3']);
        $def->clearTag('2foo2');
        $this->assertTrue($def->hasTag('1foo1'));
        $this->assertFalse($def->hasTag('2foo2'));
        $this->assertTrue($def->hasTag('3foo3'));
        $def->clearTag('1foo1');
        $this->assertFalse($def->hasTag('1foo1'));
        $this->assertTrue($def->hasTag('3foo3'));
    }

    public function testTags()
    {
        $def = new Definition('stdClass');
        $this->assertEquals([]$def->getTag('foo'), '->getTag() returns an empty array if the tag is not defined');
        
$container
            ->findDefinition('translator.default')
            ->replaceArgument(0, ServiceLocatorTagPass::register($container$loaderRefs))
            ->replaceArgument(3, $loaders)
        ;

        if ($container->hasDefinition('validator') && $container->hasDefinition('translation.extractor.visitor.constraint')) {
            $constraintVisitorDefinition = $container->getDefinition('translation.extractor.visitor.constraint');
            $constraintClassNames = [];

            foreach ($container->getDefinitions() as $definition) {
                if (!$definition->hasTag('validator.constraint_validator')) {
                    continue;
                }
                // Resolve constraint validator FQCN even if defined as %foo.validator.class% parameter                 $className = $container->getParameterBag()->resolveValue($definition->getClass());
                // Extraction of the constraint class name from the Constraint Validator FQCN                 $constraintClassNames[] = str_replace('Validator', '', substr(strrchr($className, '\\'), 1));
            }

            $constraintVisitorDefinition->setArgument(0, $constraintClassNames);
        }

        
public function process(ContainerBuilder $container): void
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if ($this->accept($definition) && $class = $container->getReflectionClass($definition->getClass(), false)) {
                $this->processClass($container$class);
            }
        }
    }

    public function accept(Definition $definition): bool
    {
        return $definition->isAutoconfigured() && !$definition->hasTag('container.ignore_attributes');
    }

    public function processClass(ContainerBuilder $container, \ReflectionClass $class): void
    {
        foreach ($class->getAttributes(Autoconfigure::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
            self::registerForAutoconfiguration($container$class$attribute);
        }
    }

    private static function registerForAutoconfiguration(ContainerBuilder $container, \ReflectionClass $class, \ReflectionAttribute $attribute): void
    {
        
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()]);
        }

        $checkAttributes = !$value->hasTag('container.ignore_attributes');
        $this->methodCalls = $this->autowireCalls($reflectionClass$isRoot$checkAttributes);

        if ($constructor) {
            [$arguments] = array_shift($this->methodCalls);

            if ($arguments !== $value->getArguments()) {
                $value->setArguments($arguments);
            }
        }

        if ($this->methodCalls !== $value->getMethodCalls()) {
            
foreach ($serviceIds as $serviceId) {
            $service = $this->resolveServiceDefinition($container$serviceId);

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

            if ($service instanceof Alias) {
                $services['aliases'][$serviceId] = $service;
            } elseif ($service instanceof Definition) {
                if ($service->hasTag('container.excluded')) {
                    continue;
                }
                $services['definitions'][$serviceId] = $service;
            } else {
                $services['services'][$serviceId] = $service;
            }
        }

        if (!empty($services['definitions'])) {
            $this->write("\n\nDefinitions\n-----------\n");
            foreach ($services['definitions'] as $id => $service) {
                
foreach ($serviceIds as $serviceId) {
            $service = $this->resolveServiceDefinition($container$serviceId);

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

            if ($service instanceof Alias) {
                $data['aliases'][$serviceId] = $this->getContainerAliasData($service);
            } elseif ($service instanceof Definition) {
                if ($service->hasTag('container.excluded')) {
                    continue;
                }
                $data['definitions'][$serviceId] = $this->getContainerDefinitionData($service$omitTags$showArguments$container$serviceId);
            } else {
                $data['services'][$serviceId] = $service::class;
            }
        }

        $this->writeData($data$options);
    }

    

    public function testAutoConfigure(): void
    {
        $container = new ContainerBuilder();

        $container->addCompilerPass(new AutoconfigureCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1000);
        $container->setDefinition('product', (new Definition(ProductDefinition::class))->setPublic(true)->setAutoconfigured(true)->setAutowired(true));

        $container->compile(true);

        static::assertTrue($container->hasDefinition('product'));
        static::assertTrue($container->getDefinition('product')->hasTag('shopware.entity.definition'));
    }

    public function testAliasing(): void
    {
        $container = new ContainerBuilder();

        $container->addCompilerPass(new AutoconfigureCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1000);
        $definition = new Definition(ExampleService::class);
        $definition->setPublic(true);
        $definition->setAutoconfigured(true);
        $definition->setAutowired(true);

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