1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Overblog\GraphQLBundle\Config\Parser; |
6
|
|
|
|
7
|
|
|
use GraphQL\Language\AST\DefinitionNode; |
8
|
|
|
use GraphQL\Language\AST\NodeKind; |
9
|
|
|
use GraphQL\Language\Parser; |
10
|
|
|
use Symfony\Component\Config\Resource\FileResource; |
11
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
12
|
|
|
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; |
13
|
|
|
|
14
|
|
|
class GraphQLParser implements ParserInterface |
15
|
|
|
{ |
16
|
|
|
private const DEFINITION_TYPE_MAPPING = [ |
17
|
|
|
NodeKind::OBJECT_TYPE_DEFINITION => 'object', |
18
|
|
|
NodeKind::INTERFACE_TYPE_DEFINITION => 'interface', |
19
|
|
|
NodeKind::ENUM_TYPE_DEFINITION => 'enum', |
20
|
|
|
NodeKind::UNION_TYPE_DEFINITION => 'union', |
21
|
|
|
NodeKind::INPUT_OBJECT_TYPE_DEFINITION => 'inputObject', |
22
|
|
|
NodeKind::SCALAR_TYPE_DEFINITION => 'customScalar', |
23
|
|
|
]; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* {@inheritdoc} |
27
|
|
|
*/ |
28
|
5 |
|
public static function parse(\SplFileInfo $file, ContainerBuilder $container): array |
29
|
|
|
{ |
30
|
5 |
|
$container->addResource(new FileResource($file->getRealPath())); |
31
|
5 |
|
$content = \trim(\file_get_contents($file->getPathname())); |
32
|
5 |
|
$typesConfig = []; |
33
|
|
|
|
34
|
|
|
// allow empty files |
35
|
5 |
|
if (empty($content)) { |
36
|
1 |
|
return []; |
37
|
|
|
} |
38
|
|
|
try { |
39
|
4 |
|
$ast = Parser::parse($content); |
40
|
1 |
|
} catch (\Exception $e) { |
41
|
1 |
|
throw new InvalidArgumentException(\sprintf('An error occurred while parsing the file "%s".', $file), $e->getCode(), $e); |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
foreach ($ast->definitions as $typeDef) { |
45
|
3 |
|
if (isset($typeDef->kind) && \in_array($typeDef->kind, \array_keys(self::DEFINITION_TYPE_MAPPING))) { |
46
|
2 |
|
$class = \sprintf('\\%s\\GraphQL\\ASTConverter\\%sNode', __NAMESPACE__, \ucfirst(self::DEFINITION_TYPE_MAPPING[$typeDef->kind])); |
47
|
2 |
|
$typesConfig[$typeDef->name->value] = \call_user_func([$class, 'toConfig'], $typeDef); |
48
|
|
|
} else { |
49
|
3 |
|
self::throwUnsupportedDefinitionNode($typeDef); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
return $typesConfig; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
private static function throwUnsupportedDefinitionNode(DefinitionNode $typeDef): void |
57
|
|
|
{ |
58
|
1 |
|
$path = \explode('\\', \get_class($typeDef)); |
59
|
1 |
|
throw new InvalidArgumentException( |
60
|
1 |
|
\sprintf( |
61
|
1 |
|
'%s definition is not supported right now.', |
62
|
1 |
|
\preg_replace('@DefinitionNode$@', '', \array_pop($path)) |
63
|
|
|
) |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|