Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
declare(strict_types=1);

use PhpCsFixer\Finder;
use Ruudk\GraphQLCodeGenerator\PhpCsFixer\GraphQLHeredocFixer;
use Ticketswap\PhpCsFixerConfig\PhpCsFixerConfigFactory;
use Ticketswap\PhpCsFixerConfig\RuleSet\TicketSwapRuleSet;

Expand All @@ -18,4 +19,15 @@
__DIR__ . '/phpstan.php',
]);

return PhpCsFixerConfigFactory::create(TicketSwapRuleSet::create())->setFinder($finder);
$config = PhpCsFixerConfigFactory::create(TicketSwapRuleSet::create())->setFinder($finder);

$config->registerCustomFixers([
new GraphQLHeredocFixer(),
]);

$config->setRules([
...$config->getRules(),
'Ruudk/graphql_heredoc' => true,
]);

return $config;
59 changes: 52 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ final readonly class SomeController
{
private const string OPERATION = <<<'GRAPHQL'
query Projects {
...AdminProjectList
...AdminProjectList
}
GRAPHQL;

Expand Down Expand Up @@ -497,9 +497,9 @@ final readonly class UserMapper
{
private const string FRAGMENT = <<<'GRAPHQL'
fragment UserName on User {
id
firstName
lastName
id
firstName
lastName
}
GRAPHQL;

Expand Down Expand Up @@ -536,9 +536,9 @@ final readonly class ListUsersClient
{
private const string OPERATION = <<<'GRAPHQL'
query ListUsers {
users {
...UserName
}
users {
...UserName
}
}
GRAPHQL;

Expand Down Expand Up @@ -570,6 +570,51 @@ final readonly class ListUsersClient

**Fragment names must be globally unique** across `.graphql` files, Twig templates, and PHP attributes — the generator throws on conflict, naming both source locations.

#### 🧹 Auto-Format GraphQL in PHP Heredocs

A custom [PHP CS Fixer](https://cs.symfony.com/) fixer ships with this library to keep the GraphQL inside your `<<<'GRAPHQL' ... GRAPHQL` nowdoc strings consistently formatted. It parses the operation and rewrites it with `webonyx/graphql-php`'s `Printer::doPrint()`, indented to match the heredoc. Only single-quoted nowdocs are touched (a heredoc would interpolate GraphQL `$variables` as PHP variables); invalid GraphQL is left untouched.

Register `GraphQLHeredocFixer` in your `.php-cs-fixer.php`:

<!-- source: .php-cs-fixer.php -->
```php
<?php

declare(strict_types=1);

use PhpCsFixer\Finder;
use Ruudk\GraphQLCodeGenerator\PhpCsFixer\GraphQLHeredocFixer;
use Ticketswap\PhpCsFixerConfig\PhpCsFixerConfigFactory;
use Ticketswap\PhpCsFixerConfig\RuleSet\TicketSwapRuleSet;

$finder = Finder::create()
->in(__DIR__ . '/examples')
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
->notPath(['Generated'])
->append([
__DIR__ . '/.php-cs-fixer.php',
__DIR__ . '/bin/graphql-client-code-generator',
__DIR__ . '/composer-dependency-analyser.php',
__DIR__ . '/phpstan.php',
]);

$config = PhpCsFixerConfigFactory::create(TicketSwapRuleSet::create())->setFinder($finder);

$config->registerCustomFixers([
new GraphQLHeredocFixer(),
]);

$config->setRules([
...$config->getRules(),
'Ruudk/graphql_heredoc' => true,
]);

return $config;
```

Running `vendor/bin/php-cs-fixer fix` now formats every `<<<'GRAPHQL'` block automatically. The fixer runs before `heredoc_indentation`, so the surrounding indentation stays consistent with the rest of your codebase.

### 🎭 Twig Template Support

Keep your GraphQL fragments next to where they're used in your templates:
Expand Down
10 changes: 10 additions & 0 deletions composer-dependency-analyser.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@

$config->ignoreErrorsOnPackage('twig/twig', [ErrorType::DEV_DEPENDENCY_IN_PROD]);
$config->ignoreErrorsOnPackage('vincentlanglet/twig-cs-fixer', [ErrorType::DEV_DEPENDENCY_IN_PROD]);
$config->ignoreErrorsOnPackage('friendsofphp/php-cs-fixer', [ErrorType::DEV_DEPENDENCY_IN_PROD]);

// The custom php-cs-fixer fixer uses ext-tokenizer's T_* constants via the
// php-cs-fixer extension API. php-cs-fixer already requires ext-tokenizer;
// the library's runtime code does not, so it is not a real dependency.
$config->ignoreErrorsOnExtensionAndPath(
'ext-tokenizer',
__DIR__ . '/src/PhpCsFixer/GraphQLHeredocFixer.php',
[ErrorType::SHADOW_DEPENDENCY],
);

// phpstan/phpdoc-parser is never referenced directly. Symfony's TypeResolver
// only enables @return / @param PHPDoc parsing when this package is loadable,
Expand Down
159 changes: 159 additions & 0 deletions src/PhpCsFixer/GraphQLHeredocFixer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<?php

declare(strict_types=1);

namespace Ruudk\GraphQLCodeGenerator\PhpCsFixer;

use GraphQL\Error\SyntaxError;
use GraphQL\Language\Parser;
use GraphQL\Language\Printer;
use JsonException;
use Override;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use SplFileInfo;

/**
* Formats the GraphQL operation inside `<<<'GRAPHQL' ... GRAPHQL` nowdoc
* strings using webonyx/graphql-php so it follows a single canonical style.
*/
final class GraphQLHeredocFixer implements FixerInterface
{
private const string INDENT = ' ';

#[Override]
public function getName() : string
{
return 'Ruudk/graphql_heredoc';
}

#[Override]
public function getDefinition() : FixerDefinitionInterface
{
return new FixerDefinition(
"GraphQL inside <<<'GRAPHQL' nowdoc strings must be formatted with the webonyx/graphql-php printer.",
[
new CodeSample(
<<<'PHP'
<?php
$query = <<<'GRAPHQL'
query Foo{ id }
GRAPHQL;

PHP,
),
],
);
}

#[Override]
public function isCandidate(Tokens $tokens) : bool
{
return $tokens->isTokenKindFound(T_START_HEREDOC);
}

#[Override]
public function isRisky() : bool
{
return false;
}

#[Override]
public function getPriority() : int
{
// Run before the built-in heredoc_indentation fixer (priority -26)
// so the re-indentation it applies afterwards stays a no-op.
return 1;
}

#[Override]
public function supports(SplFileInfo $file) : bool
{
return true;
}

#[Override]
public function fix(SplFileInfo $file, Tokens $tokens) : void
{
if ($tokens->count() === 0 || ! $this->isCandidate($tokens)) {
return;
}

for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];

if ( ! $token->isGivenKind(T_START_HEREDOC)) {
continue;
}

// Only single-quoted nowdoc with the GRAPHQL label. A heredoc
// would interpolate GraphQL `$variables` as PHP variables.
if (preg_match('/^<<<[ \t]*\'GRAPHQL\'/', $token->getContent()) !== 1) {
continue;
}

$endIndex = $tokens->getNextTokenOfKind($index, [[T_END_HEREDOC]]);

if ($endIndex === null || $endIndex === $index + 1) {
continue;
}

$bodyIndex = $index + 1;
$bodyToken = $tokens[$bodyIndex];

if ( ! $bodyToken->isGivenKind(T_ENCAPSED_AND_WHITESPACE) || $bodyIndex + 1 !== $endIndex) {
continue;
}

try {
$formatted = rtrim(Printer::doPrint(Parser::parse($bodyToken->getContent())), "\r\n");
} catch (JsonException | SyntaxError) {
continue;
}

$indent = $this->detectIndent($tokens, $index) . self::INDENT;

$body = '';

foreach (explode("\n", $formatted) as $line) {
$body .= ($line === '' ? '' : $indent . $line) . "\n";
}

$endContent = $indent . 'GRAPHQL';

if ($body === $bodyToken->getContent() && $tokens[$endIndex]->getContent() === $endContent) {
continue;
}

$tokens[$bodyIndex] = new Token([T_ENCAPSED_AND_WHITESPACE, $body]);
$tokens[$endIndex] = new Token([T_END_HEREDOC, $endContent]);
}
}

private function detectIndent(Tokens $tokens, int $index) : string
{
while (true) {
$whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE]]);

if ($whitespaceIndex === null) {
return '';
}

$whitespace = $tokens[$whitespaceIndex]->getContent();

$newlinePosition = strrpos($whitespace, "\n");

if ($newlinePosition === false) {
$index = $whitespaceIndex;

continue;
}

return substr($whitespace, $newlinePosition + 1);
}
}
}
53 changes: 53 additions & 0 deletions tests/GraphQLHeredocFixer/GraphQLHeredocFixerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Ruudk\GraphQLCodeGenerator\GraphQLHeredocFixer;

