setDecoratedService example

class DecoratorServicePassTest extends TestCase
{
    public function testProcessWithoutAlias()
    {
        $container = new ContainerBuilder();
        $fooDefinition = $container
            ->register('foo')
        ;
        $fooExtendedDefinition = $container
            ->register('foo.extended')
            ->setPublic(true)
            ->setDecoratedService('foo')
        ;
        $barDefinition = $container
            ->register('bar')
            ->setPublic(true)
        ;
        $barExtendedDefinition = $container
            ->register('bar.extended')
            ->setPublic(true)
            ->setDecoratedService('bar', 'bar.yoo')
        ;

        
/** @var DummyService $dummy */
        $dummy = $container->get(DummyService::class);
        static::assertInstanceOf(FastlyService::class$dummy->get());
    }

    public function testFastlyReplacesAndPluginExtendsFastly(): void
    {
        $container = $this->getContainer();

        $container->register(PluginService::class)
            ->setPublic(true)
            ->setDecoratedService(FastlyReverseProxyGateway::class);

        $container->compile();

        static::assertTrue($container->has('shopware.cache.reverse_proxy.redis'));
        static::assertTrue($container->has(ReverseProxyCache::class));
        static::assertTrue($container->has(ReverseProxyCacheClearer::class));
        static::assertTrue($container->has(FastlyReverseProxyGateway::class));

        static::assertInstanceOf(PluginService::class$container->get(FastlyReverseProxyGateway::class));

        /** @var DummyService $dummy */
        


        $container->register('Test\soon_private_service')
            ->setPublic(true)
            ->addTag('container.private', ['package' => 'foo/bar', 'version' => '1.42'])
        ;
        $container->register('Test\soon_private_service_decorated')
            ->setPublic(true)
            ->addTag('container.private', ['package' => 'foo/bar', 'version' => '1.42'])
        ;
        $container->register('Test\soon_private_service_decorator')
            ->setDecoratedService('Test\soon_private_service_decorated')
            ->setArguments(['Test\soon_private_service_decorator.inner']);

        $container->register('Test\private_used_shared_service');
        $container->register('Test\private_unused_shared_service');
        $container->register('Test\private_used_non_shared_service')->setShared(false);
        $container->register('Test\private_unused_non_shared_service')->setShared(false);

        $container->compile();

        $expected = [
            'Test\private_used_shared_service' => new ServiceClosureArgument(new Reference('Test\private_used_shared_service')),
            
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();
$container
    ->register('foo', 'FooClass\\Foo')
    ->setDecoratedService('bar')
    ->setPublic(true)
;

return $container;


    public function testCanDecorateServiceSubscriberUsingBinding()
    {
        $container = new ContainerBuilder();
        $container->register(ServiceSubscriberStub::class)
            ->addTag('container.service_subscriber')
            ->setPublic(true);

        $container->register(DecoratedServiceSubscriber::class)
            ->setProperty('inner', new Reference(DecoratedServiceSubscriber::class.'.inner'))
            ->setDecoratedService(ServiceSubscriberStub::class);

        $container->compile();

        $this->assertInstanceOf(DecoratedServiceSubscriber::class$container->get(ServiceSubscriberStub::class));
        $this->assertInstanceOf(ServiceSubscriberStub::class$container->get(ServiceSubscriberStub::class)->inner);
        $this->assertInstanceOf(ServiceLocator::class$container->get(ServiceSubscriberStub::class)->inner->container);
    }

    public function testCanDecorateServiceSubscriberReplacingArgument()
    {
        $container = new ContainerBuilder();
        
 elseif (null === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
            } elseif ('null' === $decorationOnInvalid) {
                throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean null (without quotes) in "%s"?', $decorationOnInvalid$id$file));
            } else {
                throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean "exception", "ignore" or null in "%s"?', $decorationOnInvalid$id$file));
            }

            $renameId = $service['decoration_inner_name'] ?? null;
            $priority = $service['decoration_priority'] ?? 0;

            $definition->setDecoratedService($decorates$renameId$priority$invalidBehavior);
        }

        if (isset($service['autowire'])) {
            $definition->setAutowired($service['autowire']);
        }

        if (isset($defaults['bind']) || isset($service['bind'])) {
            // deep clone, to avoid multiple process of the same instance in the passes             $bindings = $definition->getBindings();
            $bindings += isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];

            
$decoratedIds = [];

        $tagsToKeep = $container->hasParameter('container.behavior_describing_tags')
            ? $container->getParameter('container.behavior_describing_tags')
            : ['proxy', 'container.do_not_inline', 'container.service_locator', 'container.service_subscriber', 'container.service_subscriber.locator'];

        foreach ($definitions as [$id$definition]) {
            $decoratedService = $definition->getDecoratedService();
            [$inner$renamedId] = $decoratedService;
            $invalidBehavior = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;

            $definition->setDecoratedService(null);

            if (!$renamedId) {
                $renamedId = $id.'.inner';
            }

            $decoratedIds[$inner] ??= $renamedId;
            $this->currentId = $renamedId;
            $this->processValue($definition);

            $definition->innerServiceId = $renamedId;
            $definition->decorationOnInvalid = $invalidBehavior;

            
new ResolveInstanceofConditionalsPass())->process($container);
    }

    public function testMergeReset()
    {
        $container = new ContainerBuilder();

        $container
            ->register('bar', self::class)
            ->addArgument('a')
            ->addMethodCall('setB')
            ->setDecoratedService('foo')
            ->addTag('t')
            ->setInstanceofConditionals([
                parent::class => (new ChildDefinition(''))->addTag('bar'),
            ])
        ;

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

        $abstract = $container->getDefinition('.abstract.instanceof.bar');

        $this->assertEmpty($abstract->getArguments());
        
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();
$container
    ->register('foo', 'FooClass\\Foo')
    ->setDecoratedService('bar', 'bar.woozy')
    ->setPublic(true)
;

return $container;
private DataCollectorTranslatorPass $dataCollectorTranslatorPass;

    protected function setUp(): void
    {
        $this->container = new ContainerBuilder();
        $this->dataCollectorTranslatorPass = new DataCollectorTranslatorPass();

        $this->container->setParameter('translator_implementing_bag', Translator::class);
        $this->container->setParameter('translator_not_implementing_bag', 'Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TranslatorWithTranslatorBag');

        $this->container->register('translator.data_collector', DataCollectorTranslator::class)
            ->setDecoratedService('translator')
            ->setArguments([new Reference('translator.data_collector.inner')])
        ;

        $this->container->register('data_collector.translation', TranslationDataCollector::class)
            ->setArguments([new Reference('translator.data_collector')])
        ;
    }

    /** * @dataProvider getImplementingTranslatorBagInterfaceTranslatorClassNames */
    
 elseif ('ignore' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
            } elseif ('null' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
            } else {
                throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration-on-invalid" on service "%s". Did you mean "exception", "ignore" or "null" in "%s"?', $decorationOnInvalid$service->getAttribute('id')$file));
            }

            $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
            $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;

            $definition->setDecoratedService($decorates$renameId$priority$invalidBehavior);
        }

        if ($callable = $this->getChildren($service, 'from-callable')) {
            if ($definition instanceof ChildDefinition) {
                throw new InvalidArgumentException(sprintf('Attribute "parent" is unsupported when using "<from-callable>" on service "%s".', (string) $service->getAttribute('id')));
            }

            foreach ([
                'Attribute "synthetic"' => 'isSynthetic',
                'Attribute "file"' => 'getFile',
                'Tag "<factory>"' => 'getFactory',
                
/** * Tests that getDecoratedService() is unsupported. * * Tests that the correct InvalidArgumentException is thrown for * getDecoratedService(). * * @covers ::getServiceDefinition */
    public function testGetServiceDefinitionForDecoratedService() {
      $bar_definition = new Definition('\stdClass');
      $bar_definition->setPublic(TRUE);
      $bar_definition->setDecoratedService(new Reference('foo'));
      $services['bar'] = $bar_definition;

      $this->containerBuilder->getDefinitions()->willReturn($services);
      $this->expectException(InvalidArgumentException::class);
      $this->dumper->getArray();
    }

    /** * Tests that the correct RuntimeException is thrown for expressions. * * @covers ::dumpValue */
if (!$isDebugEnabled) {
            $container->removeDefinition(DataCollector::class);

            return;
        }

        $clientDecorator = new Definition(ClientProfiler::class);
        $clientDecorator->setArguments([
            new Reference('shopware.es.profiled.client.inner'),
        ]);
        $clientDecorator->setDecoratedService(Client::class);

        $container->setDefinition('shopware.es.profiled.client', $clientDecorator);

        $adminClientDecorator = new Definition(ClientProfiler::class);
        $adminClientDecorator->setArguments([
            new Reference('shopware.es.profiled.adminClient.inner'),
        ]);
        $adminClientDecorator->setDecoratedService('admin.openSearch.client');

        $container->setDefinition('shopware.es.profiled.adminClient', $adminClientDecorator);
    }
}
$this->assertSame([]$container->getDefinition('autowired')->getArguments());
    }

    public function testAutowireDecorator()
    {
        $container = new ContainerBuilder();
        $container->register(LoggerInterface::class, NullLogger::class);
        $container->register(Decorated::class, Decorated::class);
        $container
            ->register(Decorator::class, Decorator::class)
            ->setDecoratedService(Decorated::class)
            ->setAutowired(true)
        ;

        (new DecoratorServicePass())->process($container);
        (new AutowirePass())->process($container);

        $definition = $container->getDefinition(Decorator::class);
        $this->assertSame(Decorator::class.'.inner', (string) $definition->getArgument(1));
    }

    public function testAutowireDecoratorChain()
    {
 elseif ('ignore' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
            } elseif ('null' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
            } else {
                throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration-on-invalid" on service "%s". Did you mean "exception", "ignore" or "null" in "%s"?', $decorationOnInvalid$service->getAttribute('id')$file));
            }

            $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
            $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;

            $definition->setDecoratedService($decorates$renameId$priority$invalidBehavior);
        }

        if ($callable = $this->getChildren($service, 'from-callable')) {
            if ($definition instanceof ChildDefinition) {
                throw new InvalidArgumentException(sprintf('Attribute "parent" is unsupported when using "<from-callable>" on service "%s".', (string) $service->getAttribute('id')));
            }

            foreach ([
                'Attribute "synthetic"' => 'isSynthetic',
                'Attribute "file"' => 'getFile',
                'Tag "<factory>"' => 'getFactory',
                
Home | Imprint | This part of the site doesn't use cookies.