JsonResponse example


        $response = [];
        $formId = $request->get('formId');
        if (!$formId) {
            throw RoutingException::missingRequestParameter('formId');
        }

        if ($this->basicCaptcha->isValid($request[])) {
            $fakeSession = $request->get(BasicCaptcha::CAPTCHA_REQUEST_PARAMETER);
            $request->getSession()->set($formId . BasicCaptcha::BASIC_CAPTCHA_SESSION, $fakeSession);

            return new JsonResponse(['session' => $fakeSession]);
        }

        $violations = $this->basicCaptcha->getViolations();
        $formViolations = new ConstraintViolationException($violations[]);
        $response[] = [
            'type' => 'danger',
            'error' => 'invalid_captcha',
            'input' => $this->renderView('@Storefront/storefront/component/captcha/basicCaptchaFields.html.twig', [
                'formId' => $request->get('formId'),
                'formViolations' => $formViolations,
            ]),
        ];
private readonly MessageBusInterface $messageBus
    ) {
    }

    #[Route(path: '/api/_action/indexing', name: 'api.action.indexing', methods: ['POST'])]     public function indexing(Request $request): JsonResponse
    {
        $indexingSkips = array_filter(explode(',', (string) $request->headers->get(PlatformRequest::HEADER_INDEXING_SKIP, '')));

        $this->registry->sendIndexingMessage([]$indexingSkips);

        return new JsonResponse();
    }

    #[Route(path: '/api/_action/indexing/{indexer}', name: 'api.action.indexing.iterate', methods: ['POST'])]     public function iterate(string $indexer, Request $request): JsonResponse
    {
        $indexingSkips = array_filter(explode(',', (string) $request->headers->get(PlatformRequest::HEADER_INDEXING_SKIP, '')));

        if (!$request->request->has('offset')) {
            throw new BadRequestHttpException('Parameter `offset` missing');
        }

        

    /** * @internal */
    public function __construct(private readonly PromotionCodeService $codeService)
    {
    }

    #[Route(path: '/api/_action/promotion/codes/generate-fixed', name: 'api.action.promotion.codes.generate-fixed', methods: ['GET'], defaults: ['_acl' => ['promotion.editor']])]     public function generateFixedCode(): Response
    {
        return new JsonResponse($this->codeService->getFixedCode());
    }

    #[Route(path: '/api/_action/promotion/codes/generate-individual', name: 'api.action.promotion.codes.generate-individual', methods: ['GET'], defaults: ['_acl' => ['promotion.editor']])]     public function generateIndividualCodes(Request $request): Response
    {
        $codePattern = (string) $request->query->get('codePattern');
        if ($codePattern === '') {
            throw RoutingException::missingRequestParameter('codePattern');
        }
        $amount = $request->query->getInt('amount');

        
$mediaId = $request->query->has('mediaId') ? $request->query->getString('mediaId') : null;

        if ($preferredFileName === '') {
            throw MediaException::emptyMediaFilename();
        }
        if ($fileExtension === '') {
            throw MediaException::missingFileExtension();
        }

        $name = $this->fileNameProvider->provide($preferredFileName$fileExtension$mediaId$context);

        return new JsonResponse(['fileName' => $name]);
    }
}
$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 ($token->getErrorUrl() === null) {
            return null;
        }

        
'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,
        ]);
    }

    #[Route(path: '/api/_action/state-machine/{entityName}/{entityId}/state/{transition}', name: 'api.state_machine.transition_state', methods: ['POST'])]     public function transitionState(
        Request $request,
        Context $context,
        ResponseFactoryInterface $responseFactory,
        string $entityName,
        string $entityId,
        

        $countryId = (string) $request->request->get('countryId');

        if (!$countryId) {
            throw RoutingException::missingRequestParameter('countryId');
        }

        $countryStateDataPagelet = $this->countryStateDataPageletLoader->load($countryId$request$context);

        $this->hook(new CountryStateDataPageletLoadedHook($countryStateDataPagelet$context));

        return new JsonResponse([
            'states' => $countryStateDataPagelet->getStates(),
        ]);
    }
}
private readonly SystemConfigService $systemConfig,
        private readonly AbstractExtensionLifecycle $extensionLifecycleService,
        private readonly string $shopwareVersion,
        private readonly bool $disableUpdateCheck = false
    ) {
    }

    #[Route(path: '/api/_action/update/check', name: 'api.custom.updateapi.check', defaults: ['_acl' => ['system:core:update']], methods: ['GET'])]     public function updateApiCheck(): JsonResponse
    {
        if ($this->disableUpdateCheck) {
            return new JsonResponse();
        }

        $updates = $this->apiClient->checkForUpdates();

        if (version_compare($this->shopwareVersion, $updates->version, '>=')) {
            return new JsonResponse();
        }

        return new JsonResponse($updates);
    }

    
