addSubscriber example

use WorkflowBuilderTrait;

    public function testItWorks()
    {
        $definition = $this->createSimpleWorkflowDefinition();

        $object = new Subject();

        $logger = new Logger();

        $ed = new EventDispatcher();
        $ed->addSubscriber(new AuditTrailListener($logger));

        $workflow = new Workflow($definitionnew MethodMarkingStore()$ed);

        $workflow->apply($object, 't1');

        $expected = [
            'Leaving "a" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
            'Transition "t1" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
            'Entering "b" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
        ];

        
public function testRemoveListener() {
    $this->dispatcher->addListener('pre.bar', $this->listener);
    $this->assertTrue($this->dispatcher->hasListeners(self::PREBAR));
    $this->dispatcher->removeListener('pre.bar', $this->listener);
    $this->assertFalse($this->dispatcher->hasListeners(self::PREBAR));
    $this->dispatcher->removeListener('notExists', $this->listener);
  }

  public function testAddSubscriber() {
    $eventSubscriber = new TestEventSubscriber();
    $this->dispatcher->addSubscriber($eventSubscriber);
    $this->assertTrue($this->dispatcher->hasListeners(self::PREFOO));
    $this->assertTrue($this->dispatcher->hasListeners(self::POSTFOO));
  }

  public function testAddSubscriberWithPriorities() {
    $eventSubscriber = new TestEventSubscriber();
    $this->dispatcher->addSubscriber($eventSubscriber);

    $eventSubscriber = new TestEventSubscriberWithPriorities();
    $this->dispatcher->addSubscriber($eventSubscriber);

    
$dispatcherDefinitions[$attributes['dispatcher']] = $container->findDefinition($attributes['dispatcher']);
            }

            if (!$dispatcherDefinitions) {
                $dispatcherDefinitions = [$globalDispatcherDefinition];
            }

            $noPreload = 0;
            ExtractingEventDispatcher::$aliases = $aliases;
            ExtractingEventDispatcher::$subscriber = $class;
            $extractingDispatcher->addSubscriber($extractingDispatcher);
            foreach ($extractingDispatcher->listeners as $args) {
                $args[1] = [new ServiceClosureArgument(new Reference($id))$args[1]];
                foreach ($dispatcherDefinitions as $dispatcherDefinition) {
                    $dispatcherDefinition->addMethodCall('addListener', $args);
                }

                if (isset($this->hotPathEvents[$args[0]])) {
                    $container->getDefinition($id)->addTag('container.hot_path');
                } elseif (isset($this->noPreloadEvents[$args[0]])) {
                    ++$noPreload;
                }
            }
/** * @param callable $listener can not use native type declaration @see https://github.com/symfony/symfony/issues/42283 */
    public function addListener(string $eventName$listener, int $priority = 0): void // @phpstan-ignore-line     {
        /** @var callable(object): void $listener - Specify generic callback interface callers can provide more specific implementations */
        $this->dispatcher->addListener($eventName$listener$priority);
    }

    public function addSubscriber(EventSubscriberInterface $subscriber): void
    {
        $this->dispatcher->addSubscriber($subscriber);
    }

    public function removeListener(string $eventName, callable $listener): void
    {
        /** @var callable(object): void $listener - Specify generic callback interface callers can provide more specific implementations */
        $this->dispatcher->removeListener($eventName$listener);
    }

    public function removeSubscriber(EventSubscriberInterface $subscriber): void
    {
        $this->dispatcher->removeSubscriber($subscriber);
    }
'alias' => 'handler_that_works2',
                ]),
            ],
        ]);

        $dispatcher = new EventDispatcher();
        $bus = new MessageBus([
            new FailedMessageProcessingMiddleware(),
            new SendMessageMiddleware($senderLocator),
            new HandleMessageMiddleware($handlerLocator),
        ]);
        $dispatcher->addSubscriber(new AddErrorDetailsStampListener());
        $dispatcher->addSubscriber(new SendFailedMessageForRetryListener($locator$retryStrategyLocator));

        $dispatcher->addSubscriber(new SendFailedMessageToFailureTransportListener($sendersLocatorFailureTransport));
        $dispatcher->addSubscriber(new StopWorkerOnMessageLimitListener(1));

        $runWorker = function Dstring $transportName) use ($transports$bus$dispatcher): ?\Throwable {
            $throwable = null;
            $failedListener = function DWorkerMessageFailedEvent $event) use (&$throwable) {
                $throwable = $event->getThrowable();
            };
            $dispatcher->addListener(WorkerMessageFailedEvent::class$failedListener);

            
