Skip to content

Commit 47152ff

Browse files
committed
Separating GraphQL error formatter callback as service
Writing test for GraphQLExceptionFormatterPass
1 parent a442a9e commit 47152ff

File tree

8 files changed

+293
-11
lines changed

8 files changed

+293
-11
lines changed

src/Bridge/Symfony/Bundle/Resources/config/graphql.xml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@
160160
<argument type="service" id="api_platform.graphql.fields_builder" />
161161
</service>
162162
<!-- Exception formatter -->
163+
<service id="api_platform.graphql.exception_formatter_callback" class="ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterCallback">
164+
<argument type="service" id="api_platform.graphql.exception_formatter_factory" />
165+
</service>
166+
163167
<service id="api_platform.graphql.validation_exception_formatter" class="ApiPlatform\Core\GraphQl\Exception\Formatter\ValidationExceptionFormatter">
164168
<tag name="api_platform.graphql.exception_formatter" />
165169
</service>
@@ -178,7 +182,7 @@
178182
<argument type="service" id="api_platform.graphql.executor" />
179183
<argument type="service" id="api_platform.graphql.action.graphiql" />
180184
<argument type="service" id="api_platform.graphql.action.graphql_playground" />
181-
<argument type="service" id="api_platform.graphql.exception_formatter_factory" />
185+
<argument type="service" id="api_platform.graphql.exception_formatter_callback" />
182186
<argument>%kernel.debug%</argument>
183187
<argument>%api_platform.graphql.graphiql.enabled%</argument>
184188
<argument>%api_platform.graphql.graphql_playground.enabled%</argument>

src/GraphQl/Action/EntrypointAction.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313

1414
namespace ApiPlatform\Core\GraphQl\Action;
1515

16-
use ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterFactory;
17-
use ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterInterface;
16+
use ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterCallbackInterface;
1817
use ApiPlatform\Core\GraphQl\ExecutorInterface;
1918
use ApiPlatform\Core\GraphQl\Type\SchemaBuilderInterface;
2019
use GraphQL\Error\Debug;
@@ -42,9 +41,9 @@ final class EntrypointAction
4241
private $graphiqlEnabled;
4342
private $graphQlPlaygroundEnabled;
4443
private $defaultIde;
45-
private $exceptionFormatterFactory;
44+
private $exceptionFormatterCallback;
4645

47-
public function __construct(SchemaBuilderInterface $schemaBuilder, ExecutorInterface $executor, GraphiQlAction $graphiQlAction, GraphQlPlaygroundAction $graphQlPlaygroundAction, ExceptionFormatterFactory $exceptionFormatterFactory, bool $debug = false, bool $graphiqlEnabled = false, bool $graphQlPlaygroundEnabled = false, $defaultIde = false)
46+
public function __construct(SchemaBuilderInterface $schemaBuilder, ExecutorInterface $executor, GraphiQlAction $graphiQlAction, GraphQlPlaygroundAction $graphQlPlaygroundAction, ExceptionFormatterCallbackInterface $exceptionFormatterCallback, bool $debug = false, bool $graphiqlEnabled = false, bool $graphQlPlaygroundEnabled = false, $defaultIde = false)
4847
{
4948
$this->schemaBuilder = $schemaBuilder;
5049
$this->executor = $executor;
@@ -54,7 +53,7 @@ public function __construct(SchemaBuilderInterface $schemaBuilder, ExecutorInter
5453
$this->graphiqlEnabled = $graphiqlEnabled;
5554
$this->graphQlPlaygroundEnabled = $graphQlPlaygroundEnabled;
5655
$this->defaultIde = $defaultIde;
57-
$this->exceptionFormatterFactory = $exceptionFormatterFactory;
56+
$this->exceptionFormatterCallback = $exceptionFormatterCallback;
5857
}
5958

6059
public function __invoke(Request $request): Response
@@ -75,7 +74,8 @@ public function __invoke(Request $request): Response
7574
throw new BadRequestHttpException('GraphQL query is not valid.');
7675
}
7776

