From f65b1d07a973ed06299a532f10140f3d570312b8 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Mon, 6 Mar 2023 14:48:02 +0100 Subject: [PATCH] Add rector config (#1338) --- .gitattributes | 35 +++++++------- Makefile | 11 ++++- composer.json | 14 +++++- .../01-blog/Blog/Type/Field/HtmlField.php | 8 ++-- generate-class-reference.php | 6 +-- rector.php | 30 ++++++++++++ src/Error/Error.php | 10 ++-- src/Error/FormattedError.php | 10 ++-- src/Executor/ExecutionResult.php | 4 +- src/Executor/ReferenceExecutor.php | 4 +- src/Executor/Values.php | 10 ++-- src/GraphQL.php | 4 +- src/Language/AST/Node.php | 4 -- src/Language/Lexer.php | 13 ++--- src/Language/Visitor.php | 36 +++++++------- src/Server/Helper.php | 2 +- src/Type/Introspection.php | 3 +- src/Type/Schema.php | 6 +-- src/Type/SchemaConfig.php | 2 +- src/Utils/AST.php | 16 +++---- src/Utils/BreakingChangesFinder.php | 29 +++++------ src/Utils/SchemaExtender.php | 10 ++-- src/Utils/SchemaPrinter.php | 44 ++++++++--------- src/Utils/Utils.php | 2 +- src/Utils/Value.php | 6 +-- src/Validator/DocumentValidator.php | 8 ++-- src/Validator/QueryValidationContext.php | 4 +- src/Validator/Rules/FieldsOnCorrectType.php | 7 ++- src/Validator/Rules/KnownArgumentNames.php | 2 +- src/Validator/Rules/KnownTypeNames.php | 3 +- src/Validator/Rules/NoFragmentCycles.php | 8 ++-- .../Rules/OverlappingFieldsCanBeMerged.php | 10 ++-- .../Rules/PossibleTypeExtensions.php | 6 +-- src/Validator/Rules/QueryComplexity.php | 8 ++-- src/Validator/Rules/ValuesOfCorrectType.php | 6 +-- .../Rules/VariablesInAllowedPosition.php | 2 +- tests/ErrorHelper.php | 2 +- tests/Executor/AbstractPromiseTest.php | 2 +- tests/Executor/AbstractTest.php | 2 +- tests/Executor/TestClasses/Cat.php | 17 ++----- tests/Executor/TestClasses/Dog.php | 17 ++----- tests/Executor/VariablesTest.php | 6 +-- tests/Language/LexerTest.php | 4 +- tests/Language/VisitorTest.php | 10 ++-- tests/Type/DefinitionTest.php | 6 +-- tests/Type/IntrospectionTest.php | 24 ++++------ tests/Type/ValidationTest.php | 48 +++++++------------ tests/Utils/SchemaExtenderTest.php | 6 +-- .../SomeObjectClassType.php | 2 +- tests/Validator/FieldsOnCorrectTypeTest.php | 12 ++--- 50 files changed, 255 insertions(+), 286 deletions(-) create mode 100644 rector.php diff --git a/.gitattributes b/.gitattributes index 573d96fad..aa89919b6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,20 +1,21 @@ # Set the default behavior, in case people don't have core.autocrlf set. * text eol=lf -.github export-ignore -benchmarks export-ignore -tests export-ignore -examples export-ignore -phpstan export-ignore -.codecov.yml export-ignore -.gitattributes export-ignore -.gitignore export-ignore -CONTRIBUTING.md export-ignore -generate-class-reference.php export-ignore -mkdocs.yml export-ignore -phpbench.json export-ignore -.php-cs-fixer.php export-ignore -phpstan.neon.dist export-ignore -phpstan-baseline.neon export-ignore -phpunit.xml.dist export-ignore -renovate.json export-ignore +/.github export-ignore +/benchmarks export-ignore +/tests export-ignore +/examples export-ignore +/phpstan export-ignore +/.codecov.yml export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/CONTRIBUTING.md export-ignore +/generate-class-reference.php export-ignore +/mkdocs.yml export-ignore +/phpbench.json export-ignore +/.php-cs-fixer.php export-ignore +/phpstan.neon.dist export-ignore +/phpstan-baseline.neon export-ignore +/phpunit.xml.dist export-ignore +/rector.php export-ignore +/renovate.json export-ignore diff --git a/Makefile b/Makefile index e81ee5b68..ea58954bf 100644 --- a/Makefile +++ b/Makefile @@ -6,8 +6,15 @@ help: ## Displays this list of targets with descriptions @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m%-30s\033[0m %s\n", $$1, $$2}' .PHONY: fix -fix: vendor - composer fix +fix: rector php-cs-fixer ## Automatic code fixes + +.PHONY: rector +rector: vendor ## Automatic code fixes with Rector + composer rector + +.PHONY: php-cs-fixer +php-cs-fixer: vendor ## Fix code style + composer php-cs-fixer .PHONY: stan stan: ## Runs static analysis with phpstan diff --git a/composer.json b/composer.json index 03d7375fd..8ee00724b 100644 --- a/composer.json +++ b/composer.json @@ -28,6 +28,7 @@ "psr/http-message": "^1", "react/http": "^1.6", "react/promise": "^2.9", + "rector/rector": "^0.15.18", "symfony/polyfill-php81": "^1.23", "symfony/var-exporter": "^5 || ^6", "thecodingmachine/safe": "^1.3 || ^2" @@ -59,9 +60,18 @@ }, "scripts": { "bench": "phpbench run", - "check": "composer fix && composer stan && composer test", + "check": [ + "@fix", + "@stan", + "@test" + ], "docs": "php generate-class-reference.php", - "fix": "php-cs-fixer fix", + "fix": [ + "@rector", + "@php-cs-fixer" + ], + "php-cs-fixer": "php-cs-fixer fix", + "rector": "rector process", "stan": "phpstan", "test": "phpunit" } diff --git a/examples/01-blog/Blog/Type/Field/HtmlField.php b/examples/01-blog/Blog/Type/Field/HtmlField.php index 998982a1b..159771006 100644 --- a/examples/01-blog/Blog/Type/Field/HtmlField.php +++ b/examples/01-blog/Blog/Type/Field/HtmlField.php @@ -34,11 +34,9 @@ public static function build(array $config): array $html = $resolver($rootValue, $args); $text = \strip_tags($html); - if (isset($args['maxLength'])) { - $safeText = \mb_substr($text, 0, $args['maxLength']); - } else { - $safeText = $text; - } + $safeText = isset($args['maxLength']) + ? \mb_substr($text, 0, $args['maxLength']) + : $text; switch ($args['format']) { case ContentFormatType::FORMAT_HTML: diff --git a/generate-class-reference.php b/generate-class-reference.php index 323f0ffd8..471485cf6 100644 --- a/generate-class-reference.php +++ b/generate-class-reference.php @@ -78,7 +78,7 @@ function renderClass(ReflectionClass $class, array $options): string $constants[] = "const {$name} = " . VarExporter::export($value) . ';'; } - if (count($constants) > 0) { + if ($constants !== []) { $constants = "```php\n" . implode("\n", $constants) . "\n```"; $content .= "### {$className} Constants\n\n{$constants}\n\n"; } @@ -92,7 +92,7 @@ function renderClass(ReflectionClass $class, array $options): string } } - if (count($props) > 0) { + if ($props !== []) { $props = "```php\n" . implode("\n\n", $props) . "\n```"; $content .= "### {$className} Props\n\n{$props}\n\n"; } @@ -106,7 +106,7 @@ function renderClass(ReflectionClass $class, array $options): string } } - if (count($methods) > 0) { + if ($methods !== []) { $methods = implode("\n\n", $methods); $content .= "### {$className} Methods\n\n{$methods}\n\n"; } diff --git a/rector.php b/rector.php new file mode 100644 index 000000000..594baf351 --- /dev/null +++ b/rector.php @@ -0,0 +1,30 @@ +sets([ + SetList::CODE_QUALITY, + ]); + $rectorConfig->skip([ + CallableThisArrayToAnonymousFunctionRector::class, // Callable in array form is shorter and more efficient + IssetOnPropertyObjectToPropertyExistsRector::class, // isset() is nice when moving towards typed properties + FlipTypeControlToUseExclusiveTypeRector::class, // Unnecessarily complex with PHPStan + UnusedForeachValueToArrayKeysRector::class, // Less efficient + ]); + $rectorConfig->paths([ + __DIR__ . '/examples', + __DIR__ . '/phpstan', + __DIR__ . '/src', + __DIR__ . '/tests', + __DIR__ . '/.php-cs-fixer.php', + __DIR__ . '/generate-class-reference.php', + __DIR__ . '/rector.php', + ]); + $rectorConfig->phpstanConfig(__DIR__ . '/phpstan.neon'); +}; diff --git a/src/Error/Error.php b/src/Error/Error.php index a6d4213b3..cfd019787 100644 --- a/src/Error/Error.php +++ b/src/Error/Error.php @@ -92,7 +92,7 @@ public function __construct( $this->positions = $positions; $this->path = $path; - if (\is_array($extensions) && \count($extensions) > 0) { + if (\is_array($extensions) && $extensions !== []) { $this->extensions = $extensions; } elseif ($previous instanceof ProvidesExtensions) { $this->extensions = $previous->getExtensions(); @@ -167,9 +167,9 @@ protected function isLocated(): bool $nodes = $this->getNodes(); return $path !== null - && \count($path) > 0 + && $path !== [] && $nodes !== null - && \count($nodes) > 0; + && $nodes !== []; } public function isClientSafe(): bool @@ -227,11 +227,11 @@ public function getLocations(): array $nodes = $this->getNodes(); $this->locations = []; - if ($source !== null && \count($positions) !== 0) { + if ($source !== null && $positions !== []) { foreach ($positions as $position) { $this->locations[] = $source->getLocation($position); } - } elseif ($nodes !== null && \count($nodes) !== 0) { + } elseif ($nodes !== null && $nodes !== []) { foreach ($nodes as $node) { if (isset($node->loc->source)) { $this->locations[] = $node->loc->source->getLocation($node->loc->start); diff --git a/src/Error/FormattedError.php b/src/Error/FormattedError.php index 3a12b0037..276f7e917 100644 --- a/src/Error/FormattedError.php +++ b/src/Error/FormattedError.php @@ -42,7 +42,7 @@ public static function printError(Error $error): string $printedLocations = []; $nodes = $error->nodes; - if (isset($nodes) && \count($nodes) > 0) { + if (isset($nodes) && $nodes !== []) { foreach ($nodes as $node) { $location = $node->loc; if (isset($location)) { @@ -55,14 +55,14 @@ public static function printError(Error $error): string } } } - } elseif ($error->getSource() !== null && \count($error->getLocations()) !== 0) { + } elseif ($error->getSource() !== null && $error->getLocations() !== []) { $source = $error->getSource(); foreach ($error->getLocations() as $location) { $printedLocations[] = self::highlightSourceAtLocation($source, $location); } } - return \count($printedLocations) === 0 + return $printedLocations === [] ? $error->getMessage() : \implode("\n\n", \array_merge([$error->getMessage()], $printedLocations)) . "\n"; } @@ -141,7 +141,7 @@ public static function createFromException(\Throwable $exception, int $debugFlag static fn (SourceLocation $loc): array => $loc->toSerializableArray(), $exception->getLocations() ); - if (\count($locations) > 0) { + if ($locations !== []) { $formattedError['locations'] = $locations; } @@ -152,7 +152,7 @@ public static function createFromException(\Throwable $exception, int $debugFlag if ($exception instanceof ProvidesExtensions) { $extensions = $exception->getExtensions(); - if (\is_array($extensions) && \count($extensions) > 0) { + if (\is_array($extensions) && $extensions !== []) { $formattedError['extensions'] = $extensions; } } diff --git a/src/Executor/ExecutionResult.php b/src/Executor/ExecutionResult.php index 6fe1962b8..1398ccfab 100644 --- a/src/Executor/ExecutionResult.php +++ b/src/Executor/ExecutionResult.php @@ -157,7 +157,7 @@ public function toArray(int $debug = DebugFlag::NONE): array { $result = []; - if (\count($this->errors) > 0) { + if ($this->errors !== []) { $errorsHandler = $this->errorsHandler ?? static fn (array $errors, callable $formatter): array => \array_map($formatter, $errors); @@ -176,7 +176,7 @@ public function toArray(int $debug = DebugFlag::NONE): array $result['data'] = $this->data; } - if ($this->extensions !== null && \count($this->extensions) > 0) { + if ($this->extensions !== null && $this->extensions !== []) { $result['extensions'] = $this->extensions; } diff --git a/src/Executor/ReferenceExecutor.php b/src/Executor/ReferenceExecutor.php index 7fb87153b..2298765ed 100644 --- a/src/Executor/ReferenceExecutor.php +++ b/src/Executor/ReferenceExecutor.php @@ -197,7 +197,7 @@ protected static function buildExecutionContext( } } - if (\count($errors) > 0) { + if ($errors !== []) { return $errors; } @@ -1095,7 +1095,7 @@ protected function defaultTypeResolver($value, $contextValue, ResolveInfo $info, } } - if (\count($promisedIsTypeOfResults) > 0) { + if ($promisedIsTypeOfResults !== []) { return $this->exeContext->promiseAdapter ->all($promisedIsTypeOfResults) ->then(static function ($isTypeOfResults) use ($possibleTypes): ?ObjectType { diff --git a/src/Executor/Values.php b/src/Executor/Values.php index db3373482..ee6a0bc66 100644 --- a/src/Executor/Values.php +++ b/src/Executor/Values.php @@ -130,11 +130,9 @@ public static function getVariableValues(Schema $schema, NodeList $varDefNodes, } } - if (\count($errors) > 0) { - return [$errors, null]; - } - - return [null, $coercedValues]; + return $errors === [] + ? [null, $coercedValues] + : [$errors, null]; } /** @@ -176,7 +174,7 @@ public static function getDirectiveValues(Directive $directiveDef, Node $node, ? */ public static function getArgumentValues($def, Node $node, ?array $variableValues = null): array { - if (\count($def->args) === 0) { + if ($def->args === []) { return []; } diff --git a/src/GraphQL.php b/src/GraphQL.php index bded57793..d43a57ad2 100644 --- a/src/GraphQL.php +++ b/src/GraphQL.php @@ -127,7 +127,7 @@ public static function promiseToExecute( ? $source : Parser::parse(new Source($source, 'GraphQL')); - if ($validationRules === null || \count($validationRules) === 0) { + if ($validationRules === null || $validationRules === []) { $queryComplexity = DocumentValidator::getRule(QueryComplexity::class); assert($queryComplexity instanceof QueryComplexity, 'should not register a different rule for QueryComplexity'); @@ -142,7 +142,7 @@ public static function promiseToExecute( $validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules); - if (\count($validationErrors) > 0) { + if ($validationErrors !== []) { return $promiseAdapter->createFulfilled( new ExecutionResult(null, $validationErrors) ); diff --git a/src/Language/AST/Node.php b/src/Language/AST/Node.php index e3e30b054..d64f3dfe9 100644 --- a/src/Language/AST/Node.php +++ b/src/Language/AST/Node.php @@ -39,10 +39,6 @@ abstract class Node implements \JsonSerializable */ public function __construct(array $vars) { - if (\count($vars) === 0) { - return; - } - Utils::assign($this, $vars); } diff --git a/src/Language/Lexer.php b/src/Language/Lexer.php index 53148b732..2d0901e7a 100644 --- a/src/Language/Lexer.php +++ b/src/Language/Lexer.php @@ -52,25 +52,25 @@ class Lexer /** * The (1-indexed) line containing the current token. */ - public int $line; + public int $line = 1; /** * The character offset at which the current line begins. */ - public int $lineStart; + public int $lineStart = 0; /** * Current cursor position for UTF8 encoding of the source. */ - private int $position; + private int $position = 0; /** * Current cursor position for ASCII representation of the source. */ - private int $byteStreamPosition; + private int $byteStreamPosition = 0; /** - * @phpstan-param ParserOptions $options + * @phpstan-param ParserOptions $options */ public function __construct(Source $source, array $options = []) { @@ -80,9 +80,6 @@ public function __construct(Source $source, array $options = []) $this->options = $options; $this->lastToken = $startOfFileToken; $this->token = $startOfFileToken; - $this->line = 1; - $this->lineStart = 0; - $this->position = $this->byteStreamPosition = 0; } public function advance(): Token diff --git a/src/Language/Visitor.php b/src/Language/Visitor.php index 512a225cb..b62c0c90c 100644 --- a/src/Language/Visitor.php +++ b/src/Language/Visitor.php @@ -189,7 +189,7 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null $isLeaving = $index === \count($keys); $key = null; $node = null; - $isEdited = $isLeaving && \count($edits) > 0; + $isEdited = $isLeaving && $edits !== []; if ($isLeaving) { $key = $ancestors === [] @@ -197,7 +197,6 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null : $path[\count($path) - 1]; $node = $parent; $parent = \array_pop($ancestors); - if ($isEdited) { if ($node instanceof Node || $node instanceof NodeList) { $node = $node->cloneDeep(); @@ -225,7 +224,6 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null } } } - // @phpstan-ignore-next-line the stack is guaranteed to be non-empty at this point [ 'index' => $index, @@ -233,21 +231,19 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null 'edits' => $edits, 'inList' => $inList, ] = \array_pop($stack); + } elseif ($parent === null) { + $node = $root; } else { - if ($parent === null) { - $node = $root; - } else { - $key = $inList - ? $index - : $keys[$index]; - $node = $parent instanceof NodeList - ? $parent[$key] - : $parent->{$key}; - if ($node === null) { - continue; - } - $path[] = $key; + $key = $inList + ? $index + : $keys[$index]; + $node = $parent instanceof NodeList + ? $parent[$key] + : $parent->{$key}; + if ($node === null) { + continue; } + $path[] = $key; } $result = null; @@ -314,11 +310,11 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null $parent = $node; } - } while (\count($stack) > 0); + } while ($stack !== []); - return \count($edits) > 0 - ? $edits[0][1] - : $root; + return $edits === [] + ? $root + : $edits[0][1]; } /** diff --git a/src/Server/Helper.php b/src/Server/Helper.php index a4cb799ba..3a49cdfc8 100644 --- a/src/Server/Helper.php +++ b/src/Server/Helper.php @@ -234,7 +234,7 @@ protected function promiseToExecuteOperation( $errors = $this->validateOperationParams($op); - if (\count($errors) > 0) { + if ($errors !== []) { $locatedErrors = \array_map( [Error::class, 'createLocatedError'], $errors diff --git a/src/Type/Introspection.php b/src/Type/Introspection.php index 51e02443f..16fdaced1 100644 --- a/src/Type/Introspection.php +++ b/src/Type/Introspection.php @@ -243,8 +243,7 @@ public static function _schema(): ObjectType 'resolve' => static fn (Schema $schema): ?ObjectType => $schema->getQueryType(), ], 'mutationType' => [ - 'description' => 'If this server supports mutation, the type that ' - . 'mutation operations will be rooted at.', + 'description' => 'If this server supports mutation, the type that mutation operations will be rooted at.', 'type' => self::_type(), 'resolve' => static fn (Schema $schema): ?ObjectType => $schema->getMutationType(), ], diff --git a/src/Type/Schema.php b/src/Type/Schema.php index 2167f3ac7..8e089957b 100644 --- a/src/Type/Schema.php +++ b/src/Type/Schema.php @@ -472,10 +472,8 @@ public function assertValid(): void $type->assertValid(); // Make sure type loader returns the same instance as registered in other places of schema - if (isset($this->config->typeLoader)) { - if ($this->loadType($name) !== $type) { - throw new InvariantViolation("Type loader returns different instance for {$name} than field/argument definitions. Make sure you always return the same instance for the same type name."); - } + if (isset($this->config->typeLoader) && $this->loadType($name) !== $type) { + throw new InvariantViolation("Type loader returns different instance for {$name} than field/argument definitions. Make sure you always return the same instance for the same type name."); } } } diff --git a/src/Type/SchemaConfig.php b/src/Type/SchemaConfig.php index 6b3d354e4..8fc1e2533 100644 --- a/src/Type/SchemaConfig.php +++ b/src/Type/SchemaConfig.php @@ -83,7 +83,7 @@ public static function create(array $options = []): self { $config = new static(); - if (\count($options) > 0) { + if ($options !== []) { if (isset($options['query'])) { $config->setQuery($options['query']); } diff --git a/src/Utils/AST.php b/src/Utils/AST.php index ec667c2d7..c2050c919 100644 --- a/src/Utils/AST.php +++ b/src/Utils/AST.php @@ -93,11 +93,9 @@ public static function fromArray(array $node): Node } if (\is_array($value)) { - if (isset($value[0]) || \count($value) === 0) { - $value = new NodeList($value); - } else { - $value = self::fromArray($value); - } + $value = isset($value[0]) || $value === [] + ? new NodeList($value) + : self::fromArray($value); } $instance->{$key} = $value; @@ -193,11 +191,9 @@ public static function astFromValue($value, InputType $type): ?ValueNode $fields = $type->getFields(); $fieldNodes = []; foreach ($fields as $fieldName => $field) { - if ($isArrayLike) { - $fieldValue = $value[$fieldName] ?? null; - } else { - $fieldValue = $value->{$fieldName} ?? null; - } + $fieldValue = $isArrayLike + ? $value[$fieldName] ?? null + : $value->{$fieldName} ?? null; // Have to check additionally if key exists, since we differentiate between // "no key" and "value is null": diff --git a/src/Utils/BreakingChangesFinder.php b/src/Utils/BreakingChangesFinder.php index 2e632b383..ac4609d3a 100644 --- a/src/Utils/BreakingChangesFinder.php +++ b/src/Utils/BreakingChangesFinder.php @@ -185,8 +185,8 @@ public static function findFieldsThatChangedTypeOnObjectOrInterfaceTypes( foreach ($oldTypeMap as $typeName => $oldType) { $newType = $newTypeMap[$typeName] ?? null; if ( - ! ($oldType instanceof ObjectType || $oldType instanceof InterfaceType) - || ! ($newType instanceof ObjectType || $newType instanceof InterfaceType) + ! $oldType instanceof ObjectType && ! $oldType instanceof InterfaceType + || ! $newType instanceof ObjectType && ! $newType instanceof InterfaceType || ! ($newType instanceof $oldType) ) { continue; @@ -288,17 +288,12 @@ public static function findFieldsThatChangedTypeOnInputObjectTypes( $newFieldType ); if (! $isSafe) { - if ($oldFieldType instanceof NamedType) { - $oldFieldTypeString = $oldFieldType->name; - } else { - $oldFieldTypeString = $oldFieldType; - } - - if ($newFieldType instanceof NamedType) { - $newFieldTypeString = $newFieldType->name; - } else { - $newFieldTypeString = $newFieldType; - } + $oldFieldTypeString = $oldFieldType instanceof NamedType + ? $oldFieldType->name + : $oldFieldType; + $newFieldTypeString = $newFieldType instanceof NamedType + ? $newFieldType->name + : $newFieldType; $breakingChanges[] = [ 'type' => self::BREAKING_CHANGE_FIELD_CHANGED_KIND, @@ -468,8 +463,8 @@ public static function findArgChanges( foreach ($oldTypeMap as $typeName => $oldType) { $newType = $newTypeMap[$typeName] ?? null; if ( - ! ($oldType instanceof ObjectType || $oldType instanceof InterfaceType) - || ! ($newType instanceof ObjectType || $newType instanceof InterfaceType) + ! $oldType instanceof ObjectType && ! $oldType instanceof InterfaceType + || ! $newType instanceof ObjectType && ! $newType instanceof InterfaceType || ! ($newType instanceof $oldType) ) { continue; @@ -845,8 +840,8 @@ public static function findInterfacesAddedToObjectTypes( foreach ($newTypeMap as $typeName => $newType) { $oldType = $oldTypeMap[$typeName] ?? null; if ( - ! ($oldType instanceof ObjectType || $oldType instanceof InterfaceType) - || ! ($newType instanceof ObjectType || $newType instanceof InterfaceType) + ! $oldType instanceof ObjectType && ! $oldType instanceof InterfaceType + || ! $newType instanceof ObjectType && ! $newType instanceof InterfaceType ) { continue; } diff --git a/src/Utils/SchemaExtender.php b/src/Utils/SchemaExtender.php index e93cb43bb..59c152c1c 100644 --- a/src/Utils/SchemaExtender.php +++ b/src/Utils/SchemaExtender.php @@ -115,10 +115,10 @@ protected function doExtend( } if ( - \count($this->typeExtensionsMap) === 0 - && \count($typeDefinitionMap) === 0 - && \count($directiveDefinitions) === 0 - && \count($schemaExtensions) === 0 + $this->typeExtensionsMap === [] + && $typeDefinitionMap === [] + && $directiveDefinitions === [] + && $schemaExtensions === [] && $schemaDef === null ) { return $schema; @@ -583,7 +583,7 @@ protected function getMergedDirectives(Schema $schema, array $directiveDefinitio $schema->getDirectives() ); - if (\count($directives) === 0) { + if ($directives === []) { throw new InvariantViolation('Schema must have default directives.'); } diff --git a/src/Utils/SchemaPrinter.php b/src/Utils/SchemaPrinter.php index 2038a8c10..55f854a01 100644 --- a/src/Utils/SchemaPrinter.php +++ b/src/Utils/SchemaPrinter.php @@ -110,7 +110,7 @@ public static function printType(Type $type, array $options = []): string /** * @param callable(Directive $directive): bool $directiveFilter - * @param callable(Type &NamedType $type): bool $typeFilter + * @param callable(Type&NamedType $type): bool $typeFilter * @param array $options * * @phpstan-param Options $options @@ -120,7 +120,7 @@ protected static function printFilteredSchema(Schema $schema, callable $directiv $directives = \array_filter($schema->getDirectives(), $directiveFilter); $types = \array_filter($schema->getTypeMap(), $typeFilter); - if (isset($options['sortTypes']) && $options['sortTypes'] === true) { + if (isset($options['sortTypes']) && $options['sortTypes']) { ksort($types); } @@ -240,11 +240,11 @@ protected static function printDescription(array $options, $def, string $indenta */ protected static function printArgs(array $options, array $args, string $indentation = ''): string { - if (\count($args) === 0) { + if ($args === []) { return ''; } - if (isset($options['sortArguments']) && $options['sortArguments'] === true) { + if (isset($options['sortArguments']) && $options['sortArguments']) { usort($args, static fn (Argument $left, Argument $right): int => $left->name <=> $right->name); } @@ -351,7 +351,7 @@ protected static function printFields(array $options, $type): string $previousHasDescription = false; $fieldDefinitions = $type->getFields(); - if (isset($options['sortFields']) && $options['sortFields'] === true) { + if (isset($options['sortFields']) && $options['sortFields']) { ksort($fieldDefinitions); } @@ -401,15 +401,15 @@ protected static function printImplementedInterfaces(ImplementingType $type): st { $interfaces = $type->getInterfaces(); - return \count($interfaces) > 0 - ? ' implements ' . \implode( - ' & ', - \array_map( - static fn (InterfaceType $interface): string => $interface->name, - $interfaces - ) - ) - : ''; + return $interfaces === [] + ? '' + : ' implements ' . \implode( + ' & ', + \array_map( + static fn (InterfaceType $interface): string => $interface->name, + $interfaces + ) + ); } /** @@ -433,9 +433,9 @@ protected static function printInterface(InterfaceType $type, array $options): s protected static function printUnion(UnionType $type, array $options): string { $types = $type->getTypes(); - $types = \count($types) > 0 - ? ' = ' . \implode(' | ', $types) - : ''; + $types = $types === [] + ? '' + : ' = ' . \implode(' | ', $types); return static::printDescription($options, $type) . 'union ' . $type->name . $types; } @@ -451,7 +451,7 @@ protected static function printEnum(EnumType $type, array $options): string $firstInBlock = true; $valueDefinitions = $type->getValues(); - if (isset($options['sortEnumValues']) && $options['sortEnumValues'] === true) { + if (isset($options['sortEnumValues']) && $options['sortEnumValues']) { usort($valueDefinitions, static fn (EnumValueDefinition $left, EnumValueDefinition $right): int => $left->name <=> $right->name); } @@ -479,7 +479,7 @@ protected static function printInputObject(InputObjectType $type, array $options $firstInBlock = true; $fieldDefinitions = $type->getFields(); - if (isset($options['sortInputFields']) && $options['sortInputFields'] === true) { + if (isset($options['sortInputFields']) && $options['sortInputFields']) { ksort($fieldDefinitions); } @@ -500,8 +500,8 @@ protected static function printInputObject(InputObjectType $type, array $options */ protected static function printBlock(array $items): string { - return \count($items) > 0 - ? " {\n" . \implode("\n", $items) . "\n}" - : ''; + return $items === [] + ? '' + : " {\n" . \implode("\n", $items) . "\n}"; } } diff --git a/src/Utils/Utils.php b/src/Utils/Utils.php index e188bbc99..834f98d74 100644 --- a/src/Utils/Utils.php +++ b/src/Utils/Utils.php @@ -233,7 +233,7 @@ public static function quotedOrList(array $items): string */ public static function orList(array $items): string { - if (\count($items) === 0) { + if ($items === []) { return ''; } diff --git a/src/Utils/Value.php b/src/Utils/Value.php index 093f788ff..8876af6b9 100644 --- a/src/Utils/Value.php +++ b/src/Utils/Value.php @@ -154,9 +154,9 @@ public static function coerceInputValue($value, InputType $type, ?array $path = array_keys($fields) ); $message = "Field \"{$fieldName}\" is not defined by type \"{$type->name}\"." - . (count($suggestions) > 0 - ? ' Did you mean ' . Utils::quotedOrList($suggestions) . '?' - : ''); + . ($suggestions === [] + ? '' + : ' Did you mean ' . Utils::quotedOrList($suggestions) . '?'); $errors = self::add( $errors, diff --git a/src/Validator/DocumentValidator.php b/src/Validator/DocumentValidator.php index 76714eade..fac058e18 100644 --- a/src/Validator/DocumentValidator.php +++ b/src/Validator/DocumentValidator.php @@ -100,7 +100,7 @@ public static function validate( ): array { $rules ??= static::allRules(); - if (\count($rules) === 0) { + if ($rules === []) { return []; } @@ -266,7 +266,7 @@ public static function validateSDL( ): array { $rules ??= self::sdlRules(); - if (\count($rules) === 0) { + if ($rules === []) { return []; } @@ -288,7 +288,7 @@ public static function validateSDL( public static function assertValidSDL(DocumentNode $documentAST): void { $errors = self::validateSDL($documentAST); - if (\count($errors) > 0) { + if ($errors !== []) { throw new Error(self::combineErrorMessages($errors)); } } @@ -296,7 +296,7 @@ public static function assertValidSDL(DocumentNode $documentAST): void public static function assertValidSDLExtension(DocumentNode $documentAST, Schema $schema): void { $errors = self::validateSDL($documentAST, $schema); - if (\count($errors) > 0) { + if ($errors !== []) { throw new Error(self::combineErrorMessages($errors)); } } diff --git a/src/Validator/QueryValidationContext.php b/src/Validator/QueryValidationContext.php index 5bd1afaa9..c11053979 100644 --- a/src/Validator/QueryValidationContext.php +++ b/src/Validator/QueryValidationContext.php @@ -158,7 +158,7 @@ public function getRecursivelyReferencedFragments(OperationDefinitionNode $opera $fragments = []; $collectedNames = []; $nodesToVisit = [$operation]; - while (\count($nodesToVisit) > 0) { + while ($nodesToVisit !== []) { $node = \array_pop($nodesToVisit); $spreads = $this->getFragmentSpreads($node); foreach ($spreads as $spread) { @@ -197,7 +197,7 @@ public function getFragmentSpreads(HasSelectionSet $node): array $spreads = []; $setsToVisit = [$node->getSelectionSet()]; - while (\count($setsToVisit) > 0) { + while ($setsToVisit !== []) { $set = \array_pop($setsToVisit); foreach ($set->selections as $selection) { diff --git a/src/Validator/Rules/FieldsOnCorrectType.php b/src/Validator/Rules/FieldsOnCorrectType.php index 650b4576d..d08ed4111 100644 --- a/src/Validator/Rules/FieldsOnCorrectType.php +++ b/src/Validator/Rules/FieldsOnCorrectType.php @@ -79,10 +79,9 @@ protected function getSuggestedTypeNames(Schema $schema, Type $type, string $fie } // This interface type defines this field. - $interfaceUsageCount[$possibleInterface->name] - = ! isset($interfaceUsageCount[$possibleInterface->name]) - ? 0 - : $interfaceUsageCount[$possibleInterface->name] + 1; + $interfaceUsageCount[$possibleInterface->name] = isset($interfaceUsageCount[$possibleInterface->name]) + ? $interfaceUsageCount[$possibleInterface->name] + 1 + : 0; } } diff --git a/src/Validator/Rules/KnownArgumentNames.php b/src/Validator/Rules/KnownArgumentNames.php index 334ec198f..649b87a52 100644 --- a/src/Validator/Rules/KnownArgumentNames.php +++ b/src/Validator/Rules/KnownArgumentNames.php @@ -65,7 +65,7 @@ public static function unknownArgMessage(string $argName, string $fieldName, str { $message = "Unknown argument \"{$argName}\" on field \"{$fieldName}\" of type \"{$typeName}\"."; - if (\count($suggestedArgs) > 0) { + if ($suggestedArgs !== []) { $suggestions = Utils::quotedOrList($suggestedArgs); $message .= " Did you mean {$suggestions}?"; } diff --git a/src/Validator/Rules/KnownTypeNames.php b/src/Validator/Rules/KnownTypeNames.php index 0f1c0ef7d..700e2eb46 100644 --- a/src/Validator/Rules/KnownTypeNames.php +++ b/src/Validator/Rules/KnownTypeNames.php @@ -97,7 +97,8 @@ public function getASTVisitor(ValidationContext $context): array public static function unknownTypeMessage(string $type, array $suggestedTypes): string { $message = "Unknown type \"{$type}\"."; - if (\count($suggestedTypes) > 0) { + + if ($suggestedTypes !== []) { $suggestionList = Utils::quotedOrList($suggestedTypes); $message .= " Did you mean {$suggestionList}?"; } diff --git a/src/Validator/Rules/NoFragmentCycles.php b/src/Validator/Rules/NoFragmentCycles.php index dc17c07dc..f3db96955 100644 --- a/src/Validator/Rules/NoFragmentCycles.php +++ b/src/Validator/Rules/NoFragmentCycles.php @@ -54,7 +54,7 @@ protected function detectCycleRecursive(FragmentDefinitionNode $fragment, QueryV $spreadNodes = $context->getFragmentSpreads($fragment); - if (\count($spreadNodes) === 0) { + if ($spreadNodes === []) { return; } @@ -94,9 +94,9 @@ protected function detectCycleRecursive(FragmentDefinitionNode $fragment, QueryV */ public static function cycleErrorMessage(string $fragName, array $spreadNames = []): string { - $via = \count($spreadNames) > 0 - ? ' via ' . \implode(', ', $spreadNames) - : ''; + $via = $spreadNames === [] + ? '' + : ' via ' . \implode(', ', $spreadNames); return "Cannot spread fragment \"{$fragName}\" within itself{$via}."; } diff --git a/src/Validator/Rules/OverlappingFieldsCanBeMerged.php b/src/Validator/Rules/OverlappingFieldsCanBeMerged.php index 2430f0950..5c6279d02 100644 --- a/src/Validator/Rules/OverlappingFieldsCanBeMerged.php +++ b/src/Validator/Rules/OverlappingFieldsCanBeMerged.php @@ -243,12 +243,10 @@ protected function internalCollectFieldsAndFragmentNames( $fieldName = $selection->name->value; $fieldDef = null; if ( - $parentType instanceof ObjectType - || $parentType instanceof InterfaceType + ($parentType instanceof ObjectType + || $parentType instanceof InterfaceType) && $parentType->hasField($fieldName) ) { - if ($parentType->hasField($fieldName)) { - $fieldDef = $parentType->getField($fieldName); - } + $fieldDef = $parentType->getField($fieldName); } $responseName = isset($selection->alias) @@ -816,7 +814,7 @@ protected function subfieldConflicts( FieldNode $ast1, FieldNode $ast2 ): ?array { - if (\count($conflicts) === 0) { + if ($conflicts === []) { return null; } diff --git a/src/Validator/Rules/PossibleTypeExtensions.php b/src/Validator/Rules/PossibleTypeExtensions.php index 07a9c1d46..595c93ba1 100644 --- a/src/Validator/Rules/PossibleTypeExtensions.php +++ b/src/Validator/Rules/PossibleTypeExtensions.php @@ -73,9 +73,9 @@ public function getSDLVisitor(SDLValidationContext $context): array ...array_keys($existingTypesMap), ]; $suggestedTypes = Utils::suggestionList($typeName, $allTypeNames); - $didYouMean = \count($suggestedTypes) > 0 - ? ' Did you mean ' . Utils::quotedOrList($suggestedTypes) . '?' - : ''; + $didYouMean = $suggestedTypes === [] + ? '' + : ' Did you mean ' . Utils::quotedOrList($suggestedTypes) . '?'; $context->reportError( new Error( "Cannot extend type \"{$typeName}\" because it is not defined.{$didYouMean}", diff --git a/src/Validator/Rules/QueryComplexity.php b/src/Validator/Rules/QueryComplexity.php index 6fd2f51db..4ba9d5bca 100644 --- a/src/Validator/Rules/QueryComplexity.php +++ b/src/Validator/Rules/QueryComplexity.php @@ -69,7 +69,7 @@ public function getVisitor(QueryValidationContext $context): array 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context): void { $errors = $context->getErrors(); - if (\count($errors) > 0) { + if ($errors !== []) { return; } @@ -115,7 +115,7 @@ protected function nodeComplexity(SelectionNode $node): int : 0; $fieldDef = $this->fieldDefinition($node); - if ($fieldDef instanceof FieldDefinition && isset($fieldDef->complexityFn)) { + if ($fieldDef instanceof FieldDefinition && $fieldDef->complexityFn !== null) { $fieldArguments = $this->buildFieldArguments($node); return ($fieldDef->complexityFn)($childrenComplexity, $fieldArguments); @@ -160,7 +160,7 @@ protected function directiveExcludesField(FieldNode $node): bool $this->variableDefs, $this->getRawVariableValues() ); - if ($errors !== null && \count($errors) > 0) { + if ($errors !== null && $errors !== []) { throw new Error(\implode( "\n\n", \array_map( @@ -230,7 +230,7 @@ protected function buildFieldArguments(FieldNode $node): array $rawVariableValues ); - if (is_array($errors) && \count($errors) > 0) { + if (is_array($errors) && $errors !== []) { throw new Error(\implode( "\n\n", \array_map( diff --git a/src/Validator/Rules/ValuesOfCorrectType.php b/src/Validator/Rules/ValuesOfCorrectType.php index c0d89e04c..4e83f3b3e 100644 --- a/src/Validator/Rules/ValuesOfCorrectType.php +++ b/src/Validator/Rules/ValuesOfCorrectType.php @@ -109,9 +109,9 @@ public function getVisitor(QueryValidationContext $context): array $node->name->value, \array_keys($parentType->getFields()) ); - $didYouMean = \count($suggestions) > 0 - ? ' Did you mean ' . Utils::quotedOrList($suggestions) . '?' - : null; + $didYouMean = $suggestions === [] + ? null + : ' Did you mean ' . Utils::quotedOrList($suggestions) . '?'; $context->reportError( new Error( diff --git a/src/Validator/Rules/VariablesInAllowedPosition.php b/src/Validator/Rules/VariablesInAllowedPosition.php index c20853e1c..2435e979d 100644 --- a/src/Validator/Rules/VariablesInAllowedPosition.php +++ b/src/Validator/Rules/VariablesInAllowedPosition.php @@ -92,7 +92,7 @@ protected function allowedVariableUsage(Schema $schema, Type $varType, $varDefau { if ($locationType instanceof NonNull && ! $varType instanceof NonNull) { $hasNonNullVariableDefaultValue = $varDefaultValue !== null && ! $varDefaultValue instanceof NullValueNode; - $hasLocationDefaultValue = ! (Utils::undefined() === $locationDefaultValue); + $hasLocationDefaultValue = Utils::undefined() !== $locationDefaultValue; if (! $hasNonNullVariableDefaultValue && ! $hasLocationDefaultValue) { return false; } diff --git a/tests/ErrorHelper.php b/tests/ErrorHelper.php index 26ab20d46..708c0fc14 100644 --- a/tests/ErrorHelper.php +++ b/tests/ErrorHelper.php @@ -21,7 +21,7 @@ public static function create(string $error, array $locations = []): array { $formatted = ['message' => $error]; - if (\count($locations) > 0) { + if ($locations !== []) { $formatted['locations'] = \array_map( static fn (SourceLocation $loc): array => $loc->toArray(), $locations diff --git a/tests/Executor/AbstractPromiseTest.php b/tests/Executor/AbstractPromiseTest.php index b71e5ad43..82adaa2e7 100644 --- a/tests/Executor/AbstractPromiseTest.php +++ b/tests/Executor/AbstractPromiseTest.php @@ -475,7 +475,7 @@ public function testResolveTypeAllowsResolvingWithTypeName(): void $PetType = new InterfaceType([ 'name' => 'Pet', 'resolveType' => static fn ($obj): Deferred => new Deferred( - static function () use ($obj) { + static function () use ($obj): ?string { if ($obj instanceof Dog) { return 'Dog'; } diff --git a/tests/Executor/AbstractTest.php b/tests/Executor/AbstractTest.php index ce758950c..7b8ce115c 100644 --- a/tests/Executor/AbstractTest.php +++ b/tests/Executor/AbstractTest.php @@ -649,7 +649,7 @@ public function testResolveTypeAllowsResolvingWithTypeName(): void { $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => static function ($obj) { + 'resolveType' => static function ($obj): ?string { if ($obj instanceof Dog) { return 'Dog'; } diff --git a/tests/Executor/TestClasses/Cat.php b/tests/Executor/TestClasses/Cat.php index 91d546f44..e3dcb1f3d 100644 --- a/tests/Executor/TestClasses/Cat.php +++ b/tests/Executor/TestClasses/Cat.php @@ -4,27 +4,20 @@ final class Cat { - /** @var string */ - public $name; + public string $name; - /** @var bool */ - public $meows; + public bool $meows; - /** @var Cat|null */ - public $mother; + public ?Cat $mother = null; - /** @var Cat|null */ - public $father; + public ?Cat $father = null; /** @var array */ - public $progeny; + public array $progeny = []; public function __construct(string $name, bool $meows) { $this->name = $name; $this->meows = $meows; - $this->mother = null; - $this->father = null; - $this->progeny = []; } } diff --git a/tests/Executor/TestClasses/Dog.php b/tests/Executor/TestClasses/Dog.php index 7b8032835..7eaf83335 100644 --- a/tests/Executor/TestClasses/Dog.php +++ b/tests/Executor/TestClasses/Dog.php @@ -4,27 +4,20 @@ final class Dog { - /** @var string */ - public $name; + public string $name; - /** @var bool */ - public $woofs; + public bool $woofs; - /** @var Dog|null */ - public $mother; + public ?Dog $mother = null; - /** @var Dog|null */ - public $father; + public ?Dog $father = null; /** @var array */ - public $progeny; + public array $progeny = []; public function __construct(string $name, bool $woofs) { $this->name = $name; $this->woofs = $woofs; - $this->mother = null; - $this->father = null; - $this->progeny = []; } } diff --git a/tests/Executor/VariablesTest.php b/tests/Executor/VariablesTest.php index e9b4d0d01..716d59964 100644 --- a/tests/Executor/VariablesTest.php +++ b/tests/Executor/VariablesTest.php @@ -964,8 +964,7 @@ public function testDoesNotAllowInvalidTypesToBeUsedAsValues(): void $expected = [ 'errors' => [ [ - 'message' => 'Variable "$input" expected value of type "TestType!" which cannot ' - . 'be used as an input type.', + 'message' => 'Variable "$input" expected value of type "TestType!" which cannot be used as an input type.', 'locations' => [['line' => 2, 'column' => 25]], ], ], @@ -989,8 +988,7 @@ public function testDoesNotAllowUnknownTypesToBeUsedAsValues(): void $expected = [ 'errors' => [ [ - 'message' => 'Variable "$input" expected value of type "UnknownType!" which ' - . 'cannot be used as an input type.', + 'message' => 'Variable "$input" expected value of type "UnknownType!" which cannot be used as an input type.', 'locations' => [['line' => 2, 'column' => 25]], ], ], diff --git a/tests/Language/LexerTest.php b/tests/Language/LexerTest.php index 1a61c9d82..cea9fb04f 100644 --- a/tests/Language/LexerTest.php +++ b/tests/Language/LexerTest.php @@ -430,7 +430,7 @@ public function reportsUsefulStringErrors(): iterable ], ['"null-byte is not \u0000 end of file"', 'Invalid character within String: "\\u0000"', $this->loc(1, 19)], ['"multi' . "\n" . 'line"', 'Unterminated string.', $this->loc(1, 7)], - ['"multi' . "\r" . 'line"', 'Unterminated string.', $this->loc(1, 7)], + ['"multi line"', 'Unterminated string.', $this->loc(1, 7)], ['"bad esc \\', 'Unterminated string.', $this->loc(1, 11)], ['"bad \\z esc"', 'Invalid character escape sequence: \\z', $this->loc(1, 7)], ['"bad \\x esc"', 'Invalid character escape sequence: \\x', $this->loc(1, 7)], @@ -725,7 +725,7 @@ public function testDoubleLinkedList(): void $tokens = []; for ($tok = $startToken; $tok; $tok = $tok->next) { - if (\count($tokens) > 0) { + if ($tokens !== []) { // Tokens are double-linked, prev should point to last seen token. self::assertSame($tokens[\count($tokens) - 1], $tok->prev); } diff --git a/tests/Language/VisitorTest.php b/tests/Language/VisitorTest.php index 6cf0c1524..c763d7a96 100644 --- a/tests/Language/VisitorTest.php +++ b/tests/Language/VisitorTest.php @@ -90,12 +90,10 @@ private function getNodeByPath(DocumentNode $ast, array $path): object $result = $ast; foreach ($path as $key) { - if ($result instanceof NodeList) { - $result = $result[$key]; - } else { - /** @phpstan-ignore-next-line */ - $result = $result->{$key}; - } + $result = $result instanceof NodeList + ? $result[$key] + // @phpstan-ignore-next-line variable property access on mixed + : $result->{$key}; } return $result; diff --git a/tests/Type/DefinitionTest.php b/tests/Type/DefinitionTest.php index 0e968f599..0988e3e1e 100644 --- a/tests/Type/DefinitionTest.php +++ b/tests/Type/DefinitionTest.php @@ -1635,8 +1635,7 @@ public function testRejectsAnInputObjectTypeWithResolvers(): void $this->expectException(InvariantViolation::class); $this->expectExceptionMessage( - 'SomeInputObject.f field has a resolve property, ' - . 'but Input Types cannot define resolvers.' + 'SomeInputObject.f field has a resolve property, but Input Types cannot define resolvers.' ); $inputObjType->assertValid(); } @@ -1730,8 +1729,7 @@ public function testRejectsAnInputObjectTypeWithResolverConstant(): void ]); $this->expectException(InvariantViolation::class); $this->expectExceptionMessage( - 'SomeInputObject.f field has a resolve property, ' - . 'but Input Types cannot define resolvers.' + 'SomeInputObject.f field has a resolve property, but Input Types cannot define resolvers.' ); $inputObjType->assertValid(); } diff --git a/tests/Type/IntrospectionTest.php b/tests/Type/IntrospectionTest.php index 2b83e6764..57d7b91fc 100644 --- a/tests/Type/IntrospectionTest.php +++ b/tests/Type/IntrospectionTest.php @@ -1350,8 +1350,7 @@ public function testExposesDescriptionsOnTypesAndFields(): void ], [ 'name' => 'mutationType', - 'description' => 'If this server supports mutation, the type that ' - . 'mutation operations will be rooted at.', + 'description' => 'If this server supports mutation, the type that mutation operations will be rooted at.', ], [ 'name' => 'subscriptionType', @@ -1402,38 +1401,31 @@ enumValues { 'name' => 'SCALAR', ], [ - 'description' => 'Indicates this type is an object. ' - . '`fields` and `interfaces` are valid fields.', + 'description' => 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', 'name' => 'OBJECT', ], [ - 'description' => 'Indicates this type is an interface. ' - . '`fields`, `interfaces`, and `possibleTypes` are valid fields.', + 'description' => 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', 'name' => 'INTERFACE', ], [ - 'description' => 'Indicates this type is a union. ' - . '`possibleTypes` is a valid field.', + 'description' => 'Indicates this type is a union. `possibleTypes` is a valid field.', 'name' => 'UNION', ], [ - 'description' => 'Indicates this type is an enum. ' - . '`enumValues` is a valid field.', + 'description' => 'Indicates this type is an enum. `enumValues` is a valid field.', 'name' => 'ENUM', ], [ - 'description' => 'Indicates this type is an input object. ' - . '`inputFields` is a valid field.', + 'description' => 'Indicates this type is an input object. `inputFields` is a valid field.', 'name' => 'INPUT_OBJECT', ], [ - 'description' => 'Indicates this type is a list. ' - . '`ofType` is a valid field.', + 'description' => 'Indicates this type is a list. `ofType` is a valid field.', 'name' => 'LIST', ], [ - 'description' => 'Indicates this type is a non-null. ' - . '`ofType` is a valid field.', + 'description' => 'Indicates this type is a non-null. `ofType` is a valid field.', 'name' => 'NON_NULL', ], ], diff --git a/tests/Type/ValidationTest.php b/tests/Type/ValidationTest.php index 484bce730..751993941 100644 --- a/tests/Type/ValidationTest.php +++ b/tests/Type/ValidationTest.php @@ -579,8 +579,7 @@ public function testRejectsAnObjectTypeWithIncorrectlyNamedFields(): void $schema->validate(), [ [ - 'message' => 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but ' - . '"bad-name-with-dashes" does not.', + 'message' => 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "bad-name-with-dashes" does not.', ], ] ); @@ -1839,8 +1838,7 @@ interface AnotherInterface { $schema->validate(), [ [ - 'message' => 'Interface field AnotherInterface.field expected but ' - . 'AnotherObject does not provide it.', + 'message' => 'Interface field AnotherInterface.field expected but AnotherObject does not provide it.', 'locations' => [['line' => 7, 'column' => 9], ['line' => 10, 'column' => 7]], ], ] @@ -1870,8 +1868,7 @@ interface AnotherInterface { $schema->validate(), [ [ - 'message' => 'Interface field AnotherInterface.field expects type String but ' - . 'AnotherObject.field is type Int.', + 'message' => 'Interface field AnotherInterface.field expects type String but AnotherObject.field is type Int.', 'locations' => [['line' => 7, 'column' => 31], ['line' => 11, 'column' => 31]], ], ] @@ -1904,8 +1901,7 @@ interface AnotherInterface { $schema->validate(), [ [ - 'message' => 'Interface field AnotherInterface.field expects type A but ' - . 'AnotherObject.field is type B.', + 'message' => 'Interface field AnotherInterface.field expects type A but AnotherObject.field is type B.', 'locations' => [['line' => 10, 'column' => 16], ['line' => 14, 'column' => 16]], ], ] @@ -2047,8 +2043,7 @@ interface AnotherInterface { $schema->validate(), [ [ - 'message' => 'Interface field AnotherInterface.field expects type String but ' - . 'AnotherObject.field is type Int.', + 'message' => 'Interface field AnotherInterface.field expects type String but AnotherObject.field is type Int.', 'locations' => [['line' => 7, 'column' => 31], ['line' => 11, 'column' => 28]], ], [ @@ -2226,8 +2221,7 @@ interface AnotherInterface { $schema->validate(), [ [ - 'message' => 'Interface field AnotherInterface.field expects type String! ' - . 'but AnotherObject.field is type String.', + 'message' => 'Interface field AnotherInterface.field expects type String! but AnotherObject.field is type String.', 'locations' => [['line' => 7, 'column' => 16], ['line' => 11, 'column' => 16]], ], ] @@ -2261,8 +2255,7 @@ interface AnotherInterface implements SuperInterface { $schema->validate(), [ [ - 'message' => 'Type AnotherObject must implement SuperInterface ' - . 'because it is implemented by AnotherInterface.', + 'message' => 'Type AnotherObject must implement SuperInterface because it is implemented by AnotherInterface.', 'locations' => [['line' => 10, 'column' => 45], ['line' => 14, 'column' => 37]], ], ] @@ -2359,8 +2352,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Interface field ParentInterface.field expected ' - . 'but ChildInterface does not provide it.', + 'message' => 'Interface field ParentInterface.field expected but ChildInterface does not provide it.', 'locations' => [['line' => 7, 'column' => 9], ['line' => 10, 'column' => 7]], ], ] @@ -2390,8 +2382,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Interface field ParentInterface.field expects type String ' - . 'but ChildInterface.field is type Int.', + 'message' => 'Interface field ParentInterface.field expects type String but ChildInterface.field is type Int.', 'locations' => [['line' => 7, 'column' => 31], ['line' => 11, 'column' => 31]], ], ] @@ -2424,8 +2415,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Interface field ParentInterface.field expects type A ' - . 'but ChildInterface.field is type B.', + 'message' => 'Interface field ParentInterface.field expects type A but ChildInterface.field is type B.', 'locations' => [['line' => 10, 'column' => 16], ['line' => 14, 'column' => 16]], ], ] @@ -2566,8 +2556,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Interface field ParentInterface.field expects type String ' - . 'but ChildInterface.field is type Int.', + 'message' => 'Interface field ParentInterface.field expects type String but ChildInterface.field is type Int.', 'locations' => [['line' => 7, 'column' => 31], ['line' => 11, 'column' => 28]], ], [ @@ -2744,8 +2733,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Interface field ParentInterface.field expects type String! ' - . 'but ChildInterface.field is type String.', + 'message' => 'Interface field ParentInterface.field expects type String! but ChildInterface.field is type String.', 'locations' => [['line' => 7, 'column' => 16], ['line' => 11, 'column' => 16]], ], ] @@ -2779,8 +2767,7 @@ interface ChildInterface implements ParentInterface { $schema->validate(), [ [ - 'message' => 'Type ChildInterface must implement SuperInterface ' - . 'because it is implemented by ParentInterface.', + 'message' => 'Type ChildInterface must implement SuperInterface because it is implemented by ParentInterface.', 'locations' => [['line' => 10, 'column' => 44], ['line' => 14, 'column' => 43]], ], ] @@ -2806,8 +2793,7 @@ interface FooInterface implements FooInterface { $schema->validate(), [ [ - 'message' => 'Type FooInterface cannot implement itself ' - . 'because it would create a circular reference.', + 'message' => 'Type FooInterface cannot implement itself because it would create a circular reference.', 'locations' => [['line' => 6, 'column' => 41]], ], ] @@ -2837,13 +2823,11 @@ interface BarInterface implements FooInterface { $schema->validate(), [ [ - 'message' => 'Type FooInterface cannot implement BarInterface ' - . 'because it would create a circular reference.', + 'message' => 'Type FooInterface cannot implement BarInterface because it would create a circular reference.', 'locations' => [['line' => 10, 'column' => 41], ['line' => 6, 'column' => 41]], ], [ - 'message' => 'Type BarInterface cannot implement FooInterface ' - . 'because it would create a circular reference.', + 'message' => 'Type BarInterface cannot implement FooInterface because it would create a circular reference.', 'locations' => [['line' => 6, 'column' => 41], ['line' => 10, 'column' => 41]], ], ] diff --git a/tests/Utils/SchemaExtenderTest.php b/tests/Utils/SchemaExtenderTest.php index a3c84acc0..a73a8d54f 100644 --- a/tests/Utils/SchemaExtenderTest.php +++ b/tests/Utils/SchemaExtenderTest.php @@ -1840,10 +1840,8 @@ public function testSupportsTypeConfigDecorator(): void $fooValue = 'bar'; $typeConfigDecorator = static function ($typeConfig) use ($fooValue) { - switch ($typeConfig['name']) { - case 'Foo': - $typeConfig['resolveField'] = static fn (): string => $fooValue; - break; + if ($typeConfig['name'] === 'Foo') { + $typeConfig['resolveField'] = static fn (): string => $fooValue; } return $typeConfig; diff --git a/tests/Utils/SchemaExtenderTest/SomeObjectClassType.php b/tests/Utils/SchemaExtenderTest/SomeObjectClassType.php index daf9b2fb8..bda5ea50a 100644 --- a/tests/Utils/SchemaExtenderTest/SomeObjectClassType.php +++ b/tests/Utils/SchemaExtenderTest/SomeObjectClassType.php @@ -10,7 +10,7 @@ */ final class SomeObjectClassType extends ObjectType { - public function isTypeOf($objectValue, $context, ResolveInfo $info) + public function isTypeOf($objectValue, $context, ResolveInfo $info): bool { return true; } diff --git a/tests/Validator/FieldsOnCorrectTypeTest.php b/tests/Validator/FieldsOnCorrectTypeTest.php index 07d33e59a..278118c3b 100644 --- a/tests/Validator/FieldsOnCorrectTypeTest.php +++ b/tests/Validator/FieldsOnCorrectTypeTest.php @@ -356,8 +356,7 @@ public function testWorksWithNoSuggestions(): void */ public function testWorksWithNoSmallNumbersOfTypeSuggestions(): void { - $expected = 'Cannot query field "f" on type "T". ' - . 'Did you mean to use an inline fragment on "A" or "B"?'; + $expected = 'Cannot query field "f" on type "T". Did you mean to use an inline fragment on "A" or "B"?'; self::assertEquals($expected, FieldsOnCorrectType::undefinedFieldMessage('f', 'T', ['A', 'B'], [])); } @@ -367,8 +366,7 @@ public function testWorksWithNoSmallNumbersOfTypeSuggestions(): void */ public function testWorksWithNoSmallNumbersOfFieldSuggestions(): void { - $expected = 'Cannot query field "f" on type "T". ' - . 'Did you mean "z" or "y"?'; + $expected = 'Cannot query field "f" on type "T". Did you mean "z" or "y"?'; self::assertEquals($expected, FieldsOnCorrectType::undefinedFieldMessage('f', 'T', [], ['z', 'y'])); } @@ -378,8 +376,7 @@ public function testWorksWithNoSmallNumbersOfFieldSuggestions(): void */ public function testOnlyShowsOneSetOfSuggestionsAtATimePreferringTypes(): void { - $expected = 'Cannot query field "f" on type "T". ' - . 'Did you mean to use an inline fragment on "A" or "B"?'; + $expected = 'Cannot query field "f" on type "T". Did you mean to use an inline fragment on "A" or "B"?'; self::assertEquals($expected, FieldsOnCorrectType::undefinedFieldMessage('f', 'T', ['A', 'B'], ['z', 'y'])); } @@ -408,8 +405,7 @@ public function testLimitsLotsOfTypeSuggestions(): void */ public function testLimitsLotsOfFieldSuggestions(): void { - $expected = 'Cannot query field "f" on type "T". ' - . 'Did you mean "z", "y", "x", "w", or "v"?'; + $expected = 'Cannot query field "f" on type "T". Did you mean "z", "y", "x", "w", or "v"?'; self::assertEquals( $expected,