Files
kupshop/bundles/KupShop/GraphQLBundle/Controller/FrontendController.php
2025-08-02 16:30:27 +02:00

70 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace KupShop\GraphQLBundle\Controller;
use GraphQL\Error\CoercionError;
use GraphQL\Server\Exception\MissingContentTypeHeader;
use KupShop\KupShopBundle\Util\RequestUtil;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
use TheCodingMachine\GraphQLite\Bundle\Controller\GraphQLiteController;
class FrontendController extends GraphQLiteController
{
#[Route(path: '/graphql', name: 'graphqliteRoute')]
public function graphql(Request $request, RequestUtil $requestUtil): Response
{
$query = join(',', array_unique($this->getGraphQLActions($request)));
$requestUtil->addTransactionInfo($request, ['action' => join(':', ['graphql', $query]), 'query' => $query]);
try {
$response = $this->handleRequest($request);
} catch (\RuntimeException|MissingContentTypeHeader|CoercionError $e) {
// runtime exception is thrown from `handleRequest` when invalid data passed
// or MissingContentTypeHeader when empty Content-Type header is set
// CoercionError is caused by invalid Datetime in query variable
// all of these should result to BadRequestHttpException
throw new BadRequestHttpException($e->getMessage(), $e);
}
if ($request->isMethod('GET') && !getAdminUser()) {
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setMaxAge(0);
$response->setPublic();
$response->setSharedMaxAge(60 * 15);
}
return $response;
}
private function getGraphQLActions(Request $request): array
{
$actions = [];
$input = json_decode($request->getContent(), true) ?? null;
if (!is_array($input)) {
return $actions;
}
foreach (array_is_list($input) ? $input : [$input] as $operation) {
$operationName = $operation['operationName'] ?? null;
if (!$operationName && preg_match('/^\s*(query|mutation)\s*(\w+)/i', $operation['query'] ?? '', $matches)) {
$operationName = $matches[2] ?? null;
}
if ($operationName) {
$actions[] = $operationName;
}
}
return $actions;
}
}