addEventListener example

/** * @return string */
    public function getBlockPrefix()
    {
        return 'address';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function DFormEvent $event) {
            $data = $event->getData();
            array_walk_recursive($datafunction D&$item) {
                $item = strip_tags((string) $item);
            });
            $event->setData($data);
        });

        if ($this->config->get('shopSalutationRequired')) {
            $builder->add('salutation', SalutationType::class[
                'constraints' => [new NotBlank(['message' => null])],
            ]);
        }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!$options['sanitize_html']) {
            return;
        }

        $sanitizers = $this->sanitizers;
        $sanitizer = $options['sanitizer'] ?? $this->defaultSanitizer;

        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            static function DFormEvent $event) use ($sanitizers$sanitizer) {
                if (\is_scalar($data = $event->getData()) && '' !== trim($data)) {
                    $event->setData($sanitizers->get($sanitizer)->sanitize($data));
                }
            },
            10000 /* as soon as possible */
        );
    }
}
 elseif ('timestamp' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToTimestampTransformer($options['model_timezone']$options['model_timezone'])
            ));
        } elseif ('array' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToArrayTransformer($options['model_timezone']$options['model_timezone']['year', 'month', 'day'])
            ));
        }

        if (\in_array($options['input']['datetime', 'datetime_immutable'], true) && null !== $options['model_timezone']) {
            $builder->addEventListener(FormEvents::POST_SET_DATA, static function DFormEvent $event) use ($options): void {
                $date = $event->getData();

                if (!$date instanceof \DateTimeInterface) {
                    return;
                }

                if ($date->getTimezone()->getName() !== $options['model_timezone']) {
                    trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class$date->getTimezone()->getName()$options['model_timezone']));
                    // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));                 }
            });
        }
/** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!$options['html5']) {
            return;
        }

        $translator = $this->translator;
        $builder->addEventListener(FormEvents::PRE_SUBMIT, static function DFormEvent $event) use ($translator): void {
            $value = $event->getData();
            if (null === $value || '' === $value) {
                return;
            }

            if (\is_string($value) && preg_match(self::HTML5_PATTERN, $value)) {
                return;
            }

            $messageTemplate = 'This value is not a valid HTML5 color.';
            $messageParameters = [
                


        if ($salesChannelData) {
            $data = array_merge($data$salesChannelData);
        }

        return $this->createContext($data[]);
    }

    protected function catchEvent(string $eventName, ?object &$eventResult): void
    {
        $this->addEventListener($this->getContainer()->get('event_dispatcher')$eventNamestatic function D$event) use (&$eventResult): void {
            $eventResult = $event;
        });
    }

    abstract protected static function getContainer(): ContainerInterface;

    private function createCustomer(): CustomerEntity
    {
        $customerId = Uuid::randomHex();
        $addressId = Uuid::randomHex();

        
$eventDidRun,
            $phpunit,
            $context,
            $request
        ): void {
            $eventDidRun = true;
            $phpunit->assertEquals($context$event->getSalesChannelContext());
            $phpunit->assertEquals($request$event->getRequest());
            $phpunit->assertEquals(3, $event->getPagelet()->getSearchResult()->getProducts()->count());
        };

        $this->addEventListener($this->eventDispatcher, GuestWishlistPageletLoadedEvent::class$listenerClosure);

        $page = $this->getPageLoader()->load($request$context);

        static::assertInstanceOf(GuestWishlistPagelet::class$page);
        $phpunit->assertEquals(3, $page->getSearchResult()->getProducts()->count());
        static::assertTrue($eventDidRun);
    }

    public function testCriteria(): void
    {
        $productId = Uuid::randomHex();
        

    public function testSendMailWithDomainAndLeadingSlash(array $domainUrlTest): void
    {
        $this->createCustomer('foo-test@test.de');

        $this->addDomain($domainUrlTest['domain']);

        $caughtEvent = null;
        $this->addEventListener(
            $this->getContainer()->get('event_dispatcher'),
            CustomerAccountRecoverRequestEvent::EVENT_NAME,
            static function DCustomerAccountRecoverRequestEvent $event) use (&$caughtEvent): void {
                $caughtEvent = $event;
            }
        );

        $this->browser
            ->request(
                'POST',
                '/store-api/account/recovery-password',
                [
$this->getContainer()->get('cache.object')
            ->invalidateTags([CachedSalutationRoute::ALL_TAG]);

        $route = $this->getContainer()->get(SalutationRoute::class);

        static::assertInstanceOf(CachedSalutationRoute::class$route);

        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $listener = $this->getMockBuilder(CallableClass::class)->getMock();

        $listener->expects(static::exactly($calls))->method('__invoke');
        $this->addEventListener($dispatcher, 'salutation.loaded', $listener);

        $before($this->getContainer());

        $route->load(new Request()$this->context, new Criteria());
        $route->load(new Request()$this->context, new Criteria());

        $after($this->getContainer());

        $route->load(new Request()$this->context, new Criteria());
        $route->load(new Request()$this->context, new Criteria());
    }

    
public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Customer::class,
            'allow_extra_fields' => true,
        ]);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function DFormEvent $event) {
            $whitelist = [
                'password',
                'passwordConfirmation',
            ];

            $data = $event->getData();

            array_walk_recursive($datafunction D&$item$key) use ($whitelist) {
                if (\in_array($key$whitelist, true)) {
                    return $item;
                }
                
'salesChannelId' => TestDefaults::SALES_CHANNEL, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
            ],
        ];

        $this->getContainer()->get('product.repository')
            ->create([$product]$context);
    }

    public function testCreateNewWithEvent(): void
    {
        $caughtEvent = null;
        $this->addEventListener($this->getContainer()->get('event_dispatcher'), CartCreatedEvent::classstatic function DCartCreatedEvent $event) use (&$caughtEvent): void {
            $caughtEvent = $event;
        });

        $cartService = $this->getContainer()->get(CartService::class);

        $token = Uuid::randomHex();
        $newCart = $cartService->createNew($token);

        static::assertInstanceOf(CartCreatedEvent::class$caughtEvent);
        static::assertSame($newCart$caughtEvent->getCart());
        static::assertSame($newCart$cartService->getCart($token$this->getSalesChannelContext()));
        
$context = Context::createDefaultContext();
        $context->addState(EntityIndexerRegistry::DISABLE_INDEXING);
        $mailSent = false;

        $eventDispatcher = $this->getContainer()->get('event_dispatcher');

        $listenerClosure = function DMailSentEvent $event) use (&$mailSent): void {
            $mailSent = true;
        };

        $this->addEventListener($eventDispatcher, MailSentEvent::class$listenerClosure);

        $progress = $this->import($context, CustomerDefinition::ENTITY_NAME, '/fixtures/customers.csv', 'customers.csv');
        $eventDispatcher->removeListener(MailSentEvent::class$listenerClosure);

        static::assertTrue($context->hasState(Context::SKIP_TRIGGER_FLOW));
        static::assertFalse($mailSent, 'The mail.sent Event did run');

        static::assertImportExportSucceeded($progress$this->getInvalidLogContent($progress->getInvalidRecordsLogId()));

        $criteria = new Criteria();
        $criteria->addAssociation('addresses');
        
foreach ($attributes as $attribute) {
            if ($attribute->isIdentifier()) {
                continue;
            }

            $field = $metaData->getFieldForColumn($attribute->getColumnName());
            $builder->add($field);
        }

        // set default value for all attribute fields to prevent null override if a field isn't in the submit data         $builder->addEventListener(FormEvents::POST_SET_DATA, function DFormEvent $event) use ($attributes$metaData) {
            try {
                $form = $event->getForm();
                $data = $event->getData();

                if (!$data instanceof ModelEntity) {
                    return;
                }

                foreach ($attributes as $attribute) {
                    if ($attribute->isIdentifier()) {
                        continue;
                    }
'/store-api/checkout/order',
            );

        $response = \json_decode($this->browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertNotNull($response['orderCustomer']);
        static::assertNull($response['orderCustomer']['salutationId']);
    }

    protected function catchEvent(string $eventName, ?Event &$eventResult): void
    {
        $this->addEventListener($this->getContainer()->get('event_dispatcher')$eventNamestatic function DEvent $event) use (&$eventResult): void {
            $eventResult = $event;
        });
    }

    private function createTestData(): void
    {
        $this->addCountriesToSalesChannel();

        $this->productRepository->create([
            [
                'id' => $this->ids->create('p1'),
                
public function __construct(
        private PasswordHasherListener $passwordHasherListener,
    ) {
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($options['hash_property_path']) {
            $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'registerPassword']);
        }
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'hash_property_path' => null,
        ]);

        
public function testGenerateUserRecoveryWithNotExistingSalesChannelLanguage(): void
    {
        $this->createRecovery(self::VALID_EMAIL);

        $this->context->assign([
            'languageIdChain' => [Uuid::randomHex()],
        ]);

        $eventDispatched = false;
        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $this->addEventListener($dispatcher, UserRecoveryRequestEvent::EVENT_NAME, function DUserRecoveryRequestEvent $event) use (&$eventDispatched): void {
            $eventDispatched = true;
        });

        $this->userRecoveryService->generateUserRecovery(self::VALID_EMAIL, $this->context);

        static::assertTrue($eventDispatched);
    }

    public function testGenerateUserRecoveryWithExistingUser(): void
    {
        $this->createRecovery(self::VALID_EMAIL);

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