78-
$executionResult = $this->executor->executeQuery($this->schemaBuilder->getSchema(), $query, null, null, $variables, $operation);
77+
$executionResult = $this->executor->executeQuery($this->schemaBuilder->getSchema(), $query, null, null, $variables, $operation)
78+
->setErrorFormatter($this->exceptionFormatterCallback);
7979
} catch (BadRequestHttpException $e) {
8080
$exception = new UserError($e->getMessage(), 0, $e);
8181

@@ -215,7 +215,8 @@ private function decodeVariables(string $variables): array
215215

216216
private function buildExceptionResponse(\Exception $e, int $statusCode): JsonResponse
217217
{
218-
$executionResult = new ExecutionResult(null, [new Error($e->getMessage(), null, null, null, null, $e)]);
218+
$executionResult = (new ExecutionResult(null, [new Error($e->getMessage(), null, null, null, null, $e)]))
219+
->setErrorFormatter($this->exceptionFormatterCallback);
219220

220221
return new JsonResponse($executionResult->toArray($this->debug), $statusCode);
221222
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Core\GraphQl\Exception;
15+
16+
use GraphQL\Error\Error;
17+
use GraphQL\Error\FormattedError;
18+
19+
/**
20+
* @expremintal
21+
*
22+
* @author Mahmood Bazdar <[email protected]>
23+
*/
24+
class ExceptionFormatterCallback implements ExceptionFormatterCallbackInterface
25+
{
26+
private $exceptionFormatterFactory;
27+
28+
public function __construct(ExceptionFormatterFactoryInterface $exceptionFormatterFactory)
29+
{
30+
$this->exceptionFormatterFactory = $exceptionFormatterFactory;
31+
}
32+
33+
/**
34+
* {@inheritdoc}
35+
*/
36+
public function __invoke(Error $error): array
37+
{
38+
$formatters = $this->exceptionFormatterFactory->getExceptionFormatters();
39+
usort($formatters, function (ExceptionFormatterInterface $a, ExceptionFormatterInterface $b) {
40+
if ($a->getPriority() == $b->getPriority()) {
41+
return 0;
42+
}
43+
44+
return ($a->getPriority() > $b->getPriority()) ? -1 : 1;
45+
});
46+
/** @var ExceptionFormatterInterface $exceptionFormatter */
47+
foreach ($formatters as $exceptionFormatter) {
48+
if (null !== $error->getPrevious() && $exceptionFormatter->supports($error->getPrevious())) {
49+
return $exceptionFormatter->format($error);
50+
}
51+
}
52+
53+
// falling back to default GraphQL error formatter
54+
return FormattedError::createFromException($error);
55+
}
56+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Core\GraphQl\Exception;
15+
16+
use GraphQL\Error\Error;
17+
18+
/**
19+
* @expremintal
20+
*
21+
* @author Mahmood Bazdar <[email protected]>
22+
*/
23+
interface ExceptionFormatterCallbackInterface
24+
{
25+
/**
26+
* Callback function will be used for formatting GraphQL errors.
27+
*/
28+
public function __invoke(Error $error): array;
29+
}

tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ public function testDisableGraphQl()
366366
$containerBuilderProphecy->setDefinition('api_platform.graphql.query_resolver_locator', Argument::type(Definition::class))->shouldNotBeCalled();
367367
$containerBuilderProphecy->setDefinition('api_platform.graphql.mutation_resolver_locator', Argument::type(Definition::class))->shouldNotBeCalled();
368368
$containerBuilderProphecy->setDefinition('api_platform.graphql.validation_exception_formatter', Argument::type(Definition::class))->shouldNotBeCalled();
369+
$containerBuilderProphecy->setDefinition('api_platform.graphql.exception_formatter_callback', Argument::type(Definition::class))->shouldNotBeCalled();
369370
$containerBuilderProphecy->setDefinition('api_platform.graphql.exception_formatter_locator', Argument::type(Definition::class))->shouldNotBeCalled();
370371
$containerBuilderProphecy->setDefinition('api_platform.graphql.exception_formatter_factory', Argument::type(Definition::class))->shouldNotBeCalled();
371372
$containerBuilderProphecy->setDefinition('api_platform.graphql.command.export_command', Argument::type(Definition::class))->shouldNotBeCalled();
@@ -1142,6 +1143,7 @@ private function getBaseContainerBuilderProphecy(array $doctrineIntegrationsToLo
11421143
'api_platform.graphql.resolver.stage.write',
11431144
'api_platform.graphql.resolver.stage.validate',
11441145
'api_platform.graphql.resolver.resource_field',
1146+
'api_platform.graphql.exception_formatter_callback',
11451147
'api_platform.graphql.validation_exception_formatter',
11461148
'api_platform.graphql.exception_formatter_locator',
11471149
'api_platform.graphql.exception_formatter_factory',
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Core\Tests\Bridge\Symfony\Bundle\DependencyInjection\Compiler;
15+
16+
use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\GraphQlExceptionFormatterPass;
17+
use PHPUnit\Framework\TestCase;
18+
use Prophecy\Argument;
19+
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
20+
use Symfony\Component\DependencyInjection\ContainerBuilder;
21+
use Symfony\Component\DependencyInjection\Definition;
22+
use Symfony\Component\DependencyInjection\Reference;
23+
24+
/**
25+
* @author Mahmood Bazdar <[email protected]>
26+
*/
27+
class GraphQlExceptionFormatterPassTest extends TestCase
28+
{
29+
public function testProcess()
30+
{
31+
$filterPass = new GraphQlExceptionFormatterPass();
32+
33+
$this->assertInstanceOf(CompilerPassInterface::class, $filterPass);
34+
35+
$exceptionFormatterLocatorDefinitionProphecy = $this->prophesize(Definition::class);
36+
$exceptionFormatterLocatorDefinitionProphecy->addArgument(Argument::that(function (array $arg) {
37+
return !isset($arg['foo']) && isset($arg['my_id']) && $arg['my_id'] instanceof Reference;
38+
}))->shouldBeCalled();
39+
40+
$exceptionFormatterFactoryDefinitionProphecy = $this->prophesize(Definition::class);
41+
$exceptionFormatterFactoryDefinitionProphecy->addArgument(['my_id'])->shouldBeCalled();
42+
43+
$containerBuilderProphecy = $this->prophesize(ContainerBuilder::class);
44+
$containerBuilderProphecy->getParameter('api_platform.graphql.enabled')->willReturn(true)->shouldBeCalled();
45+
$containerBuilderProphecy->findTaggedServiceIds('api_platform.graphql.exception_formatter', true)->willReturn(['foo' => [], 'bar' => [['id' => 'my_id']]])->shouldBeCalled();
46+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_locator')->willReturn($exceptionFormatterLocatorDefinitionProphecy->reveal())->shouldBeCalled();
47+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_factory')->willReturn($exceptionFormatterFactoryDefinitionProphecy->reveal())->shouldBeCalled();
48+
49+
$filterPass->process($containerBuilderProphecy->reveal());
50+
}
51+
52+
public function testIdNotExist()
53+
{
54+
$filterPass = new GraphQlExceptionFormatterPass();
55+
56+
$this->assertInstanceOf(CompilerPassInterface::class, $filterPass);
57+
58+
$exceptionFormatterLocatorDefinitionProphecy = $this->prophesize(Definition::class);
59+
$exceptionFormatterLocatorDefinitionProphecy->addArgument(Argument::that(function (array $arg) {
60+
return !isset($arg['foo']) && isset($arg['bar']) && $arg['bar'] instanceof Reference;
61+
}))->shouldBeCalled();
62+
63+
$exceptionFormatterFactoryDefinitionProphecy = $this->prophesize(Definition::class);
64+
$exceptionFormatterFactoryDefinitionProphecy->addArgument(['bar'])->shouldBeCalled();
65+
66+
$containerBuilderProphecy = $this->prophesize(ContainerBuilder::class);
67+
$containerBuilderProphecy->getParameter('api_platform.graphql.enabled')->willReturn(true)->shouldBeCalled();
68+
$containerBuilderProphecy->findTaggedServiceIds('api_platform.graphql.exception_formatter', true)->willReturn(['foo' => [], 'bar' => [['hi' => 'hello']]])->shouldBeCalled();
69+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_locator')->willReturn($exceptionFormatterLocatorDefinitionProphecy->reveal())->shouldBeCalled();
70+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_factory')->willReturn($exceptionFormatterFactoryDefinitionProphecy->reveal())->shouldBeCalled();
71+
72+
$filterPass->process($containerBuilderProphecy->reveal());
73+
}
74+
75+
public function testDisabled()
76+
{
77+
$filterPass = new GraphQlExceptionFormatterPass();
78+
79+
$this->assertInstanceOf(CompilerPassInterface::class, $filterPass);
80+
81+
$exceptionFormatterLocatorDefinitionProphecy = $this->prophesize(Definition::class);
82+
$exceptionFormatterLocatorDefinitionProphecy->addArgument(Argument::any())->shouldNotBeCalled();
83+
84+
$exceptionFormatterFactoryDefinitionProphecy = $this->prophesize(Definition::class);
85+
$exceptionFormatterFactoryDefinitionProphecy->addArgument(['my_id'])->shouldNotBeCalled();
86+
87+
$containerBuilderProphecy = $this->prophesize(ContainerBuilder::class);
88+
$containerBuilderProphecy->getParameter('api_platform.graphql.enabled')->willReturn(false)->shouldBeCalled();
89+
$containerBuilderProphecy->findTaggedServiceIds('api_platform.graphql.exception_formatter', true)->willReturn(['foo' => [], 'bar' => [['id' => 'my_id']]])->shouldNotBeCalled();
90+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_locator')->willReturn($exceptionFormatterLocatorDefinitionProphecy->reveal())->shouldNotBeCalled();
91+
$containerBuilderProphecy->getDefinition('api_platform.graphql.exception_formatter_factory')->willReturn($exceptionFormatterFactoryDefinitionProphecy->reveal())->shouldNotBeCalled();
92+
93+
$filterPass->process($containerBuilderProphecy->reveal());
94+
}
95+
}

tests/GraphQl/Action/EntrypointActionTest.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
use ApiPlatform\Core\GraphQl\Action\EntrypointAction;
1717
use ApiPlatform\Core\GraphQl\Action\GraphiQlAction;
1818
use ApiPlatform\Core\GraphQl\Action\GraphQlPlaygroundAction;
19-
use ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterFactory;
19+
use ApiPlatform\Core\GraphQl\Exception\ExceptionFormatterCallbackInterface;
2020
use ApiPlatform\Core\GraphQl\ExecutorInterface;
2121
use ApiPlatform\Core\GraphQl\Type\SchemaBuilderInterface;
2222
use GraphQL\Executor\ExecutionResult;
@@ -229,22 +229,24 @@ private function getEntrypointAction(array $variables = ['graphqlVariable']): En
229229
$schemaBuilderProphecy = $this->prophesize(SchemaBuilderInterface::class);
230230
$schemaBuilderProphecy->getSchema()->willReturn($schema->reveal());
231231

232+
$exceptionFormatterCallback = $this->prophesize(ExceptionFormatterCallbackInterface::class)->reveal();
233+
232234
$executionResultProphecy = $this->prophesize(ExecutionResult::class);
233235
$executionResultProphecy->toArray(false)->willReturn(['GraphQL']);
234236
$executionResultProphecy->setErrorFormatter(Argument::type('callable'))->willReturn($executionResultProphecy);
237+
$executionResultProphecy->setErrorFormatter($exceptionFormatterCallback)->willReturn($executionResultProphecy);
235238
$executionResultProphecy->toArray(3)->willReturn(['GraphQL']);
236239
$executorProphecy = $this->prophesize(ExecutorInterface::class);
237240
$executorProphecy->executeQuery(Argument::is($schema->reveal()), 'graphqlQuery', null, null, $variables, 'graphqlOperationName')->willReturn($executionResultProphecy->reveal());
238241

239242
$twigProphecy = $this->prophesize(TwigEnvironment::class);
240243
$routerProphecy = $this->prophesize(RouterInterface::class);
241244

242-
$exceptionFormatterFactoryProphecy = $this->prophesize(ExceptionFormatterFactory::class);
243-
244245
$graphiQlAction = new GraphiQlAction($twigProphecy->reveal(), $routerProphecy->reveal(), true);
245246
$graphQlPlaygroundAction = new GraphQlPlaygroundAction($twigProphecy->reveal(), $routerProphecy->reveal(), true);
246247

247248
return new EntrypointAction($schemaBuilderProphecy->reveal(), $executorProphecy->reveal(), $graphiQlAction, $graphQlPlaygroundAction, false, true, true, 'graphiql');
248249
return new EntrypointAction($schemaBuilderProphecy->reveal(), $executorProphecy->reveal(), $graphiQlAction, $graphQlPlaygroundAction, $exceptionFormatterFactoryProphecy->reveal(), true, true, true, 'graphiql');
250+
return new EntrypointAction($schemaBuilderProphecy->reveal(), $executorProphecy->reveal(), $graphiQlAction, $graphQlPlaygroundAction, $exceptionFormatterCallback, true, true, true, 'graphiql');
249251
}
250252
}

0 commit comments

Comments
 (0)