Skip to content

Commit

Permalink
Add concatAST utility function (#930)
Browse files Browse the repository at this point in the history
  • Loading branch information
vhenzl authored Oct 1, 2021
1 parent 10419b0 commit eb640db
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You can find and compare releases at the [GitHub release page](https://github.co
- Add tests for errors that occur when undeclared fields are passed in input
- Warn about orphaned object types
- Expose structured enumeration of directive locations
- Add `AST::concatAST()` utility
- Allow lazy input object fields

### Optimized
Expand Down
22 changes: 22 additions & 0 deletions src/Utils/AST.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\DefinitionNode;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\EnumValueNode;
use GraphQL\Language\AST\FloatValueNode;
Expand Down Expand Up @@ -43,6 +44,7 @@
use Traversable;

use function array_key_exists;
use function array_push;
use function count;
use function is_array;
use function is_bool;
Expand Down Expand Up @@ -608,4 +610,24 @@ public static function getOperationAST(DocumentNode $document, ?string $operatio

return $operation;
}

/**
* Provided a collection of ASTs, presumably each from different files,
* concatenate the ASTs together into batched AST, useful for validating many
* GraphQL source files which together represent one conceptual application.
*
* @param array<DocumentNode> $documents
*
* @api
*/
public static function concatAST(array $documents): DocumentNode
{
/** @var array<DefinitionNode> $definitions */
$definitions = [];
foreach ($documents as $document) {
array_push($definitions, ...$document->definitions);
}

return new DocumentNode(['definitions' => new NodeList($definitions)]);
}
}
49 changes: 49 additions & 0 deletions tests/Utils/ConcatASTTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace GraphQL\Tests\Utils;

use GraphQL\Language\Parser;
use GraphQL\Language\Printer;
use GraphQL\Utils\AST;
use PHPUnit\Framework\TestCase;

class ConcatASTTest extends TestCase
{
/**
* @see it('concatenates two ASTs together'
*/
public function testConcatenatesTwoAstsTogether(): void
{
$sourceA = '
{ a, b, ...Frag }
';

$sourceB = '
fragment Frag on T {
c
}
';

$astA = Parser::parse($sourceA);
$astB = Parser::parse($sourceB);
$astC = AST::concatAST([$astA, $astB]);

self::assertEquals(
<<<'GRAPHQL'
{
a
b
...Frag
}
fragment Frag on T {
c
}

GRAPHQL,
Printer::doPrint($astC)
);
}
}

0 comments on commit eb640db

Please sign in to comment.