generateUrl example


    public function getSitemaps($shopId)
    {
        $files = $this->filesystem->listContents('shop-' . $shopId);
        $sitemaps = [];

        foreach ($files as $file) {
            if ($file['basename'][0] === '.') {
                continue;
            }

            $path = $this->publicUrlGenerator->generateUrl('sitemap/shop-' . $shopId . '/' . $file['basename']);

            $sitemaps[] = new Sitemap(
                $path,
                0,
                new DateTime('@' . $file['timestamp'])
            );
        }

        return $sitemaps;
    }
}
$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');
        }

        
$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'));
    }
}
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerReference;

class SubRequestController
{
    public function __construct(private ContainerInterface $container)
    {
    }

    public function indexAction($handler)
    {
        $errorUrl = $this->generateUrl('subrequest_fragment_error', ['_locale' => 'fr', '_format' => 'json']);
        $altUrl = $this->generateUrl('subrequest_fragment', ['_locale' => 'fr', '_format' => 'json']);

        // simulates a failure during the rendering of a fragment...         // should render fr/json         $content = $handler->render($errorUrl, 'inline', ['alt' => $altUrl]);

        // ...to check that the FragmentListener still references the right Request         // when rendering another fragment after the error occurred         // should render en/html instead of fr/json         $content .= $handler->render(new ControllerReference(self::class.'::fragmentAction'));

        


        $transitionsJson = [];
        /** @var StateMachineTransitionEntity $transition */
        foreach ($availableTransitions as $transition) {
            $transitionsJson[] = [
                'name' => $transition->getToStateMachineState()->getName(),
                'technicalName' => $transition->getToStateMachineState()->getTechnicalName(),
                'actionName' => $transition->getActionName(),
                'fromStateName' => $transition->getFromStateMachineState()->getTechnicalName(),
                'toStateName' => $transition->getToStateMachineState()->getTechnicalName(),
                'url' => $this->generateUrl('api.state_machine.transition_state', [
                    'entityName' => $entityName,
                    'entityId' => $entityId,
                    'version' => $request->attributes->get('version'),
                    'transition' => $transition->getActionName(),
                ]),
            ];
        }

        return new JsonResponse([
            'transitions' => $transitionsJson,
        ]);
    }
public function send(string $location, FilesystemInterface $filesystem): void
    {
        $this->front->Plugins()->ViewRenderer()->setNoRender();
        $downloadStrategy = (int) $this->config->get('esdDownloadStrategy');

        $meta = $filesystem->getMetadata($location);
        $mimeType = $filesystem->getMimetype($location) ?: 'application/octet-stream';

        $response = $this->front->Response();

        if ($this->canServedLocal($filesystem$downloadStrategy)) {
            $publicUrl = $this->publicUrlGenerator->generateUrl($location);
            $path = (string) parse_url($publicUrl, PHP_URL_PATH);
            switch ($downloadStrategy) {
                case 0:
                    $response->setRedirect($publicUrl);
                    break;
                case 2:
                    $location = $this->privateFilesystemRoot . '/' . $location;
                    $response->headers->set('content-type', 'application/octet-stream');
                    $response->headers->set('content-disposition', sprintf('attachment; filename="%s"', basename($location)));
                    $response->headers->set('x-sendfile', $location);
                    break;
                
public function testGenerateUrl()
    {
        $router = $this->createMock(RouterInterface::class);
        $router->expects($this->once())->method('generate')->willReturn('/foo');

        $container = new Container();
        $container->set('router', $router);

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

        $this->assertEquals('/foo', $controller->generateUrl('foo'));
    }

    public function testRedirect()
    {
        $controller = $this->createController();
        $response = $controller->redirect('https://dunglas.fr', 301);

        $this->assertInstanceOf(RedirectResponse::class$response);
        $this->assertSame('https://dunglas.fr', $response->getTargetUrl());
        $this->assertSame(301, $response->getStatusCode());
    }

    
/** * @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(),
            

        return new RedirectResponse($url$status);
    }

    /** * Returns a RedirectResponse to the given route with the given parameters. * * @param int $status The HTTP status code (302 "Found" by default) */
    protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
    {
        return $this->redirect($this->generateUrl($route$parameters)$status);
    }

    /** * Returns a JsonResponse that uses the serializer component if enabled, or json_encode. * * @param int $status The HTTP status code (200 "OK" by default) */
    protected function json(mixed $data, int $status = 200, array $headers = [], array $context = []): JsonResponse
    {
        if ($this->container->has('serializer')) {
            $json = $this->container->get('serializer')->serialize($data, 'json', array_merge([
                
return new Response();
    }

    /** * @param array<string, mixed> $attributes * @param array<string, mixed> $routeParameters */
    protected function forwardToRoute(string $routeName, array $attributes = [], array $routeParameters = []): Response
    {
        $router = $this->container->get('router');

        $url = $this->generateUrl($routeName$routeParameters, Router::PATH_INFO);

        // for the route matching the request method is set to "GET" because         // this method is not ought to be used as a post passthrough         // rather it shall return templates or redirects to display results of the request ahead         $method = $router->getContext()->getMethod();
        $router->getContext()->setMethod(Request::METHOD_GET);

        $route = $router->match($url);
        $router->getContext()->setMethod($method);

        $request = $this->container->get('request_stack')->getCurrentRequest();

        

            ),
            $context
        );

        return $this->redirectToRoute('frontend.account.edit-order.page', ['orderId' => $orderId]);
    }

    #[Route(path: '/account/order/update/{orderId}', name: 'frontend.account.edit-order.update-order', methods: ['POST'])]     public function updateOrder(string $orderId, Request $request, SalesChannelContext $context): Response
    {
        $finishUrl = $this->generateUrl('frontend.checkout.finish.page', [
            'orderId' => $orderId,
            'changedPayment' => true,
        ]);

        /** @var OrderEntity|null $order */
        $order = $this->orderRoute->load($request$contextnew Criteria([$orderId]))->getOrders()->first();

        if ($order === null) {
            throw OrderException::orderNotFound($orderId);
        }

        
 catch (UnknownPaymentMethodException|CartException $e) {
            if ($e->getErrorCode() === CartException::CART_PAYMENT_INVALID_ORDER_STORED_CODE && $e->getParameter('orderId')) {
                return $this->forwardToRoute('frontend.checkout.finish.page', ['orderId' => $e->getParameter('orderId'), 'changedPayment' => false, 'paymentFailed' => true]);
            }
            $message = $this->trans('error.' . $e->getErrorCode());
            $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'])]
Home | Imprint | This part of the site doesn't use cookies.