Version 4.6.0

This commit is contained in:
Neo committed 2025-12-19 05:55:31 -08:00
1 parent f79dcf067a
commit 517a5e1f70
2036 files changed
+110041 -26162

No files matched your search

+387 -192
View File
@@ -1,9 +1,12 @@
<?php
declare(strict_types=1);
namespace GraphQL\Utils;
use GraphQL\Error\Error;
use GraphQL\Language\Printer;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\CompositeType;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InterfaceType;
@@ -11,7 +14,23 @@ use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use function array_filter;
use function array_keys;
use function array_map;
use function array_merge;
use function array_values;
use function count;
use function explode;
use function implode;
use function ksort;
use function mb_strlen;
use function preg_match_all;
use function sprintf;
use function str_replace;
use function strlen;
use function substr;
/**
* Given an instance of Schema, prints it in GraphQL type language.
@@ -19,100 +38,90 @@ use GraphQL\Type\Definition\Directive;
class SchemaPrinter
{
/**
* @param array<string, bool> $options
* Available options:
* - commentDescriptions:
* Provide true to use preceding comments as the description.
* This option is provided to ease adoption and will be removed in v16.
*
* @api
* @param Schema $schema
* @return string
*/
public static function doPrint(Schema $schema)
public static function doPrint(Schema $schema, array $options = []) : string
{
return self::printFilteredSchema($schema, function($n) {
return !self::isSpecDirective($n);
}, 'self::isDefinedType');
return static::printFilteredSchema(
$schema,
static function ($type) : bool {
return ! Directive::isSpecifiedDirective($type);
},
static function ($type) : bool {
return ! Type::isBuiltInType($type);
},
$options
);
}
/**
* @api
* @param Schema $schema
* @return string
* @param array<string, bool> $options
*/
public static function printIntrosepctionSchema(Schema $schema)
protected static function printFilteredSchema(Schema $schema, callable $directiveFilter, callable $typeFilter, array $options) : string
{
return self::printFilteredSchema($schema, [__CLASS__, 'isSpecDirective'], [__CLASS__, 'isIntrospectionType']);
}
$directives = array_filter($schema->getDirectives(), $directiveFilter);
private static function isSpecDirective($directiveName)
{
return (
$directiveName === 'skip' ||
$directiveName === 'include' ||
$directiveName === 'deprecated'
$types = $schema->getTypeMap();
ksort($types);
$types = array_filter($types, $typeFilter);
return sprintf(
"%s\n",
implode(
"\n\n",
array_filter(
array_merge(
[static::printSchemaDefinition($schema)],
array_map(
static function (Directive $directive) use ($options) : string {
return static::printDirective($directive, $options);
},
$directives
),
array_map(
static function ($type) use ($options) : string {
return static::printType($type, $options);
},
$types
)
)
)
)
);
}
private static function isDefinedType($typename)
protected static function printSchemaDefinition(Schema $schema) : string
{
return !self::isIntrospectionType($typename) && !self::isBuiltInScalar($typename);
}
private static function isIntrospectionType($typename)
{
return strpos($typename, '__') === 0;
}
private static function isBuiltInScalar($typename)
{
return (
$typename === Type::STRING ||
$typename === Type::BOOLEAN ||
$typename === Type::INT ||
$typename === Type::FLOAT ||
$typename === Type::ID
);
}
private static function printFilteredSchema(Schema $schema, $directiveFilter, $typeFilter)
{
$directives = array_filter($schema->getDirectives(), function($directive) use ($directiveFilter) {
return $directiveFilter($directive->name);
});
$typeMap = $schema->getTypeMap();
$types = array_filter(array_keys($typeMap), $typeFilter);
sort($types);
$types = array_map(function($typeName) use ($typeMap) { return $typeMap[$typeName]; }, $types);
return implode("\n\n", array_filter(array_merge(
[self::printSchemaDefinition($schema)],
array_map('self::printDirective', $directives),
array_map('self::printType', $types)
))) . "\n";
}
private static function printSchemaDefinition(Schema $schema)
{
if (self::isSchemaOfCommonNames($schema)) {
return;
if (static::isSchemaOfCommonNames($schema)) {
return '';
}
$operationTypes = [];
$queryType = $schema->getQueryType();
if ($queryType) {
$operationTypes[] = " query: {$queryType->name}";
if ($queryType !== null) {
$operationTypes[] = sprintf(' query: %s', $queryType->name);
}
$mutationType = $schema->getMutationType();
if ($mutationType) {
$operationTypes[] = " mutation: {$mutationType->name}";
if ($mutationType !== null) {
$operationTypes[] = sprintf(' mutation: %s', $mutationType->name);
}
$subscriptionType = $schema->getSubscriptionType();
if ($subscriptionType) {
$operationTypes[] = " subscription: {$subscriptionType->name}";
if ($subscriptionType !== null) {
$operationTypes[] = sprintf(' subscription: %s', $subscriptionType->name);
}
return "schema {\n" . implode("\n", $operationTypes) . "\n}";
return sprintf("schema {\n%s\n}", implode("\n", $operationTypes));
}
/**
* GraphQL schema define root types for each type of operation. These types are
* the same as any other type and can be named in any manner, however there is
@@ -125,189 +134,375 @@ class SchemaPrinter
*
* When using this naming convention, the schema description can be omitted.
*/
private static function isSchemaOfCommonNames(Schema $schema)
protected static function isSchemaOfCommonNames(Schema $schema) : bool
{
$queryType = $schema->getQueryType();
if ($queryType && $queryType->name !== 'Query') {
if ($queryType !== null && $queryType->name !== 'Query') {
return false;
}
$mutationType = $schema->getMutationType();
if ($mutationType && $mutationType->name !== 'Mutation') {
if ($mutationType !== null && $mutationType->name !== 'Mutation') {
return false;
}
$subscriptionType = $schema->getSubscriptionType();
if ($subscriptionType && $subscriptionType->name !== 'Subscription') {
return false;
return $subscriptionType === null || $subscriptionType->name === 'Subscription';
}
/**
* @param array<string, bool> $options
*/
protected static function printDirective(Directive $directive, array $options) : string
{
return static::printDescription($options, $directive)
. 'directive @' . $directive->name
. static::printArgs($options, $directive->args)
. ($directive->isRepeatable ? ' repeatable' : '')
. ' on ' . implode(' | ', $directive->locations);
}
/**
* @param array<string, bool> $options
*/
protected static function printDescription(array $options, $def, $indentation = '', $firstInBlock = true) : string
{
if (! $def->description) {
return '';
}
$lines = static::descriptionLines($def->description, 120 - strlen($indentation));
if (isset($options['commentDescriptions'])) {
return static::printDescriptionWithComments($lines, $indentation, $firstInBlock);
}
return true;
}
$description = $indentation && ! $firstInBlock
? "\n" . $indentation . '"""'
: $indentation . '"""';
public static function printType(Type $type)
{
if ($type instanceof ScalarType) {
return self::printScalar($type);
} else if ($type instanceof ObjectType) {
return self::printObject($type);
} else if ($type instanceof InterfaceType) {
return self::printInterface($type);
} else if ($type instanceof UnionType) {
return self::printUnion($type);
} else if ($type instanceof EnumType) {
return self::printEnum($type);
// In some circumstances, a single line can be used for the description.
if (count($lines) === 1 &&
mb_strlen($lines[0]) < 70 &&
substr($lines[0], -1) !== '"'
) {
return $description . static::escapeQuote($lines[0]) . "\"\"\"\n";
}
Utils::invariant($type instanceof InputObjectType);
return self::printInputObject($type);
// Format a multi-line block quote to account for leading space.
$hasLeadingSpace = isset($lines[0]) &&
(
substr($lines[0], 0, 1) === ' ' ||
substr($lines[0], 0, 1) === '\t'
);
if (! $hasLeadingSpace) {
$description .= "\n";
}
$lineLength = count($lines);
for ($i = 0; $i < $lineLength; $i++) {
if ($i !== 0 || ! $hasLeadingSpace) {
$description .= $indentation;
}
$description .= static::escapeQuote($lines[$i]) . "\n";
}
$description .= $indentation . "\"\"\"\n";
return $description;
}
private static function printScalar(ScalarType $type)
/**
* @return string[]
*/
protected static function descriptionLines(string $description, int $maxLen) : array
{
return self::printDescription($type) . "scalar {$type->name}";
$lines = [];
$rawLines = explode("\n", $description);
foreach ($rawLines as $line) {
if ($line === '') {
$lines[] = $line;
} else {
// For > 120 character long lines, cut at space boundaries into sublines
// of ~80 chars.
$sublines = static::breakLine($line, $maxLen);
foreach ($sublines as $subline) {
$lines[] = $subline;
}
}
}
return $lines;
}
private static function printObject(ObjectType $type)
/**
* @return string[]
*/
protected static function breakLine(string $line, int $maxLen) : array
{
$interfaces = $type->getInterfaces();
$implementedInterfaces = !empty($interfaces) ?
' implements ' . implode(', ', array_map(function($i) {
return $i->name;
}, $interfaces)) : '';
return self::printDescription($type) .
"type {$type->name}$implementedInterfaces {\n" .
self::printFields($type) . "\n" .
"}";
if (strlen($line) < $maxLen + 5) {
return [$line];
}
preg_match_all('/((?: |^).{15,' . ($maxLen - 40) . '}(?= |$))/', $line, $parts);
$parts = $parts[0];
return array_map('trim', $parts);
}
private static function printInterface(InterfaceType $type)
protected static function printDescriptionWithComments($lines, $indentation, $firstInBlock) : string
{
return self::printDescription($type) .
"interface {$type->name} {\n" .
self::printFields($type) . "\n" .
"}";
$description = $indentation && ! $firstInBlock ? "\n" : '';
foreach ($lines as $line) {
if ($line === '') {
$description .= $indentation . "#\n";
} else {
$description .= $indentation . '# ' . $line . "\n";
}
}
return $description;
}
private static function printUnion(UnionType $type)
protected static function escapeQuote($line) : string
{
return self::printDescription($type) .
"union {$type->name} = " . implode(" | ", $type->getTypes());
return str_replace('"""', '\\"""', $line);
}
private static function printEnum(EnumType $type)
/**
* @param array<string, bool> $options
*/
protected static function printArgs(array $options, $args, $indentation = '') : string
{
return self::printDescription($type) .
"enum {$type->name} {\n" .
self::printEnumValues($type->getValues()) . "\n" .
"}";
}
private static function printEnumValues($values)
{
return implode("\n", array_map(function($value, $i) {
return self::printDescription($value, ' ', !$i) . ' ' .
$value->name . self::printDeprecated($value);
}, $values, array_keys($values)));
}
private static function printInputObject(InputObjectType $type)
{
$fields = array_values($type->getFields());
return self::printDescription($type) .
"input {$type->name} {\n" .
implode("\n", array_map(function($f, $i) {
return self::printDescription($f, ' ', !$i) . ' ' . self::printInputValue($f);
}, $fields, array_keys($fields))) . "\n" .
"}";
}
private static function printFields($type)
{
$fields = array_values($type->getFields());
return implode("\n", array_map(function($f, $i) {
return self::printDescription($f, ' ', !$i) . ' ' .
$f->name . self::printArgs($f->args, ' ') . ': ' .
(string) $f->getType() . self::printDeprecated($f);
}, $fields, array_keys($fields)));
}
private static function printArgs($args, $indentation = '')
{
if (count($args) === 0) {
if (! $args) {
return '';
}
// If every arg does not have a description, print them on one line.
if (Utils::every($args, function($arg) { return empty($arg->description); })) {
return '(' . implode(', ', array_map('self::printInputValue', $args)) . ')';
if (Utils::every(
$args,
static function ($arg) : bool {
return strlen($arg->description ?? '') === 0;
}
)) {
return '(' . implode(', ', array_map('static::printInputValue', $args)) . ')';
}
return "(\n" . implode("\n", array_map(function($arg, $i) use ($indentation) {
return self::printDescription($arg, ' ' . $indentation, !$i) . ' ' . $indentation .
self::printInputValue($arg);
}, $args, array_keys($args))) . "\n" . $indentation . ')';
return sprintf(
"(\n%s\n%s)",
implode(
"\n",
array_map(
static function ($arg, $i) use ($indentation, $options) : string {
return static::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation .
static::printInputValue($arg);
},
$args,
array_keys($args)
)
),
$indentation
);
}
private static function printInputValue($arg)
protected static function printInputValue($arg) : string
{
$argDecl = $arg->name . ': ' . (string) $arg->getType();
if ($arg->defaultValueExists()) {
$argDecl .= ' = ' . Printer::doPrint(AST::astFromValue($arg->defaultValue, $arg->getType()));
}
return $argDecl;
}
private static function printDirective($directive)
/**
* @param array<string, bool> $options
*/
public static function printType(Type $type, array $options = []) : string
{
return self::printDescription($directive) .
'directive @' . $directive->name . self::printArgs($directive->args) .
' on ' . implode(' | ', $directive->locations);
if ($type instanceof ScalarType) {
return static::printScalar($type, $options);
}
if ($type instanceof ObjectType) {
return static::printObject($type, $options);
}
if ($type instanceof InterfaceType) {
return static::printInterface($type, $options);
}
if ($type instanceof UnionType) {
return static::printUnion($type, $options);
}
if ($type instanceof EnumType) {
return static::printEnum($type, $options);
}
if ($type instanceof InputObjectType) {
return static::printInputObject($type, $options);
}
throw new Error(sprintf('Unknown type: %s.', Utils::printSafe($type)));
}
private static function printDeprecated($fieldOrEnumVal)
/**
* @param array<string, bool> $options
*/
protected static function printScalar(ScalarType $type, array $options) : string
{
return sprintf('%sscalar %s', static::printDescription($options, $type), $type->name);
}
/**
* @param array<string, bool> $options
*/
protected static function printObject(ObjectType $type, array $options) : string
{
$interfaces = $type->getInterfaces();
$implementedInterfaces = count($interfaces) > 0
? ' implements ' . implode(
' & ',
array_map(
static function (InterfaceType $interface) : string {
return $interface->name;
},
$interfaces
)
)
: '';
return static::printDescription($options, $type) .
sprintf("type %s%s {\n%s\n}", $type->name, $implementedInterfaces, static::printFields($options, $type));
}
/**
* @param array<string, bool> $options
*/
protected static function printFields(array $options, $type) : string
{
$fields = array_values($type->getFields());
return implode(
"\n",
array_map(
static function ($f, $i) use ($options) : string {
return static::printDescription($options, $f, ' ', ! $i) . ' ' .
$f->name . static::printArgs($options, $f->args, ' ') . ': ' .
(string) $f->getType() . static::printDeprecated($f);
},
$fields,
array_keys($fields)
)
);
}
protected static function printDeprecated($fieldOrEnumVal) : string
{
$reason = $fieldOrEnumVal->deprecationReason;
if (empty($reason)) {
if ($reason === null) {
return '';
}
if ($reason === '' || $reason === Directive::DEFAULT_DEPRECATION_REASON) {
return ' @deprecated';
}
return ' @deprecated(reason: ' .
Printer::doPrint(AST::astFromValue($reason, Type::string())) . ')';
}
private static function printDescription($def, $indentation = '', $firstInBlock = true)
/**
* @param array<string, bool> $options
*/
protected static function printInterface(InterfaceType $type, array $options) : string
{
if (!$def->description) {
return '';
}
$lines = explode("\n", $def->description);
$description = $indentation && !$firstInBlock ? "\n" : '';
foreach ($lines as $line) {
if ($line === '') {
$description .= $indentation . "#\n";
} else {
// For > 120 character long lines, cut at space boundaries into sublines
// of ~80 chars.
$sublines = self::breakLine($line, 120 - strlen($indentation));
foreach ($sublines as $subline) {
$description .= $indentation . '# ' . $subline . "\n";
}
}
}
return $description;
$interfaces = $type->getInterfaces();
$implementedInterfaces = count($interfaces) > 0
? ' implements ' . implode(
' & ',
array_map(
static function (InterfaceType $interface) : string {
return $interface->name;
},
$interfaces
)
)
: '';
return static::printDescription($options, $type) .
sprintf("interface %s%s {\n%s\n}", $type->name, $implementedInterfaces, static::printFields($options, $type));
}
private static function breakLine($line, $len)
/**
* @param array<string, bool> $options
*/
protected static function printUnion(UnionType $type, array $options) : string
{
if (strlen($line) < $len + 5) {
return [$line];
}
preg_match_all("/((?: |^).{15," . ($len - 40) . "}(?= |$))/", $line, $parts);
$parts = $parts[0];
return array_map(function($part) {
return trim($part);
}, $parts);
return static::printDescription($options, $type) .
sprintf('union %s = %s', $type->name, implode(' | ', $type->getTypes()));
}
}
/**
* @param array<string, bool> $options
*/
protected static function printEnum(EnumType $type, array $options) : string
{
return static::printDescription($options, $type) .
sprintf("enum %s {\n%s\n}", $type->name, static::printEnumValues($type->getValues(), $options));
}
/**
* @param array<string, bool> $options
*/
protected static function printEnumValues($values, array $options) : string
{
return implode(
"\n",
array_map(
static function ($value, $i) use ($options) : string {
return static::printDescription($options, $value, ' ', ! $i) . ' ' .
$value->name . static::printDeprecated($value);
},
$values,
array_keys($values)
)
);
}
/**
* @param array<string, bool> $options
*/
protected static function printInputObject(InputObjectType $type, array $options) : string
{
$fields = array_values($type->getFields());
return static::printDescription($options, $type) .
sprintf(
"input %s {\n%s\n}",
$type->name,
implode(
"\n",
array_map(
static function ($f, $i) use ($options) : string {
return static::printDescription($options, $f, ' ', ! $i) . ' ' . static::printInputValue($f);
},
$fields,
array_keys($fields)
)
)
);
}
/**
* @param array<string, bool> $options
*
* @api
*/
public static function printIntrospectionSchema(Schema $schema, array $options = []) : string
{
return static::printFilteredSchema(
$schema,
[Directive::class, 'isSpecifiedDirective'],
[Introspection::class, 'isIntrospectionType'],
$options
);
}
}