/** * @phpstan-type DefaultExceptionData array{code: string, status: string, title: string, detail: string|null, meta?: array{trace: array<int|string, mixed>, file: string, line: int, previous?: mixed}} * * @phpstan-import-type ErrorData from ShopwareHttpException as ShopwareExceptionData */
#[Package('core')] class ErrorResponseFactory
{
    public function getResponseFromException(\Throwable $exception, bool $debug = false): Response
    {
        $response = new JsonResponse(
            null,
            $this->getStatusCodeFromException($exception),
            $this->getHeadersFromException($exception)
        );

        $response->setEncodingOptions($response->getEncodingOptions() | \JSON_INVALID_UTF8_SUBSTITUTE);
        $response->setData(['errors' => $this->getErrorsFromException($exception$debug)]);

        return $response;
    }

    

        } catch (RateLimitExceededException $exception) {
            $response[] = [
                'type' => 'info',
                'alert' => $this->renderView('@Storefront/storefront/utilities/alert.html.twig', [
                    'type' => 'info',
                    'content' => $this->trans('error.rateLimitExceeded', ['%seconds%' => $exception->getWaitTime()]),
                ]),
            ];
        }

        return new JsonResponse($response);
    }

    #[Route(path: '/form/newsletter', name: 'frontend.form.newsletter.register.handle', defaults: ['XmlHttpRequest' => true, '_captcha' => true], methods: ['POST'])]     public function handleNewsletter(Request $request, RequestDataBag $data, SalesChannelContext $context): JsonResponse
    {
        $subscribe = $data->get('option') === self::SUBSCRIBE;

        if ($subscribe) {
            $response = $this->handleSubscribe($request$data$context);
        } else {
            $response = $this->handleUnsubscribe($data$context);
        }
private readonly AbstractExtensionDataProvider $extensionDataProvider,
        private readonly EntityRepository $userRepository,
        private readonly EntityRepository $languageRepository
    ) {
    }

    #[Route(path: '/api/_action/extension/installed', name: 'api.extension.installed', methods: ['GET'])]     public function getInstalledExtensions(Context $context): Response
    {
        $context = $this->switchContext($context);

        return new JsonResponse(
            $this->extensionDataProvider->getInstalledExtensions($context)
        );
    }

    private function switchContext(Context $context): Context
    {
        if (!$context->getSource() instanceof AdminApiSource) {
            return $context;
        }

        /** @var AdminApiSource $source */
        
$builder->withClaim('languageId', $context->getLanguageId());
        }

        if (\in_array('payment_method:read', $privileges, true)) {
            $builder->withClaim('paymentMethodId', $context->getPaymentMethod()->getId());
        }

        if (\in_array('shipping_method:read', $privileges, true)) {
            $builder->withClaim('shippingMethodId', $context->getShippingMethod()->getId());
        }

        return new JsonResponse([
            'token' => $builder->getToken($configuration->signer()$configuration->signingKey())->toString(),
            'expires' => $expiration->format(\DateTime::ATOM),
            'shopId' => $shopId,
        ]);
    }

    /** * @return array{app_secret: non-empty-string, privileges: array<string>} */
    private function fetchAppDetails(string $name): array
    {
        
if ($app === null) {
            throw new AppByNameNotFoundException($appName);
        }

        $secret = $app->getAppSecret();
        if ($secret === null) {
            throw new MissingAppSecretException();
        }

        $uri = $this->querySigner->signUri($requestDataBag->get('uri')$secret$context)->__toString();

        return new JsonResponse([
            'uri' => $uri,
        ]);
    }
}
$workerDispatcher->addSubscriber(new StopWorkerOnMemoryLimitListener(
                MemorySizeCalculator::convertToBytes($this->memoryLimit)
            ));
        }

        $worker = new Worker([$this->defaultTransportName => $receiver]$this->bus, $workerDispatcher);

        $worker->run(['sleep' => 50]);

        $consumerLock->release();

        return new JsonResponse(['handledMessages' => $listener->getHandledMessages()]);
    }
}
class ExtensionStoreLicensesController extends AbstractController
{
    public function __construct(private readonly AbstractExtensionStoreLicensesService $extensionStoreLicensesService)
    {
    }

    #[Route(path: '/api/license/cancel/{licenseId}', name: 'api.license.cancel', methods: ['DELETE'])]     public function cancelSubscription(int $licenseId, Context $context): JsonResponse
    {
        $this->extensionStoreLicensesService->cancelSubscription($licenseId$context);

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

    #[Route(path: '/api/license/rate/{extensionId}', name: 'api.license.rate', methods: ['POST'])]     public function rateLicensedExtension(int $extensionId, Request $request, Context $context): JsonResponse
    {
        $this->extensionStoreLicensesService->rateLicensedExtension(
            ReviewStruct::fromRequest($extensionId$request),
            $context
        );

        return new JsonResponse(null, Response::HTTP_NO_CONTENT);
    }
Home | Imprint | This part of the site doesn't use cookies.