RedirectResponse example

try {
            return $this->paymentProcessor->process($orderId$dataBag$context$finishUrl$errorUrl);
        } catch (PaymentProcessException|PaymentException $e) {
            $transactionId = $e->getOrderTransactionId();
            $this->logger->error('An error occurred during processing the payment', ['orderTransactionId' => $transactionId, 'exceptionMessage' => $e->getMessage()]);
            if ($transactionId !== null) {
                $this->transactionStateHandler->fail($transactionId$context->getContext());
            }
            if ($errorUrl !== null) {
                $errorUrl .= (parse_url($errorUrl, \PHP_URL_QUERY) ? '&' : '?') . 'error-code=' . $e->getErrorCode();

                return new RedirectResponse($errorUrl);
            }

            throw $e;
        }
    }

    public function finalizeTransaction(string $paymentToken, Request $request, SalesChannelContext $context): TokenStruct
    {
        $token = $this->tokenFactory->parseToken($paymentToken);

        if ($token->isExpired()) {
            
/** * @internal */
#[Route(defaults: ['_routeScope' => ['api']])] class MediaFileFetchRedirectTestController extends AbstractController
{
    #[Route(path: '/api/_action/redirect-to-echo', name: 'api.action.test.redirect-to-echo', defaults: ['auth_required' => false], methods: ['GET'])]     public function redirectAction(Request $request): RedirectResponse
    {
        $parameters = $request->query->all();

        $response = new RedirectResponse($this->generateUrl('api.action.test.echo_json', $parameters));
        // only send location header         $response->setContent('');

        return $response;
    }

    #[Route(path: '/api/_action/echo-json', name: 'api.action.test.echo_json', defaults: ['auth_required' => false], methods: ['GET'])]     public function echoJsonAction(Request $request): JsonResponse
    {
        $data = [
            'headers' => $request->headers->all(),
            
$this->stateMachineRegistry->transition(
                new Transition(
                    OrderTransactionDefinition::ENTITY_NAME,
                    $transaction->getOrderTransaction()->getId(),
                    $response->getStatus(),
                    'stateId'
                ),
                $salesChannelContext->getContext()
            );
        }

        return new RedirectResponse($response->getRedirectUrl());
    }

    public function finalize(AsyncPaymentTransactionStruct $transaction, Request $request, SalesChannelContext $salesChannelContext): void
    {
        $queryParameters = $request->query->all();
        unset($queryParameters['_sw_payment_token']);

        $payload = $this->buildFinalizePayload($transaction$queryParameters);
        $app = $this->getAppPaymentMethod($transaction->getOrderTransaction())->getApp();
        if ($app === null) {
            throw PaymentException::asyncFinalizeInterrupted($transaction->getOrderTransaction()->getId(), 'App not defined');
        }
$context,
                $customer
            );
        } catch (UnknownPaymentMethodException|InvalidUuidException|PaymentException $exception) {
            $this->addFlash(self::DANGER, $this->trans('error.' . $exception->getErrorCode()));

            return $this->forwardToRoute('frontend.account.payment.page', ['success' => false]);
        }

        $this->addFlash(self::SUCCESS, $this->trans('account.paymentSuccess'));

        return new RedirectResponse($this->generateUrl('frontend.account.payment.page'));
    }
}
$routerContext->setMethod('GET');
        $routerContext->setHost($parsedUrl['host']);
        $routerContext->setBaseUrl(rtrim($parsedUrl['path'] ?? '', '/'));

        if ($this->requestStack->getMainRequest()) {
            $this->requestStack->getMainRequest()
                ->attributes->set(RequestTransformer::SALES_CHANNEL_BASE_URL, '');
        }

        $url = $this->router->generate($route$params, Router::ABSOLUTE_URL);

        return new RedirectResponse($url);
    }
}
if ($type === self::ADDRESS_TYPE_SHIPPING) {
                $this->accountService->setDefaultShippingAddress($addressId$context$customer);
            } elseif ($type === self::ADDRESS_TYPE_BILLING) {
                $this->accountService->setDefaultBillingAddress($addressId$context$customer);
            } else {
                $success = false;
            }
        } catch (AddressNotFoundException) {
            $success = false;
        }

        return new RedirectResponse(
            $this->generateUrl('frontend.account.address.page', ['changedDefaultAddress' => $success])
        );
    }

    #[Route(path: '/account/address/delete/{addressId}', name: 'frontend.account.address.delete', options: ['seo' => false], defaults: ['_loginRequired' => true], methods: ['POST'])]     public function deleteAddress(string $addressId, SalesChannelContext $context, CustomerEntity $customer): Response
    {
        $success = true;

        if (!$addressId) {
            throw RoutingException::missingRequestParameter('addressId');
        }
$request,
            $salesChannelContext
        );

        $response = $this->handleException($result);
        if ($response !== null) {
            return $response;
        }

        $finishUrl = $result->getFinishUrl();
        if ($finishUrl) {
            return new RedirectResponse($finishUrl);
        }

        return new JsonResponse(null, Response::HTTP_NO_CONTENT);
    }

    private function handleException(TokenStruct $token): ?Response
    {
        if ($token->getException() === null) {
            return null;
        }

        
if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
            return;
        }

        $request = $event->getRequest();

        $parameters = [
            'redirectTo' => $request->attributes->get('_route'),
            'redirectParameters' => json_encode($request->attributes->get('_route_params'), \JSON_THROW_ON_ERROR),
        ];

        $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page', $parameters));

        $event->setResponse($redirectResponse);
    }

    public function maintenanceResolver(RequestEvent $event): void
    {
        if ($this->maintenanceModeResolver->shouldRedirect($event->getRequest())) {
            $event->setResponse(
                new RedirectResponse(
                    $this->router->generate('frontend.maintenance.page'),
                    RedirectResponse::HTTP_TEMPORARY_REDIRECT
                )
$response = $this->downloadResponseGenerator->getResponse($media$this->salesChannelContext);

        $response->headers->set('date', null);
        $expectedResponse->headers->set('date', null);

        static::assertEquals($expectedResponse$response);
    }

    public static function filesystemProvider(): \Generator
    {
        yield 'private / aws' => [true, 'external', 'external', new RedirectResponse('foobar.txt')];
        yield 'public / aws' => [false, 'external', 'external', new RedirectResponse('foobar.txt')];
        yield 'private / google' => [true, 'external', 'external', new RedirectResponse('foobar.txt')];
        yield 'public / google' => [false, 'external', 'external', new RedirectResponse('foobar.txt')];
        yield 'private / local / php' => [true, 'local', 'local', self::getExpectedStreamResponse()];
        yield 'private / local / x-sendfile' => [
            true,
            'local',
            'local',
            self::getExpectedStreamResponse('X-Sendfile'),
            DownloadResponseGenerator::X_SENDFILE_DOWNLOAD_STRATEGRY,
        ];
        
private function registerHandler(string $handler): ServiceLocator
    {
        $class = match ($handler) {
            SynchronousPaymentHandlerInterface::class => new class() implements SynchronousPaymentHandlerInterface {
                public function pay(SyncPaymentTransactionStruct $transaction, RequestDataBag $dataBag, SalesChannelContext $salesChannelContext): void
                {
                }
            },
            AsynchronousPaymentHandlerInterface::class => new class() implements AsynchronousPaymentHandlerInterface {
                public function pay(AsyncPaymentTransactionStruct $transaction, RequestDataBag $dataBag, SalesChannelContext $salesChannelContext): RedirectResponse
                {
                    return new RedirectResponse('https://example.com');
                }

                public function finalize(AsyncPaymentTransactionStruct $transaction, Request $request, SalesChannelContext $salesChannelContext): void
                {
                }
            },
            PreparedPaymentHandlerInterface::class => new class() implements PreparedPaymentHandlerInterface {
                public function validate(Cart $cart, RequestDataBag $requestDataBag, SalesChannelContext $context): Struct
                {
                    return new ArrayStruct();
                }

                
$cartPage->setCart($cart);

        $this->cartPageLoaderMock->method('load')->willReturn(
            $cartPage
        );

        $request = new Request();
        $request->query->set('redirected', false);

        $response = $this->controller->cartPage($request$this->createMock(SalesChannelContext::class));

        static::assertEquals(new RedirectResponse('url')$response);
    }

    public function testGetCartRedirectOnShippingErrorsPreventLoop(): void
    {
        $cart = new Cart(Uuid::randomHex());
        $cart->addErrors(new ShippingMethodChangedError('old', 'new'));

        $cartPage = new CheckoutCartPage();
        $cartPage->setCart($cart);

        $this->cartPageLoaderMock->method('load')->willReturn(
            
$container = new ContainerBuilder();
        $container->set('event_dispatcher', static::createMock(EventDispatcherInterface::class));
        $container->set('router', $router);

        $this->controller->setContainer($container);

        $response = $this->controller->editOrder($ids->get('order')new Request(), Generator::createSalesChannelContext());

        // Ensure flash massage is shown         static::assertEquals('danger error.CHECKOUT__ORDER_ORDER_NOT_FOUND', $this->controller->flash);
        static::assertEquals(new RedirectResponse('http://localhost/account/order')$response);
    }

    public function testEditOrderInvalidUuid(): void
    {
        // Ensure it redirects to the correct route         $router = static::createMock(RouterInterface::class);
        $router
            ->expects(static::once())
            ->method('generate')
            ->with('frontend.account.order.page')
            ->willReturn('http://localhost/account/order');

        
$this->addFlash('danger', $message);

            return $this->forwardToRoute('frontend.checkout.confirm.page');
        }

        try {
            $finishUrl = $this->generateUrl('frontend.checkout.finish.page', ['orderId' => $orderId]);
            $errorUrl = $this->generateUrl('frontend.account.edit-order.page', ['orderId' => $orderId]);

            $response = Profiler::trace('handle-payment', fn (): ?RedirectResponse => $this->paymentService->handlePaymentByOrder($orderId$data$context$finishUrl$errorUrl));

            return $response ?? new RedirectResponse($finishUrl);
        } catch (PaymentProcessException|InvalidOrderException|PaymentException|UnknownPaymentMethodException) {
            return $this->forwardToRoute('frontend.checkout.finish.page', ['orderId' => $orderId, 'changedPayment' => false, 'paymentFailed' => true]);
        }
    }

    #[Route(path: '/widgets/checkout/info', name: 'frontend.checkout.info', defaults: ['XmlHttpRequest' => true], methods: ['GET'])]     public function info(Request $request, SalesChannelContext $context): Response
    {
        $cart = $this->cartService->getCart($context->getToken()$context);
        if ($cart->getLineItems()->count() <= 0) {
            return new Response(null, Response::HTTP_NO_CONTENT);
        }
public function getResponse(
        MediaEntity $media,
        SalesChannelContext $context,
        string $expiration = '+120 minutes'
    ): Response {
        $fileSystem = $this->getFileSystem($media);
        $path = $this->urlGenerator->getRelativeMediaUrl($media);

        try {
            $url = $fileSystem->temporaryUrl($path(new \DateTime())->modify($expiration));

            return new RedirectResponse($url);
        } catch (UnableToGenerateTemporaryUrl) {
        }

        return $this->getDefaultResponse($media$context$fileSystem);
    }

    private function getDefaultResponse(MediaEntity $media, SalesChannelContext $context, FilesystemOperator $fileSystem): Response
    {
        if (!$media->isPrivate()) {
            return new RedirectResponse($this->urlGenerator->getAbsoluteMediaUrl($media));
        }

        
if (!\is_string($canonical) || empty($canonical)) {
            return null;
        }

        $queryString = $request->getQueryString();

        if ($queryString) {
            $canonical = sprintf('%s?%s', $canonical$queryString);
        }

        return new RedirectResponse($canonical, Response::HTTP_MOVED_PERMANENTLY);
    }
}
Home | Imprint | This part of the site doesn't use cookies.