$mock->expects(static::exactly(2))
            ->method('load')
            ->willReturn($expectedConfig);

        $configStore = new MemoizedSystemConfigStore();
        $service = new MemoizedSystemConfigLoader($mock$configStore);

        $config = $service->load(TestDefaults::SALES_CHANNEL);
        static::assertSame($expectedConfig$config);

        $dispatcher = new EventDispatcher();
        $dispatcher->addSubscriber($configStore);

        // Dispatching the event resets the memoization and ensures load is called a second time.         $dispatcher->dispatch(new SystemConfigChangedEvent('abc.config.foo', 'none', TestDefaults::SALES_CHANNEL));

        // The load method is now called a second time as memoization has been reset for the sales channel.         $config = $service->load(TestDefaults::SALES_CHANNEL);
        static::assertSame($expectedConfig$config);
    }

    public function testMemoizationResetsOnValueChangeEventWithoutSalesChannelId(): void
    {
        
/** * @param callable $listener can not use native type declaration @see https://github.com/symfony/symfony/issues/42283 */
    public function addListener(string $eventName$listener, int $priority = 0): void // @phpstan-ignore-line     {
        /** @var callable(object): void $listener - Specify generic callback interface callers can provide more specific implementations */
        $this->dispatcher->addListener($eventName$listener$priority);
    }

    public function addSubscriber(EventSubscriberInterface $subscriber): void
    {
        $this->dispatcher->addSubscriber($subscriber);
    }

    public function removeListener(string $eventName, callable $listener): void
    {
        /** @var callable(object): void $listener - Specify generic callback interface callers can provide more specific implementations */
        $this->dispatcher->removeListener($eventName$listener);
    }

    public function removeSubscriber(EventSubscriberInterface $subscriber): void
    {
        $this->dispatcher->removeSubscriber($subscriber);
    }