use PhpCsFixer\Tokenizer\Tokens;
use PHPUnit\Framework\TestCase;
use Ruudk\GraphQLCodeGenerator\PhpCsFixer\GraphQLHeredocFixer;
use SplFileInfo;

final class GraphQLHeredocFixerTest extends TestCase
{
private const string FIXTURES = __DIR__ . '/fixtures';

public function testFormatsGraphQLNowdoc() : void
{
$unformatted = (string) file_get_contents(self::FIXTURES . '/unformatted.php.fixture');
$expected = (string) file_get_contents(self::FIXTURES . '/formatted.php.fixture');

self::assertSame($expected, $this->fix($unformatted));
}

public function testAlreadyFormattedIsLeftUnchanged() : void
{
$formatted = (string) file_get_contents(self::FIXTURES . '/formatted.php.fixture');

self::assertSame($formatted, $this->fix($formatted));
}

public function testInvalidGraphQLIsLeftUntouched() : void
{
$invalid = (string) file_get_contents(self::FIXTURES . '/invalid.php.fixture');

self::assertSame($invalid, $this->fix($invalid));
}

public function testNonGraphQLNowdocAndInterpolatedHeredocAreSkipped() : void
{
$skipped = (string) file_get_contents(self::FIXTURES . '/skipped.php.fixture');

self::assertSame($skipped, $this->fix($skipped));
}

private function fix(string $code) : string
{
$fixer = new GraphQLHeredocFixer();
$tokens = Tokens::fromCode($code);
$fixer->fix(new SplFileInfo('Example.php'), $tokens);

return $tokens->generateCode();
}
}
21 changes: 21 additions & 0 deletions tests/GraphQLHeredocFixer/fixtures/formatted.php.fixture
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

final class Example
{
private const string OPERATION = <<<'GRAPHQL'
query Projects {
...AdminProjectList
}

fragment AdminProjectList on Query {
viewer {
name
}
projects {
...Row
}
}
GRAPHQL;
}
8 changes: 8 additions & 0 deletions tests/GraphQLHeredocFixer/fixtures/invalid.php.fixture
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

declare(strict_types=1);

$query = <<<'GRAPHQL'
query GetUser($id: ID! {
user(id: $id
GRAPHQL;
11 changes: 11 additions & 0 deletions tests/GraphQLHeredocFixer/fixtures/skipped.php.fixture
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

$sql = <<<'SQL'
SELECT 1
SQL;

$interpolated = <<<GRAPHQL
query { user(id: $id) { name } }
GRAPHQL;
13 changes: 13 additions & 0 deletions tests/GraphQLHeredocFixer/fixtures/unformatted.php.fixture
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

final class Example
{
private const string OPERATION = <<<'GRAPHQL'
query Projects{
...AdminProjectList
}
fragment AdminProjectList on Query{ viewer{name} projects{ ...Row } }
GRAPHQL;
}
Loading
Loading