getFlashBag example


        $context = Context::createDefaultContext();
        $customer = $this->createCustomer($context);

        $browser = $this->login($customer->getEmail());

        $browser->request('POST', $_SERVER['APP_URL'] . '/account/profile/delete');

        /** @var StorefrontResponse $response */
        $response = $browser->getResponse();

        static::assertArrayHasKey('success', $this->getFlashBag()->all());
        static::assertTrue($response->isRedirect()(string) $response->getContent());
    }

    public function testAccountOverviewPageLoadedScriptsAreExecuted(): void
    {
        $context = Context::createDefaultContext();
        $customer = $this->createCustomer($context);

        $browser = $this->login($customer->getEmail());

        $browser->request('GET', '/account');
        

    public function toolbarAction(Request $request, string $token = null): Response
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        if (!$request->attributes->getBoolean('_stateless') && $request->hasSession()
            && ($session = $request->getSession())->isStarted() && $session->getFlashBag() instanceof AutoExpireFlashBag
        ) {
            // keep current flashes for one more request if using AutoExpireFlashBag             $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
        }

        if ('empty' === $token || null === $token) {
            return new Response('', 200, ['Content-Type' => 'text/html']);
        }

        $this->profiler->disable();

        
use IntegrationTestBehaviour;
    use StorefrontControllerTestBehaviour;
    use StorefrontSalesChannelTestHelper;

    /** * @before * * @after */
    public function clearFlashBag(): void
    {
        $this->getFlashBag()->clear();
    }

    /** * @dataProvider productNumbers */
    public function testAddAndDeleteProductByNumber(string $productId, string $productNumber, bool $available = true): void
    {
        $contextToken = Uuid::randomHex();

        $cartService = $this->getContainer()->get(CartService::class);
        if ($productId && $available) {
            
$productLineItem1->setQuantity(1);
        $guestProductQuantity = 5;
        $productLineItem2->setQuantity($guestProductQuantity);

        $previousCart->addLineItems(new LineItemCollection([$productLineItem1$productLineItem2]));
        $previousCart->markUnmodified();

        $cartMergedEvent = new CartMergedEvent(new Cart('customerToken')$currentContext$previousCart);

        $subscriber->addCartMergedNoticeFlash($cartMergedEvent);

        static::assertNotEmpty($infoFlash = $session->getFlashBag()->get('info'));

        static::assertEquals('checkout.cart-merged-hint', $infoFlash[0]);
    }

    /** * @param array<string, mixed> $salesChannelData */
    private function createSalesChannelContext(string $contextToken, array $salesChannelData, ?string $customerId = null): SalesChannelContext
    {
        if ($customerId) {
            $salesChannelData[SalesChannelContextService::CUSTOMER_ID] = $customerId;
        }
public function notify(Notification $notification, RecipientInterface $recipient, string $transportName = null): void
    {
        if (null === $request = $this->stack->getCurrentRequest()) {
            return;
        }

        $message = $notification->getSubject();
        if ($notification->getEmoji()) {
            $message = $notification->getEmoji().' '.$message;
        }
        $request->getSession()->getFlashBag()->add($this->mapper->flashMessageTypeFromImportance($notification->getImportance())$message);
    }

    public function supports(Notification $notification, RecipientInterface $recipient): bool
    {
        return true;
    }
}
string $expectedFlashMessageType
    ) {
        $session = $this->createMock(Session::class);
        $session->method('getFlashBag')->willReturn(new FlashBag());
        $browserChannel = $this->buildBrowserChannel($session$mapper);
        $notification = new Notification();
        $notification->importance($importance);
        $recipient = new Recipient('hello@example.com');

        $browserChannel->notify($notification$recipient);

        $this->assertEquals($expectedFlashMessageTypearray_key_first($session->getFlashBag()->all()));
    }

    public function testUnknownImportanceMappingIsReported()
    {
        $session = $this->createMock(Session::class);
        $session->method('getFlashBag')->willReturn(new FlashBag());
        $browserChannel = $this->buildBrowserChannel($sessionnew DefaultFlashMessageImportanceMapper());
        $notification = new Notification();
        $notification->importance('unknown-importance-string');
        $recipient = new Recipient('hello@example.com');

        
$groups = [
            'info' => $errors->getNotices(),
            'warning' => $errors->getWarnings(),
            'danger' => $errors->getErrors(),
        ];

        $request = $this->container->get('request_stack')->getMainRequest();
        $exists = [];

        if ($request && $request->hasSession() && $request->getSession() instanceof FlashBagAwareSessionInterface) {
            $exists = $request->getSession()->getFlashBag()->peekAll();
        }

        $flat = [];
        foreach ($exists as $messages) {
            $flat = array_merge($flat$messages);
        }

        /** @var array<string, Error[]> $groups */
        foreach ($groups as $type => $errors) {
            foreach ($errors as $error) {
                $parameters = [];

                
$requestDataBag = new RequestDataBag();
        $requestDataBag->set('username', $customer->getEmail());
        $requestDataBag->set('password', 'test12345');

        $salesChannelContextNew = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL
        );

        $this->getContainer()->get(AuthController::class)->login($request$requestDataBag$salesChannelContextNew);
        $flashBag = $session->getFlashBag();

        static::assertNotEmpty($infoFlash = $flashBag->get('danger'));
        static::assertEquals($this->getContainer()->get('translator')->trans('checkout.product-not-found', ['%s%' => 'Test product'])$infoFlash[0]);
    }

    public function testAccountLoginPageLoadedHookScriptsAreExecuted(): void
    {
        $this->request('GET', '/account/login', []);

        $traces = $this->getContainer()->get(ScriptTraces::class)->getTraces();

        
public function logoutAction(Request $request)
    {
        $request->getSession()->invalidate();

        return new Response('<html><body>Session cleared.</body></html>');
    }

    public function setFlashAction(Request $request$message)
    {
        $session = $request->getSession();
        $session->getFlashBag()->set('notice', $message);

        return new RedirectResponse($this->container->get('router')->generate('session_showflash'));
    }

    public function showFlashAction(Request $request)
    {
        $session = $request->getSession();

        if ($session->getFlashBag()->has('notice')) {
            [$output] = $session->getFlashBag()->get('notice');
        } else {
            
$sessionMetadata = [];
        $sessionAttributes = [];
        $flashes = [];
        if ($request->hasSession()) {
            $session = $request->getSession();
            if ($session->isStarted()) {
                $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated());
                $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed());
                $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
                $sessionAttributes = $session->all();
                $flashes = $session->getFlashBag()->peekAll();
            }
        }

        $statusCode = $response->getStatusCode();

        $responseCookies = [];
        foreach ($response->headers->getCookies() as $cookie) {
            $responseCookies[$cookie->getName()] = $cookie;
        }

        $dotenvVars = [];
        
$systemConfig = $this->getContainer()->get(SystemConfigService::class);
        $systemConfig->set('core.cart.wishlistEnabled', true);
    }

    /** * @before * * @after */
    public function clearFlashBag(): void
    {
        $this->getFlashBag()->clear();
    }

    public function testWishlistIndex(): void
    {
        $browser = $this->login();

        $salesChannelId = $browser->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);

        $productId = $this->createProduct($salesChannelId);

        // add product to wishlist
 catch (\RuntimeException) {
            return [];
        }

        // In 7.0 (when symfony/http-foundation: 6.4 is required) this can be updated to         // check if the session is an instance of FlashBagAwareSessionInterface         if (!method_exists($session, 'getFlashBag')) {
            return [];
        }

        if (null === $types || '' === $types || [] === $types) {
            return $session->getFlashBag()->all();
        }

        if (\is_string($types)) {
            return $session->getFlashBag()->get($types);
        }

        $result = [];
        foreach ($types as $type) {
            $result[$type] = $session->getFlashBag()->get($type);
        }

        
$this->errorTemplateResolver = $errorTemplateResolver;
    }

    public function error(\Throwable $exception, Request $request, SalesChannelContext $context): Response
    {
        $session = $request->hasSession() ? $request->getSession() : null;

        try {
            $is404StatusCode = $exception instanceof HttpException
                && $exception->getStatusCode() === Response::HTTP_NOT_FOUND;

            if (!$is404StatusCode && $session !== null && method_exists($session, 'getFlashBag') && !$session->getFlashBag()->has('danger')) {
                $session->getFlashBag()->add('danger', $this->trans('error.message-default'));
            }

            $request->attributes->set('navigationId', $context->getSalesChannel()->getNavigationCategoryId());

            $salesChannelId = $context->getSalesChannel()->getId();
            $cmsErrorLayoutId = $this->systemConfigService->getString('core.basicInformation.http404Page', $salesChannelId);
            if ($cmsErrorLayoutId !== '' && $is404StatusCode) {
                $errorPage = $this->errorPageLoader->load($cmsErrorLayoutId$request$context);

                $response = $this->renderStorefront(
                    
trait SessionTestBehaviour
{
    /** * @after */
    public function clearSession(): void
    {
        $session = $this->getSession();
        $session->clear();

        if ($session instanceof FlashBagAwareSessionInterface) {
            $session->getFlashBag()->clear();
        }
    }

    public function getSession(): SessionInterface
    {
        /** @var SessionFactoryInterface $factory */
        $factory = $this->getContainer()->get('session.factory');

        return $factory->createSession();
    }
}

        try {
            $session = $this->container->get('request_stack')->getSession();
        } catch (SessionNotFoundException $e) {
            throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".', 0, $e);
        }

        if (!$session instanceof FlashBagAwareSessionInterface) {
            trigger_deprecation('symfony/framework-bundle', '6.2', 'Calling "addFlash()" method when the session does not implement %s is deprecated.', FlashBagAwareSessionInterface::class);
        }

        $session->getFlashBag()->add($type$message);
    }

    /** * Checks if the attribute is granted against the current authentication token and optionally supplied subject. * * @throws \LogicException */
    protected function isGranted(mixed $attribute, mixed $subject = null): bool
    {
        if (!$this->container->has('security.authorization_checker')) {
            throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
        }
Home | Imprint | This part of the site doesn't use cookies.