$eventDispatcherMock,
            $this->getContainer()->get(Connection::class),
            $this->getContainer()->get('shopware.app_system.guzzle'),
            $this->shopUrl,
            $this->getContainer(),
            $this->getContainer()->get(HookableEventFactory::class),
            Kernel::SHOPWARE_FALLBACK_VERSION,
            $this->bus,
            true
        );

        $webhookDispatcher->addSubscriber(new MockSubscriber());
    }

    public function testRemoveSubscriber(): void
    {
        $eventDispatcherMock = $this->createMock(EventDispatcher::class);
        $eventDispatcherMock->expects(static::once())
            ->method('removeSubscriber');

        $webhookDispatcher = new WebhookDispatcher(
            $eventDispatcherMock,
            $this->getContainer()->get(Connection::class),
            

        );

        $storefrontPluginRegistry = $this->getStorefrontPluginRegistry(
            [
                new SimplePlugin(true, __DIR__ . '/fixtures/SimplePlugin'),
            ]
        );

        $subscriber = new ThemeCompilerEnrichScssVarSubscriber($configService$storefrontPluginRegistry);

        $this->eventDispatcher->addSubscriber($subscriber);

        /** @var SystemConfigService $sysConfService */
        $sysConfService = $this->getContainer()->get(SystemConfigService::class);
        $sysConfService->set('SimplePlugin.config.simplePluginBackgroundcolor', '#fff');
        $sysConfService->set('SwagNoThemeCustomCss.config.noThemeCustomCssBackGroundcolor', '#aaa');

        try {
            $actual = $compileStyles->invoke(
                $this->themeCompiler,
                $testScss,
                new StorefrontPluginConfiguration('test'),
                [],
$this->dispatcher->addListener($eventName$listener$priority);

        return $this;
    }

    public function addEventSubscriber(EventSubscriberInterface $subscriber)static
    {
        if ($this->locked) {
            throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.');
        }

        $this->dispatcher->addSubscriber($subscriber);

        return $this;
    }

    public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false)static
    {
        if ($this->locked) {
            throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.');
        }

        if ($forcePrepend) {
            

    public function addListener(string $eventName, callable|array $listener, int $priority = 0)
    {
        $this->dispatcher->addListener($eventName$listener$priority);
    }

    /** * @return void */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->dispatcher->addSubscriber($subscriber);
    }

    /** * @return void */
    public function removeListener(string $eventName, callable|array $listener)
    {
        if (isset($this->wrappedListeners[$eventName])) {
            foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
                if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) {
                    $listener = $wrappedListener;
                    
public function testNotRenderedTemplatedEmail()
    {
        $this->expectException(LogicException::class);

        $transport = new NullTransport(new EventDispatcher());
        $transport->send((new TemplatedEmail())->htmlTemplate('Some template'));
    }

    public function testRenderedTemplatedEmail()
    {
        $transport = new NullTransport($dispatcher = new EventDispatcher());
        $dispatcher->addSubscriber(new MessageListener(null, new BodyRenderer(new Environment(new ArrayLoader(['tpl' => 'Some message'])))));

        $sentMessage = $transport->send((new TemplatedEmail())->to('me@example.com')->from('me@example.com')->htmlTemplate('tpl'));
        $this->assertMatchesRegularExpression('/Some message/', $sentMessage->getMessage()->toString());
    }

    public function testRejectMessage()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(MessageEvent::classfn (MessageEvent $event) => $event->reject(), 255);
        $dispatcher->addListener(MessageEvent::classfn () => throw new \RuntimeException('Should never be called.'));

        
$mediaService = $this->createMock(MediaService::class);
        $fileSaver = $this->createMock(FileSaver::class);

        $mediaFolderRepository = $this->createMock(EntityRepository::class);
        $mediaRepository = $this->createMock(EntityRepository::class);

        $mediaSerializer = new MediaSerializer($mediaService$fileSaver$mediaFolderRepository$mediaRepository);
        $mediaSerializer->setRegistry($serializerRegistry);

        $eventDispatcher = new EventDispatcher();
        $eventDispatcher->addSubscriber(new MediaSerializerSubscriber($mediaSerializer));

        $mediaId = Uuid::randomHex();
        $expectedDestination = 'shopware-logo';
        $record = [
            'id' => $mediaId,
            'title' => 'Logo',
            'url' => 'http://172.16.11.80/shopware-logo.png',
            'mediaFolderId' => Uuid::randomHex(),
        ];

        $expectedMediaFile = new MediaFile(
            


    /** * @requires extension pcntl */
    public function testSignalSubscriberNotCalledByDefault()
    {
        $command = new BaseSignableCommand(false);

        $subscriber = new SignalEventSubscriber();
        $dispatcher = new EventDispatcher();
        $dispatcher->addSubscriber($subscriber);

        $application = $this->createSignalableApplication($command$dispatcher);

        $this->assertSame(0, $application->run(new ArrayInput(['signal'])));
        $this->assertFalse($subscriber->signaled);
    }

    /** * @requires extension pcntl */
    public function testSignalSubscriber()
    {
public function testConsoleEvent()
    {
        $dispatcher = new EventDispatcher();
        $listener = new DebugHandlersListener(null);
        $app = $this->createMock(Application::class);
        $app->expects($this->once())->method('getHelperSet')->willReturn(new HelperSet());
        $command = new Command(__FUNCTION__);
        $command->setApplication($app);
        $event = new ConsoleEvent($commandnew ArgvInput()new ConsoleOutput());

        $dispatcher->addSubscriber($listener);

        $xListeners = [
            KernelEvents::REQUEST => [[$listener, 'configure']],
            ConsoleEvents::COMMAND => [[$listener, 'configure']],
        ];
        $this->assertSame($xListeners$dispatcher->getListeners());

        $exception = null;
        $eHandler = new ErrorHandler();
        set_error_handler([$eHandler, 'handleError']);
        set_exception_handler([$eHandler, 'handleException']);
        
Home | Imprint | This part of the site doesn't use cookies.