From 11d32413378d9be39b796d39309928cd15de78e4 Mon Sep 17 00:00:00 2001 From: Alex Bouma Date: Thu, 2 Dec 2021 13:25:20 +0100 Subject: [PATCH 1/9] Fix undefined array key with missing cache config (#1994) --- CHANGELOG.md | 4 ++++ docs/5/performance/schema-caching.md | 2 +- docs/master/performance/schema-caching.md | 2 +- src/Schema/AST/ASTCache.php | 23 +++++++++++++---------- 4 files changed, 19 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 770c4aaa07..79fbeb6e34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +### Fixed + +- Prevent `Undefined array key` error when using cache version 2 and not having all version 1 configuration present https://github.com/nuwave/lighthouse/pull/1994 + ## v5.27.1 ### Changed diff --git a/docs/5/performance/schema-caching.md b/docs/5/performance/schema-caching.md index 249d8f0dbc..38d30c12a0 100644 --- a/docs/5/performance/schema-caching.md +++ b/docs/5/performance/schema-caching.md @@ -14,7 +14,7 @@ using the [cache](../api-reference/commands.md#cache) artisan command: The structure of the serialized schema can change between Lighthouse releases. In order to prevent errors, use cache version 2 and a deployment method that -atomically updates both the cache file and the dependencies, e.g. K8s. +atomically updates both the cache file and the dependencies, e.g. K8s. ## Development diff --git a/docs/master/performance/schema-caching.md b/docs/master/performance/schema-caching.md index 249d8f0dbc..38d30c12a0 100644 --- a/docs/master/performance/schema-caching.md +++ b/docs/master/performance/schema-caching.md @@ -14,7 +14,7 @@ using the [cache](../api-reference/commands.md#cache) artisan command: The structure of the serialized schema can change between Lighthouse releases. In order to prevent errors, use cache version 2 and a deployment method that -atomically updates both the cache file and the dependencies, e.g. K8s. +atomically updates both the cache file and the dependencies, e.g. K8s. ## Development diff --git a/src/Schema/AST/ASTCache.php b/src/Schema/AST/ASTCache.php index 8f8c272caa..19cdb89801 100644 --- a/src/Schema/AST/ASTCache.php +++ b/src/Schema/AST/ASTCache.php @@ -59,18 +59,21 @@ public function __construct(ConfigRepository $config) $this->enable = $cacheConfig['enable']; $version = $cacheConfig['version'] ?? 1; - if (! in_array($version, [1, 2])) { - throw new UnknownCacheVersionException($version); - } - $this->version = $version; - // Version 1 - $this->store = $cacheConfig['store'] ?? null; - $this->key = $cacheConfig['key']; - $this->ttl = $cacheConfig['ttl']; + switch ($version) { + case 1: + $this->store = $cacheConfig['store'] ?? null; + $this->key = $cacheConfig['key']; + $this->ttl = $cacheConfig['ttl']; + break; + case 2: + $this->path = $cacheConfig['path'] ?? base_path('bootstrap/cache/lighthouse-schema.php'); + break; + default: + throw new UnknownCacheVersionException($version); + } - // Version 2 - $this->path = $cacheConfig['path'] ?? base_path('bootstrap/cache/lighthouse-schema.php'); + $this->version = $version; } public function isEnabled(): bool From e56266cee9f428556c8b3da9830548c0764934e5 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Thu, 2 Dec 2021 13:26:01 +0100 Subject: [PATCH 2/9] v5.27.2 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79fbeb6e34..d96157be10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +## v5.27.2 + ### Fixed - Prevent `Undefined array key` error when using cache version 2 and not having all version 1 configuration present https://github.com/nuwave/lighthouse/pull/1994 From b4205b51b1c087c68f6126077e29c158f71769a3 Mon Sep 17 00:00:00 2001 From: LavaDesu Date: Sun, 5 Dec 2021 17:30:02 +0700 Subject: [PATCH 3/9] Fix undefined array key with interfaces and two renamed models (#1997) --- CHANGELOG.md | 4 +++ src/Schema/TypeRegistry.php | 2 +- .../Schema/Types/InterfaceTest.php | 33 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d96157be10..044c12efb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +### Fixed + +- Prevent possible `Undefined array key 0` error when there's an interface implemented by two renamed models https://github.com/nuwave/lighthouse/pull/1997 + ## v5.27.2 ### Fixed diff --git a/src/Schema/TypeRegistry.php b/src/Schema/TypeRegistry.php index ee86c6e8fa..ee49e3b4d4 100644 --- a/src/Schema/TypeRegistry.php +++ b/src/Schema/TypeRegistry.php @@ -489,7 +489,7 @@ protected function typeResolverFallback(array $possibleTypes): Closure ); } - return $this->get($actuallyPossibleTypes[0]); + return $this->get(end($actuallyPossibleTypes)); } return $this->get(class_basename($root)); diff --git a/tests/Integration/Schema/Types/InterfaceTest.php b/tests/Integration/Schema/Types/InterfaceTest.php index 710ebe6329..5d2a17f480 100644 --- a/tests/Integration/Schema/Types/InterfaceTest.php +++ b/tests/Integration/Schema/Types/InterfaceTest.php @@ -113,6 +113,39 @@ interface Nameable { $this->assertArrayNotHasKey('id', $result->json('data.namedThings.1')); } + public function testDoesNotErrorOnSecondRenamedModel(): void + { + // This creates one team with it + factory(User::class)->create(); + + $this->schema = /** @lang GraphQL */ <<qualifyTestResolver('fetchResults')}") + } +GRAPHQL; + + $this->expectNotToPerformAssertions(); + $this->graphQL(/** @lang GraphQL */ ' + { + namedThings { + name + } + } + '); + } + public function testThrowsOnAmbiguousSchemaMapping(): void { // This creates one team with it From b28fb817f6d8a410e303a11ae69b4c10ca0f019c Mon Sep 17 00:00:00 2001 From: spawnia Date: Sun, 5 Dec 2021 11:30:27 +0100 Subject: [PATCH 4/9] v5.27.3 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 044c12efb1..4b61538683 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +## v5.27.3 + ### Fixed - Prevent possible `Undefined array key 0` error when there's an interface implemented by two renamed models https://github.com/nuwave/lighthouse/pull/1997 From 8416f68b43cd804c5710d451a0c35a4756a97035 Mon Sep 17 00:00:00 2001 From: Antonio Dal Sie Date: Sun, 5 Dec 2021 22:12:14 +0100 Subject: [PATCH 5/9] Allow clients to order a list of models by an aggregated value of their relations with `@orderBy` Co-authored-by: spawnia --- .gitignore | 1 + CHANGELOG.md | 4 + composer.json | 36 ++-- docs/master/api-reference/directives.md | 178 ++++++---------- docs/master/digging-deeper/ordering.md | 139 ++++++++++++ docs/master/sidebar.js | 1 + src/OrderBy/OrderByDirective.php | 197 ++++++++++++++++-- src/OrderBy/OrderByServiceProvider.php | 71 ++++++- src/Support/Traits/GeneratesColumnsEnum.php | 15 +- src/Validation/RulesGatherer.php | 5 +- .../OrderBy/OrderByDirectiveDBTest.php | 180 ++++++++++++++++ .../OrderBy/OrderByDirectiveTest.php | 101 +++++++++ .../WhereConditionsDirectiveTest.php | 2 +- 13 files changed, 762 insertions(+), 168 deletions(-) create mode 100644 docs/master/digging-deeper/ordering.md diff --git a/.gitignore b/.gitignore index 4238311a59..83f1a988ac 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ # Individual per developer .env .idea +.vscode phpunit.xml # Generated files diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b61538683..4659996249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +### Added + +- Allow clients to order a list of models by an aggregated value of their relations with `@orderBy` https://github.com/nuwave/lighthouse/pull/1848 + ## v5.27.3 ### Fixed diff --git a/composer.json b/composer.json index 14f193271c..6024f2fb30 100644 --- a/composer.json +++ b/composer.json @@ -1,14 +1,13 @@ { "name": "nuwave/lighthouse", - "type": "library", "description": "A framework for serving GraphQL from Laravel", + "license": "MIT", + "type": "library", "keywords": [ "graphql", "laravel", "laravel-graphql" ], - "homepage": "https://lighthouse-php.com", - "license": "MIT", "authors": [ { "name": "Christopher Moore", @@ -21,6 +20,11 @@ "homepage": "https://franke.tech" } ], + "homepage": "https://lighthouse-php.com", + "support": { + "issues": "https://github.com/nuwave/lighthouse/issues", + "source": "https://github.com/nuwave/lighthouse" + }, "require": { "php": ">= 7.2", "ext-json": "*", @@ -67,6 +71,17 @@ "mll-lab/laravel-graphql-playground": "GraphQL IDE for better development workflow - integrated with Laravel", "pusher/pusher-php-server": "Required when using the Pusher Subscriptions driver" }, + "autoload": { + "psr-4": { + "Nuwave\\Lighthouse\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/", + "Benchmarks\\": "benchmarks" + } + }, "config": { "sort-packages": true }, @@ -87,26 +102,11 @@ ] } }, - "autoload": { - "psr-4": { - "Nuwave\\Lighthouse\\": "src/" - } - }, - "autoload-dev": { - "psr-4": { - "Tests\\": "tests/", - "Benchmarks\\": "benchmarks" - } - }, "scripts": { "rector": "rector process -v src/ tests/", "stan": "phpstan analyse --memory-limit 2048M", "test": "phpunit --colors=always", "test:integration": "phpunit --colors=always --testsuite Integration", "test:unit": "phpunit --colors=always --testsuite Unit" - }, - "support": { - "issues": "https://github.com/nuwave/lighthouse/issues", - "source": "https://github.com/nuwave/lighthouse" } } diff --git a/docs/master/api-reference/directives.md b/docs/master/api-reference/directives.md index 7208c0d6b5..f0fa823e9a 100644 --- a/docs/master/api-reference/directives.md +++ b/docs/master/api-reference/directives.md @@ -1989,136 +1989,82 @@ type Query { Sort a result list by one or more given columns. """ directive @orderBy( - """ - Restrict the allowed column names to a well-defined list. - This improves introspection capabilities and security. - Mutually exclusive with the `columnsEnum` argument. - Only used when the directive is added on an argument. - """ - columns: [String!] - - """ - Use an existing enumeration type to restrict the allowed columns to a predefined list. - This allowes you to re-use the same enum for multiple fields. - Mutually exclusive with the `columns` argument. - Only used when the directive is added on an argument. - """ - columnsEnum: String - - """ - The database column for which the order by clause will be applied on. - Only used when the directive is added on a field. - """ - column: String - - """ - The direction of the order by clause. - Only used when the directive is added on a field. - """ - direction: OrderByDirection = ASC + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + Only used when the directive is added on an argument. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + Only used when the directive is added on an argument. + """ + columnsEnum: String + + """ + Allow clients to sort by aggregates on relations. + Only used when the directive is added on an argument. + """ + relations: [OrderByRelation!] + + """ + The database column for which the order by clause will be applied on. + Only used when the directive is added on a field. + """ + column: String + + """ + The direction of the order by clause. + Only used when the directive is added on a field. + """ + direction: OrderByDirection = ASC ) on ARGUMENT_DEFINITION | FIELD_DEFINITION """ Options for the `direction` argument on `@orderBy`. """ enum OrderByDirection { - """ - Sort in ascending order. - """ - ASC + """ + Sort in ascending order. + """ + ASC - """ - Sort in descending order. - """ - DESC -} -``` - -### Client Controlled Ordering - -To enable clients to control the ordering, use this directive on an argument of -a field that is backed by a database query. - -```graphql -type Query { - posts(orderBy: _ @orderBy(columns: ["posted_at", "title"])): [Post!]! @all + """ + Sort in descending order. + """ + DESC } -``` - -The type of the argument can be left blank as `_` , -as Lighthouse will automatically generate an input that takes enumerated column names, -together with the `SortOrder` enum, and add that to your schema: -```graphql -"Allows ordering a list of records." -input QueryPostsOrderByOrderByClause { - "The column that is used for ordering." - column: QueryPostsOrderByColumn! - - "The direction that is used for ordering." - order: SortOrder! -} - -"Order by clause for the `orderBy` argument on the query `posts`." -enum QueryPostsOrderByColumn { - POSTED_AT @enum(value: "posted_at") - TITLE @enum(value: "title") -} - -"The available directions for ordering a list of records." -enum SortOrder { - "Sort records in ascending order." - ASC - - "Sort records in descending order." - DESC -} -``` - -To re-use a list of allowed columns, define your own enumeration type and use the `columnsEnum` argument instead of `columns`: - -```graphql -type Query { - allPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @all - paginatedPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! - @paginate -} - -"A custom description for this custom enum." -enum PostColumn { - # Another reason why you might want to have a custom enum is to - # correct typos or bad naming in column names. - POSTED_AT @enum(value: "postd_timestamp") - TITLE @enum(value: "title") -} -``` - -Lighthouse will still automatically generate the necessary input types and the `SortOrder` enum. -Instead of generating enums for the allowed columns, it will simply use the existing `PostColumn` enum. - -Querying a field that has an `orderBy` argument looks like this: - -```graphql -{ - posts(orderBy: [{ column: POSTED_AT, order: ASC }]) { - title - } -} -``` - -You may pass more than one sorting option to add a secondary ordering. - -### Predefined Ordering +""" +Options for the `relations` argument on `@orderBy`. +""" +input OrderByRelation { + """ + TODO: description + """ + relation: String! -To predefine a default order for your field, use this directive on a field: + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + """ + columns: [String!] -```graphql -type Query { - latestUsers: [User!]! @all @orderBy(column: "created_at", direction: DESC) + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + """ + columnsEnum: String } ``` -Clients won't have to pass any arguments to the field and still receive ordered results by default. +See [ordering](../digging-deeper/ordering.md). ## @paginate diff --git a/docs/master/digging-deeper/ordering.md b/docs/master/digging-deeper/ordering.md new file mode 100644 index 0000000000..8c6ca1c048 --- /dev/null +++ b/docs/master/digging-deeper/ordering.md @@ -0,0 +1,139 @@ +# Ordering + +## Client Controlled Ordering + +To enable clients to control the ordering, use [@orderBy](../api-reference/directives.md#orderby) on an argument of +a field that is backed by a database query. + +```graphql +type Query { + posts(orderBy: _ @orderBy(columns: ["posted_at", "title"])): [Post!]! @all +} +``` + +The type of the argument can be left blank as `_` , +as Lighthouse will automatically generate an input that takes enumerated column names, +together with the `SortOrder` enum, and add that to your schema: + +```graphql +"Order by clause for Query.posts.orderBy." +input QueryPostsOrderByOrderByClause { + "The column that is used for ordering." + column: QueryPostsOrderByColumn! + + "The direction that is used for ordering." + order: SortOrder! +} + +"Allowed column names for Query.posts.orderBy" +enum QueryPostsOrderByColumn { + POSTED_AT @enum(value: "posted_at") + TITLE @enum(value: "title") +} + +"Directions for ordering a list of records." +enum SortOrder { + "Sort records in ascending order." + ASC + + "Sort records in descending order." + DESC +} +``` + +Querying a field that has an `orderBy` argument looks like this: + +```graphql +{ + posts(orderBy: [{ column: POSTED_AT, order: ASC }]) { + title + } +} +``` + +### Secondary Ordering + +You may pass more than one sorting option to add a secondary ordering. + +```graphql +{ + posts(orderBy: [ + { column: POSTED_AT, order: ASC } + { column: TITLE, order: DESC } + ]) { + title + } +} +``` + +### Reuse Columns Enum + +To re-use a list of allowed columns, define your own enumeration type and use the `columnsEnum` argument instead of `columns`: + +```graphql +type Query { + allPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @all + paginatedPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! + @paginate +} + +"A custom description for this custom enum." +enum PostColumn { + # Another reason why you might want to have a custom enum is to + # correct typos or bad naming in column names. + POSTED_AT @enum(value: "postd_timestamp") + TITLE @enum(value: "title") +} +``` + +Lighthouse will still automatically generate the necessary input types and the `SortOrder` enum. +Instead of generating enums for the allowed columns, it will simply use the existing `PostColumn` enum. + +### Ordering By Relations + +You can allow clients to order a list of models by an aggregated value of their relations. +You must specify which relations and which of their columns are allowed. + +```graphql +type Query { + users( + orderBy: _ @orderBy(relations: [ + { + relation: "tasks" + columns: ["difficulty"] + } + ]) + ): [User!]! @all +} +``` + +Lighthouse will automatically generate the appropriate input types and enum values. + +```graphql +{ + users(orderBy: [ + { + tasks: { aggregate: COUNT } + order: ASC + } + { + tasks: { aggregate: MAX, column: DIFFICULTY } + order: DESC + } + ]) { + id + } +} +``` + +## Predefined Ordering + +To predefine a default order for your field, use [@orderBy](../api-reference/directives.md#orderby) on a field: + +```graphql +type Query { + latestUsers: [User!]! @all @orderBy(column: "created_at", direction: DESC) +} +``` + +Clients won't have to pass any arguments to the field and still receive ordered results by default. diff --git a/docs/master/sidebar.js b/docs/master/sidebar.js index d1073be891..0acf52ceee 100644 --- a/docs/master/sidebar.js +++ b/docs/master/sidebar.js @@ -52,6 +52,7 @@ module.exports = [ title: "Digging Deeper", children: [ "digging-deeper/schema-organisation", + "digging-deeper/ordering", "digging-deeper/relay", "digging-deeper/error-handling", "digging-deeper/adding-types-programmatically", diff --git a/src/OrderBy/OrderByDirective.php b/src/OrderBy/OrderByDirective.php index d29d9daff0..28d2a445a0 100644 --- a/src/OrderBy/OrderByDirective.php +++ b/src/OrderBy/OrderByDirective.php @@ -6,9 +6,14 @@ use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\Parser; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Support\Arr; +use Illuminate\Support\Str; +use Nuwave\Lighthouse\Exceptions\DefinitionException; use Nuwave\Lighthouse\Schema\AST\ASTHelper; use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; +use Nuwave\Lighthouse\Support\AppVersion; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; use Nuwave\Lighthouse\Support\Contracts\ArgDirectiveForArray; use Nuwave\Lighthouse\Support\Contracts\ArgManipulator; @@ -42,6 +47,12 @@ public static function definition(): string """ columnsEnum: String + """ + Allow clients to sort by aggregates on relations. + Only used when the directive is added on an argument. + """ + relations: [OrderByRelation!] + """ The database column for which the order by clause will be applied on. Only used when the directive is added on a field. @@ -69,19 +80,68 @@ enum OrderByDirection { """ DESC } + +""" +Options for the `relations` argument on `@orderBy`. +""" +input OrderByRelation { + """ + TODO: description + """ + relation: String! + + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + """ + columnsEnum: String +} GRAPHQL; } /** - * @param array $value + * @param array> $value */ public function handleBuilder($builder, $value): object { foreach ($value as $orderByClause) { - $builder->orderBy( - $orderByClause['column'], - $orderByClause['order'] - ); + $order = Arr::pull($orderByClause, 'order'); + $column = Arr::pull($orderByClause, 'column'); + + if ($column === null) { + if (! $builder instanceof Builder) { + throw new DefinitionException('Can not order by relations on non-Eloquent builders, got: '.get_class($builder)); + } + + // TODO use array_key_first() in PHP 7.3 + $relation = Arr::first(array_keys($orderByClause)); + $relationSnake = Str::snake($relation); + + $relationValues = Arr::first($orderByClause); + + $aggregate = $relationValues['aggregate']; + if ($aggregate === 'count') { + $builder->withCount($relation); + + $column = "{$relationSnake}_count"; + } else { + $operator = 'with'.ucfirst($aggregate); + $relationColumn = $relationValues['column']; + $builder->{$operator}($relation, $relationColumn); + + $column = "{$relationSnake}_{$aggregate}_{$relationColumn}"; + } + } + + $builder->orderBy($column, $order); } return $builder; @@ -93,21 +153,106 @@ public function manipulateArgDefinition( FieldDefinitionNode &$parentField, ObjectTypeDefinitionNode &$parentType ): void { - if ($this->hasAllowedColumns()) { - $restrictedOrderByName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).'OrderByClause'; - $argDefinition->type = Parser::typeReference("[$restrictedOrderByName!]"); - $allowedColumnsEnumName = $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType); - - $documentAST - ->setTypeDefinition( - OrderByServiceProvider::createOrderByClauseInput( - $restrictedOrderByName, - "Order by clause for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`.", - $allowedColumnsEnumName - ) - ); - } else { + if (! $this->hasAllowedColumns() && ! $this->directiveHasArgument('relations')) { $argDefinition->type = Parser::typeReference('['.OrderByServiceProvider::DEFAULT_ORDER_BY_CLAUSE.'!]'); + + return; + } + + $qualifiedOrderByPrefix = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType); + + $allowedColumnsTypeName = $this->hasAllowedColumns() + ? $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType) + : 'String'; + + if ($this->directiveHasArgument('relations')) { + /** @var array $relationsInputs */ + $relationsInputs = []; + + foreach ($this->directiveArgValue('relations') as $relation) { + $relationName = $relation['relation']; + $relationUpper = ucfirst($relationName); + + $inputName = $qualifiedOrderByPrefix.$relationUpper; + + $relationsInputs[$relationName] = $inputName; + + $columns = $relation['columns'] ?? null; + if (null !== $columns) { + $allowedRelationColumnsEnumName = "{$qualifiedOrderByPrefix}{$relationUpper}Column"; + + $documentAST->setTypeDefinition( + $this->createAllowedColumnsEnum( + $argDefinition, + $parentField, + $parentType, + $columns, + $allowedRelationColumnsEnumName + ) + ); + + $documentAST->setTypeDefinition( + OrderByServiceProvider::createRelationAggregateFunctionForColumnInput( + $inputName, + "Aggregate specification for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.{$relationName}.", + $allowedRelationColumnsEnumName + ) + ); + } else { + $documentAST->setTypeDefinition( + OrderByServiceProvider::createRelationAggregateFunctionInput( + $inputName, + "Aggregate specification for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.{$relationName}." + ) + ); + } + } + + $qualifiedRelationOrderByName = "{$qualifiedOrderByPrefix}RelationOrderByClause"; + + /** @var array $relationNames */ + $relationNames = array_keys($relationsInputs); + + $inputMerged = <<name->value}.{$parentField->name->value}.{$argDefinition->name->value}." + input {$qualifiedRelationOrderByName} { + "The column that is used for ordering." + column: $allowedColumnsTypeName {$this->mutuallyExclusiveRule($relationNames)} + + "The direction that is used for ordering." + order: SortOrder! +GRAPHQL; + + foreach ($relationsInputs as $relation => $input) { + /** @var array $otherOptions */ + $otherOptions = ['column']; + foreach ($relationNames as $relationName) { + if ($relationName !== $relation) { + $otherOptions [] = $relationName; + } + } + + $inputMerged .= <<mutuallyExclusiveRule($otherOptions)} + +GRAPHQL; + } + + $argDefinition->type = Parser::typeReference("[{$qualifiedRelationOrderByName}!]"); + + $documentAST->setTypeDefinition(Parser::inputObjectTypeDefinition("{$inputMerged}}")); + } else { + $restrictedOrderByName = $qualifiedOrderByPrefix.'OrderByClause'; + $argDefinition->type = Parser::typeReference('['.$restrictedOrderByName.'!]'); + + $documentAST->setTypeDefinition( + OrderByServiceProvider::createOrderByClauseInput( + $restrictedOrderByName, + "Order by clause for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.", + $allowedColumnsTypeName + ) + ); } } @@ -118,4 +263,18 @@ public function handleFieldBuilder(object $builder): object $this->directiveArgValue('direction', 'ASC') ); } + + /** + * @param array $otherOptions + */ + protected function mutuallyExclusiveRule(array $otherOptions): string + { + if (AppVersion::below(8.0)) { + return ''; + } + + $optionsString = implode(',', $otherOptions); + + return "@rules(apply: [\"prohibits:{$optionsString}\"])"; + } } diff --git a/src/OrderBy/OrderByServiceProvider.php b/src/OrderBy/OrderByServiceProvider.php index ab7f70396c..e1d4e29566 100644 --- a/src/OrderBy/OrderByServiceProvider.php +++ b/src/OrderBy/OrderByServiceProvider.php @@ -30,8 +30,8 @@ static function (): string { function (ManipulateAST $manipulateAST): void { $documentAST = $manipulateAST->documentAST; $documentAST->setTypeDefinition( - Parser::enumTypeDefinition(/** @lang GraphQL */ ' - "The available directions for ordering a list of records." + Parser::enumTypeDefinition(/* @lang GraphQL */ ' + "Directions for ordering a list of records." enum SortOrder { "Sort records in ascending order." ASC @@ -39,8 +39,37 @@ enum SortOrder { "Sort records in descending order." DESC } - ' - ) + ') + ); + $documentAST->setTypeDefinition( + Parser::enumTypeDefinition(/* @lang GraphQL */ ' + "Aggregate functions when ordering by a relation without specifying a column." + enum OrderByRelationAggregateFunction { + "Amount of items." + COUNT @enum(value: "count") + } + ') + ); + $documentAST->setTypeDefinition( + Parser::enumTypeDefinition(/* @lang GraphQL */ ' + "Aggregate functions when ordering by a relation that may specify a column." + enum OrderByRelationWithColumnAggregateFunction { + "Average." + AVG @enum(value: "avg") + + "Minimum." + MIN @enum(value: "min") + + "Maximum." + MAX @enum(value: "max") + + "Sum." + SUM @enum(value: "sum") + + "Amount of items." + COUNT @enum(value: "count") + } + ') ); $documentAST->setTypeDefinition( static::createOrderByClauseInput( @@ -55,7 +84,7 @@ enum SortOrder { public static function createOrderByClauseInput(string $name, string $description, string $columnType): InputObjectTypeDefinitionNode { - return Parser::inputObjectTypeDefinition(/** @lang GraphQL */ <<name->value}` argument on field `{$parentField->name->value}` on type `{$parentType->name->value}`.\"\n" - ."enum $allowedColumnsEnumName {\n"; - foreach ($enumValues as $enumValue) { - $enumDefinition .= "$enumValue\n"; - } - $enumDefinition .= '}'; + $enumValuesString = implode("\n", $enumValues); - return Parser::enumTypeDefinition($enumDefinition); + return Parser::enumTypeDefinition(/** @lang GraphQL */ <<name->value}.{$parentField->name->value}.{$argDefinition->name->value}." +enum $allowedColumnsEnumName { + {$enumValuesString} +} +GRAPHQL + ); } } diff --git a/src/Validation/RulesGatherer.php b/src/Validation/RulesGatherer.php index 69ad94a4be..0a46f8d147 100644 --- a/src/Validation/RulesGatherer.php +++ b/src/Validation/RulesGatherer.php @@ -274,10 +274,10 @@ static function ($rule) use ($argumentPath) { 'Gte', 'Lt', 'Lte', - 'RequiredIf', - 'RequiredUnless', 'ProhibitedIf', 'ProhibitedUnless', + 'RequiredIf', + 'RequiredUnless', 'Same', ])) { $args[0] = implode('.', array_merge($argumentPath, [$args[0]])); @@ -285,6 +285,7 @@ static function ($rule) use ($argumentPath) { // Rules where all arguments are field references if (in_array($name, [ + 'Prohibits', 'RequiredWith', 'RequiredWithAll', 'RequiredWithout', diff --git a/tests/Integration/OrderBy/OrderByDirectiveDBTest.php b/tests/Integration/OrderBy/OrderByDirectiveDBTest.php index 0f1e295acb..5a03153acd 100644 --- a/tests/Integration/OrderBy/OrderByDirectiveDBTest.php +++ b/tests/Integration/OrderBy/OrderByDirectiveDBTest.php @@ -4,7 +4,9 @@ use Illuminate\Support\Carbon; use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Support\AppVersion; use Tests\DBTestCase; +use Tests\Utils\Models\Task; use Tests\Utils\Models\User; class OrderByDirectiveDBTest extends DBTestCase @@ -261,4 +263,182 @@ public function testOrderColumnOnField(): void ], ]); } + + public function testOrderByRelationCount(): void + { + $this->schema = /** @lang GraphQL */ ' + type Query { + users( + orderBy: _ @orderBy(relations: [ + { + relation: "tasks" + } + ]) + ): [User!]! @all + } + + type User { + id: Int! + } + '; + + /** @var \Tests\Utils\Models\User $userA */ + $userA = factory(User::class)->create(); + /** @var \Tests\Utils\Models\User $userB */ + $userB = factory(User::class)->create(); + + $userA->tasks()->saveMany( + factory(Task::class, 1)->create() + ); + $userB->tasks()->saveMany( + factory(Task::class, 2)->create() + ); + + $this->graphQL(/** @lang GraphQL */ ' + { + users( + orderBy: [ + { + tasks: { aggregate: COUNT } + order: DESC + } + ] + ) { + id + } + } + ')->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => $userB->id, + ], + [ + 'id' => $userA->id, + ], + ], + ], + ]); + + $this->graphQL(/** @lang GraphQL */ ' + { + users( + orderBy: [ + { + tasks: { aggregate: COUNT } + order: ASC + } + ] + ) { + id + } + } + ')->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => $userA->id, + ], + [ + 'id' => $userB->id, + ], + ], + ], + ]); + } + + public function testOrderByRelationAggregate(): void + { + if (AppVersion::below(8.0)) { + $this->markTestSkipped('relation aggregates are not available'); + } + + $this->schema = /** @lang GraphQL */ ' + type Query { + users( + orderBy: _ @orderBy(relations: [ + { + relation: "tasks" + columns: ["difficulty"] + } + ]) + ): [User!]! @all + } + + type User { + id: Int! + } + + enum UserColumn { + NAME @enum(value: "name") + } + '; + + /** @var \Tests\Utils\Models\User $userA */ + $userA = factory(User::class)->create(); + /** @var \Tests\Utils\Models\User $userB */ + $userB = factory(User::class)->create(); + + /** @var \Tests\Utils\Models\Task $taskA1 */ + $taskA1 = factory(Task::class)->make(); + $taskA1->difficulty = 1; + $userA->tasks()->save($taskA1); + + /** @var \Tests\Utils\Models\Task $taskB1 */ + $taskB1 = factory(Task::class)->make(); + $taskB1->difficulty = 2; + $userB->tasks()->save($taskB1); + + $this->graphQL(/** @lang GraphQL */ ' + { + users( + orderBy: [ + { + tasks: { aggregate: SUM, column: DIFFICULTY } + order: DESC + } + ] + ) { + id + } + } + ')->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => $userB->id, + ], + [ + 'id' => $userA->id, + ], + ], + ], + ]); + + $this->graphQL(/** @lang GraphQL */ ' + { + users( + orderBy: [ + { + tasks: { aggregate: SUM, column: DIFFICULTY } + order: ASC + } + ] + ) { + id + } + } + ')->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => $userA->id, + ], + [ + 'id' => $userB->id, + ], + ], + ], + ]); + } } diff --git a/tests/Integration/OrderBy/OrderByDirectiveTest.php b/tests/Integration/OrderBy/OrderByDirectiveTest.php index 221510e814..ab4c3362bf 100644 --- a/tests/Integration/OrderBy/OrderByDirectiveTest.php +++ b/tests/Integration/OrderBy/OrderByDirectiveTest.php @@ -2,7 +2,9 @@ namespace Tests\Integration\OrderBy; +use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\InputObjectType; +use Nuwave\Lighthouse\Support\AppVersion; use Tests\TestCase; class OrderByDirectiveTest extends TestCase @@ -26,4 +28,103 @@ public function testGeneratesInputWithFullyQualifiedName(): void ); $this->assertInstanceOf(InputObjectType::class, $input); } + + public function testGeneratesInputWithFullyQualifiedNameUsingRelations(): void + { + $schemaString = /** @lang GraphQL */ ' + type Query { + foo( + orderBy: _ @orderBy( + columns: ["bar"], + relations: [ + { relation: "foo" }, + { relation: "baz", columns: ["foz"] }, + ] + ) + ): ID @mock + } + '; + + $schema = $this->buildSchema($schemaString); + + $clause = $schema->getType( + 'Query' // Parent + .'Foo' // Field + .'OrderBy' // Arg + .'RelationOrderByClause' // Suffix + ); + $this->assertInstanceOf(InputObjectType::class, $clause); + + $foo = $schema->getType( + 'Query' // Parent + .'Foo' // Field + .'OrderBy' // Arg + .'Foo' // Relation + ); + $this->assertInstanceOf(InputObjectType::class, $foo); + + $baz = $schema->getType( + 'Query' // Parent + .'Foo' // Field + .'OrderBy' // Arg + .'Baz' // Relation + ); + $this->assertInstanceOf(InputObjectType::class, $baz); + + $bazEnum = $schema->getType( + 'Query' // Parent + .'Foo' // Field + .'OrderBy' // Arg + .'Baz' // Relation + .'Column' // Suffix + ); + $this->assertInstanceOf(EnumType::class, $bazEnum); + } + + public function testValidatesOnlyColumnOrOneRelationIsUsed(): void + { + if (AppVersion::below(8.0)) { + $this->markTestSkipped('prohibits rule is not available'); + } + + $this->schema = /** @lang GraphQL */ ' + type Query { + foo( + orderBy: _ @orderBy( + columns: ["bar"], + relations: [ + { relation: "foo" }, + { relation: "baz", columns: ["foz"] }, + ] + ) + ): ID @mock + } + '; + + $this + ->graphQL(/** @lang GraphQL */ ' + { + foo(orderBy: [{ + column: BAR + foo: { aggregate: COUNT } + order: ASC + }]) + } + ') + ->assertGraphQLValidationError('orderBy.0.column', 'The order by.0.column field prohibits order by.0.foo / order by.0.baz from being present.') + ->assertGraphQLValidationError('orderBy.0.foo', 'The order by.0.foo field prohibits order by.0.column / order by.0.baz from being present.'); + + $this + ->graphQL(/** @lang GraphQL */ ' + { + foo(orderBy: [{ + foo: { aggregate: COUNT } + baz: { aggregate: COUNT } + order: ASC + }]) + } + ') + ->assertGraphQLValidationError('orderBy.0.foo', 'The order by.0.foo field prohibits order by.0.column / order by.0.baz from being present.') + ->assertGraphQLValidationError('orderBy.0.baz', 'The order by.0.baz field prohibits order by.0.column / order by.0.foo from being present.'); + } } diff --git a/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php b/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php index fc96fce0b0..4451842b81 100644 --- a/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php +++ b/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php @@ -839,7 +839,7 @@ public function testOnlyAllowsWhitelistedColumns(): void [ 'kind' => 'ENUM', 'name' => $expectedEnumName, - 'description' => 'Allowed column names for the `where` argument on field `whitelistedColumns` on type `Query`.', + 'description' => 'Allowed column names for Query.whitelistedColumns.where.', 'fields' => null, 'inputFields' => null, 'interfaces' => null, From 62c53d42f021086bf7298b3ce30a0893b1a6a53c Mon Sep 17 00:00:00 2001 From: spawnia Date: Sun, 5 Dec 2021 22:15:00 +0100 Subject: [PATCH 6/9] v5.28.0 --- CHANGELOG.md | 2 + docs/5/api-reference/directives.md | 178 ++++++++++------------------- docs/5/sidebar.js | 1 + 3 files changed, 65 insertions(+), 116 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4659996249..fc13a789c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ You can find and compare releases at the [GitHub release page](https://github.co ## Unreleased +## v5.28.0 + ### Added - Allow clients to order a list of models by an aggregated value of their relations with `@orderBy` https://github.com/nuwave/lighthouse/pull/1848 diff --git a/docs/5/api-reference/directives.md b/docs/5/api-reference/directives.md index 7208c0d6b5..f0fa823e9a 100644 --- a/docs/5/api-reference/directives.md +++ b/docs/5/api-reference/directives.md @@ -1989,136 +1989,82 @@ type Query { Sort a result list by one or more given columns. """ directive @orderBy( - """ - Restrict the allowed column names to a well-defined list. - This improves introspection capabilities and security. - Mutually exclusive with the `columnsEnum` argument. - Only used when the directive is added on an argument. - """ - columns: [String!] - - """ - Use an existing enumeration type to restrict the allowed columns to a predefined list. - This allowes you to re-use the same enum for multiple fields. - Mutually exclusive with the `columns` argument. - Only used when the directive is added on an argument. - """ - columnsEnum: String - - """ - The database column for which the order by clause will be applied on. - Only used when the directive is added on a field. - """ - column: String - - """ - The direction of the order by clause. - Only used when the directive is added on a field. - """ - direction: OrderByDirection = ASC + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + Only used when the directive is added on an argument. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + Only used when the directive is added on an argument. + """ + columnsEnum: String + + """ + Allow clients to sort by aggregates on relations. + Only used when the directive is added on an argument. + """ + relations: [OrderByRelation!] + + """ + The database column for which the order by clause will be applied on. + Only used when the directive is added on a field. + """ + column: String + + """ + The direction of the order by clause. + Only used when the directive is added on a field. + """ + direction: OrderByDirection = ASC ) on ARGUMENT_DEFINITION | FIELD_DEFINITION """ Options for the `direction` argument on `@orderBy`. """ enum OrderByDirection { - """ - Sort in ascending order. - """ - ASC + """ + Sort in ascending order. + """ + ASC - """ - Sort in descending order. - """ - DESC -} -``` - -### Client Controlled Ordering - -To enable clients to control the ordering, use this directive on an argument of -a field that is backed by a database query. - -```graphql -type Query { - posts(orderBy: _ @orderBy(columns: ["posted_at", "title"])): [Post!]! @all + """ + Sort in descending order. + """ + DESC } -``` - -The type of the argument can be left blank as `_` , -as Lighthouse will automatically generate an input that takes enumerated column names, -together with the `SortOrder` enum, and add that to your schema: -```graphql -"Allows ordering a list of records." -input QueryPostsOrderByOrderByClause { - "The column that is used for ordering." - column: QueryPostsOrderByColumn! - - "The direction that is used for ordering." - order: SortOrder! -} - -"Order by clause for the `orderBy` argument on the query `posts`." -enum QueryPostsOrderByColumn { - POSTED_AT @enum(value: "posted_at") - TITLE @enum(value: "title") -} - -"The available directions for ordering a list of records." -enum SortOrder { - "Sort records in ascending order." - ASC - - "Sort records in descending order." - DESC -} -``` - -To re-use a list of allowed columns, define your own enumeration type and use the `columnsEnum` argument instead of `columns`: - -```graphql -type Query { - allPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @all - paginatedPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! - @paginate -} - -"A custom description for this custom enum." -enum PostColumn { - # Another reason why you might want to have a custom enum is to - # correct typos or bad naming in column names. - POSTED_AT @enum(value: "postd_timestamp") - TITLE @enum(value: "title") -} -``` - -Lighthouse will still automatically generate the necessary input types and the `SortOrder` enum. -Instead of generating enums for the allowed columns, it will simply use the existing `PostColumn` enum. - -Querying a field that has an `orderBy` argument looks like this: - -```graphql -{ - posts(orderBy: [{ column: POSTED_AT, order: ASC }]) { - title - } -} -``` - -You may pass more than one sorting option to add a secondary ordering. - -### Predefined Ordering +""" +Options for the `relations` argument on `@orderBy`. +""" +input OrderByRelation { + """ + TODO: description + """ + relation: String! -To predefine a default order for your field, use this directive on a field: + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + """ + columns: [String!] -```graphql -type Query { - latestUsers: [User!]! @all @orderBy(column: "created_at", direction: DESC) + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + """ + columnsEnum: String } ``` -Clients won't have to pass any arguments to the field and still receive ordered results by default. +See [ordering](../digging-deeper/ordering.md). ## @paginate diff --git a/docs/5/sidebar.js b/docs/5/sidebar.js index d1073be891..0acf52ceee 100644 --- a/docs/5/sidebar.js +++ b/docs/5/sidebar.js @@ -52,6 +52,7 @@ module.exports = [ title: "Digging Deeper", children: [ "digging-deeper/schema-organisation", + "digging-deeper/ordering", "digging-deeper/relay", "digging-deeper/error-handling", "digging-deeper/adding-types-programmatically", From 132cba58517438518b854e4953a8bf2502b688af Mon Sep 17 00:00:00 2001 From: spawnia Date: Sun, 5 Dec 2021 22:15:15 +0100 Subject: [PATCH 7/9] v5.28.0 --- docs/5/digging-deeper/ordering.md | 139 ++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 docs/5/digging-deeper/ordering.md diff --git a/docs/5/digging-deeper/ordering.md b/docs/5/digging-deeper/ordering.md new file mode 100644 index 0000000000..8c6ca1c048 --- /dev/null +++ b/docs/5/digging-deeper/ordering.md @@ -0,0 +1,139 @@ +# Ordering + +## Client Controlled Ordering + +To enable clients to control the ordering, use [@orderBy](../api-reference/directives.md#orderby) on an argument of +a field that is backed by a database query. + +```graphql +type Query { + posts(orderBy: _ @orderBy(columns: ["posted_at", "title"])): [Post!]! @all +} +``` + +The type of the argument can be left blank as `_` , +as Lighthouse will automatically generate an input that takes enumerated column names, +together with the `SortOrder` enum, and add that to your schema: + +```graphql +"Order by clause for Query.posts.orderBy." +input QueryPostsOrderByOrderByClause { + "The column that is used for ordering." + column: QueryPostsOrderByColumn! + + "The direction that is used for ordering." + order: SortOrder! +} + +"Allowed column names for Query.posts.orderBy" +enum QueryPostsOrderByColumn { + POSTED_AT @enum(value: "posted_at") + TITLE @enum(value: "title") +} + +"Directions for ordering a list of records." +enum SortOrder { + "Sort records in ascending order." + ASC + + "Sort records in descending order." + DESC +} +``` + +Querying a field that has an `orderBy` argument looks like this: + +```graphql +{ + posts(orderBy: [{ column: POSTED_AT, order: ASC }]) { + title + } +} +``` + +### Secondary Ordering + +You may pass more than one sorting option to add a secondary ordering. + +```graphql +{ + posts(orderBy: [ + { column: POSTED_AT, order: ASC } + { column: TITLE, order: DESC } + ]) { + title + } +} +``` + +### Reuse Columns Enum + +To re-use a list of allowed columns, define your own enumeration type and use the `columnsEnum` argument instead of `columns`: + +```graphql +type Query { + allPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @all + paginatedPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! + @paginate +} + +"A custom description for this custom enum." +enum PostColumn { + # Another reason why you might want to have a custom enum is to + # correct typos or bad naming in column names. + POSTED_AT @enum(value: "postd_timestamp") + TITLE @enum(value: "title") +} +``` + +Lighthouse will still automatically generate the necessary input types and the `SortOrder` enum. +Instead of generating enums for the allowed columns, it will simply use the existing `PostColumn` enum. + +### Ordering By Relations + +You can allow clients to order a list of models by an aggregated value of their relations. +You must specify which relations and which of their columns are allowed. + +```graphql +type Query { + users( + orderBy: _ @orderBy(relations: [ + { + relation: "tasks" + columns: ["difficulty"] + } + ]) + ): [User!]! @all +} +``` + +Lighthouse will automatically generate the appropriate input types and enum values. + +```graphql +{ + users(orderBy: [ + { + tasks: { aggregate: COUNT } + order: ASC + } + { + tasks: { aggregate: MAX, column: DIFFICULTY } + order: DESC + } + ]) { + id + } +} +``` + +## Predefined Ordering + +To predefine a default order for your field, use [@orderBy](../api-reference/directives.md#orderby) on a field: + +```graphql +type Query { + latestUsers: [User!]! @all @orderBy(column: "created_at", direction: DESC) +} +``` + +Clients won't have to pass any arguments to the field and still receive ordered results by default. From 7cde2ae1061bd8d5ec1510fd60e41519d55cd263 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Mon, 6 Dec 2021 09:47:06 +0100 Subject: [PATCH 8/9] Use php-cs-fixer over StyleCI (#1998) --- .gitattributes | 2 +- .github/workflows/autoformat.yml | 33 ++++- .gitignore | 1 + .php-cs-fixer.php | 12 ++ .styleci.yml | 6 - CONTRIBUTING.md | 5 +- Makefile | 8 +- README.md | 1 - _ide_helper.php | 25 ++-- benchmarks/HugeResponseBench.php | 2 +- composer.json | 1 + docs/master/api-reference/directives.md | 118 +++++++++--------- docs/master/digging-deeper/ordering.md | 39 +++--- rector.php | 8 +- src/Auth/CanDirective.php | 10 +- src/ClientDirectives/ClientDirective.php | 6 +- src/Console/DirectiveCommand.php | 14 +-- src/Console/FieldGeneratorCommand.php | 2 +- src/Console/IdeHelperCommand.php | 15 +-- src/Console/InterfaceCommand.php | 2 +- src/Console/LighthouseGeneratorCommand.php | 10 +- src/Console/PrintSchemaCommand.php | 7 +- src/Console/ScalarCommand.php | 2 +- src/Console/SubscriptionCommand.php | 2 +- src/Console/UnionCommand.php | 2 +- src/Console/ValidateSchemaCommand.php | 4 +- src/Console/ValidatorCommand.php | 2 +- src/Defer/Defer.php | 17 ++- src/Defer/DeferServiceProvider.php | 2 +- src/Defer/DeferrableDirective.php | 6 +- src/Events/BuildExtensionsResponse.php | 1 - src/Events/RegisterDirectiveNamespaces.php | 1 - src/Exceptions/FederationException.php | 1 - src/Exceptions/InvalidDriverException.php | 1 - src/Exceptions/ParseException.php | 2 +- src/Exceptions/ValidationException.php | 2 +- src/Execution/Arguments/ArgPartitioner.php | 6 +- src/Execution/Arguments/Argument.php | 3 +- src/Execution/Arguments/ArgumentSet.php | 9 +- .../Arguments/ArgumentSetFactory.php | 13 +- .../Arguments/ArgumentTypeNodeConverter.php | 2 + src/Execution/Arguments/UpdateModel.php | 4 +- src/Execution/Arguments/UpsertModel.php | 4 +- src/Execution/AuthenticationErrorHandler.php | 2 +- src/Execution/AuthorizationErrorHandler.php | 2 +- .../BatchLoader/BatchLoaderRegistry.php | 3 +- src/Execution/DataLoader/BatchLoader.php | 5 +- src/Execution/ErrorPool.php | 2 +- src/Execution/ExtensionErrorHandler.php | 2 +- src/Execution/ExtensionsResponse.php | 4 +- .../ModelsLoader/PaginatedModelsLoader.php | 2 +- .../ModelsLoader/SimpleModelsLoader.php | 2 +- src/Execution/ReportingErrorHandler.php | 4 +- src/Execution/Resolved.php | 1 + src/Execution/Utils/Subscription.php | 2 +- src/Execution/ValidationErrorHandler.php | 2 +- src/Federation/ASTManipulator.php | 8 +- .../Directives/ExtendsDirective.php | 2 +- .../Directives/ExternalDirective.php | 2 +- src/Federation/Directives/KeyDirective.php | 2 +- .../Directives/ProvidesDirective.php | 2 +- .../Directives/RequiresDirective.php | 2 +- src/Federation/EntityResolverProvider.php | 20 +-- src/Federation/FederationPrinter.php | 18 +-- src/Federation/FederationServiceProvider.php | 2 +- src/Federation/Resolvers/Entities.php | 3 +- src/Federation/Resolvers/Service.php | 1 + src/Federation/SchemaPrinter.php | 20 +-- src/Federation/SchemaValidator.php | 4 +- src/Federation/Types/Any.php | 6 +- src/GlobalId/GlobalId.php | 4 +- src/GlobalId/GlobalIdDirective.php | 1 + src/GlobalId/GlobalIdServiceProvider.php | 6 +- src/GlobalId/NodeDirective.php | 4 +- src/GlobalId/NodeRegistry.php | 3 +- src/GraphQL.php | 13 +- src/LighthouseServiceProvider.php | 15 ++- src/OrderBy/OrderByDirective.php | 18 +-- src/Pagination/ConnectionField.php | 4 +- src/Pagination/PaginationArgs.php | 2 +- src/Pagination/PaginationManipulator.php | 29 ++--- src/Pagination/PaginationType.php | 6 +- src/Pagination/PaginatorField.php | 2 + src/Pagination/SimplePaginatorField.php | 2 + src/Schema/AST/ASTBuilder.php | 4 +- src/Schema/AST/ASTCache.php | 6 +- src/Schema/AST/ASTHelper.php | 34 ++--- src/Schema/AST/DocumentAST.php | 13 +- src/Schema/AST/TypeNodeConverter.php | 22 ++-- src/Schema/DirectiveLocator.php | 30 ++--- .../Directives/ArgTraversalDirective.php | 6 +- src/Schema/Directives/BaseDirective.php | 11 +- src/Schema/Directives/CacheDirective.php | 9 +- src/Schema/Directives/ComplexityDirective.php | 4 +- src/Schema/Directives/LazyLoadDirective.php | 3 +- src/Schema/Directives/LikeDirective.php | 12 +- src/Schema/Directives/LimitDirective.php | 16 +-- src/Schema/Directives/MethodDirective.php | 3 +- src/Schema/Directives/ModelDirective.php | 4 +- .../ModifyModelExistenceDirective.php | 12 +- .../Directives/MutationExecutorDirective.php | 4 +- src/Schema/Directives/NamespaceDirective.php | 4 +- src/Schema/Directives/NestDirective.php | 4 +- src/Schema/Directives/RelationDirective.php | 10 +- .../Directives/RelationDirectiveHelpers.php | 5 +- src/Schema/Directives/ScopeDirective.php | 2 +- src/Schema/Directives/ThrottleDirective.php | 10 +- src/Schema/Directives/TrimDirective.php | 1 + src/Schema/Factories/ArgumentFactory.php | 1 + src/Schema/Factories/DirectiveFactory.php | 2 +- src/Schema/Factories/FieldFactory.php | 13 +- src/Schema/ResolverProvider.php | 5 +- src/Schema/SchemaBuilder.php | 2 +- src/Schema/Source/SchemaStitcher.php | 4 +- src/Schema/TypeRegistry.php | 42 +++---- src/Schema/Types/GraphQLSubscription.php | 11 +- src/Schema/Types/Scalars/DateScalar.php | 6 +- src/Schema/Types/Scalars/Upload.php | 2 +- src/Schema/Values/CacheValue.php | 22 ++-- src/Schema/Values/FieldValue.php | 2 +- src/Scout/ScoutEnhancer.php | 10 +- src/Scout/SearchDirective.php | 2 +- src/SoftDeletes/SoftDeletesDirective.php | 2 +- src/SoftDeletes/TrashedDirective.php | 10 +- src/Subscriptions/Authorizer.php | 2 +- src/Subscriptions/BroadcastManager.php | 2 +- .../BroadcastSubscriptionJob.php | 5 +- .../Broadcasters/EchoBroadcaster.php | 2 +- .../Broadcasters/PusherBroadcaster.php | 2 +- src/Subscriptions/Contracts/Broadcaster.php | 1 + .../Contracts/SubscriptionIterator.php | 7 +- .../Events/EchoSubscriptionEvent.php | 4 +- .../Exceptions/UnauthorizedSubscriber.php | 1 - .../Iterators/AuthenticatingSyncIterator.php | 4 +- src/Subscriptions/Iterators/SyncIterator.php | 2 +- .../Storage/CacheStorageManager.php | 14 +-- .../Storage/RedisStorageManager.php | 24 ++-- src/Subscriptions/Subscriber.php | 4 +- src/Subscriptions/SubscriptionRegistry.php | 10 +- .../SubscriptionResolverProvider.php | 6 +- src/Subscriptions/SubscriptionRouter.php | 6 +- .../SubscriptionServiceProvider.php | 10 +- src/Support/Contracts/ArgBuilderDirective.php | 7 +- src/Support/Contracts/ArgDirective.php | 1 - .../Contracts/ArgDirectiveForArray.php | 1 - src/Support/Contracts/ArgResolver.php | 5 +- .../Contracts/ArgSanitizerDirective.php | 3 +- .../Contracts/ArgTransformerDirective.php | 5 +- src/Support/Contracts/CanStreamResponse.php | 1 + src/Support/Contracts/CreatesResponse.php | 1 + .../Contracts/FieldBuilderDirective.php | 5 +- src/Support/Contracts/FieldMiddleware.php | 1 + src/Support/Contracts/TypeManipulator.php | 1 + src/Support/DriverManager.php | 21 ++-- src/Support/Http/Middleware/AcceptJson.php | 4 +- .../Http/Middleware/AttemptAuthentication.php | 1 + .../Http/Middleware/LogGraphQLQueries.php | 2 +- src/Support/Http/Responses/ResponseStream.php | 10 +- src/Support/Http/Responses/Stream.php | 1 + src/Support/Traits/GeneratesColumnsEnum.php | 8 +- src/Support/Utils.php | 20 +-- src/Testing/MakesGraphQLRequests.php | 14 ++- src/Testing/MakesGraphQLRequestsLumen.php | 6 +- src/Testing/MockResolver.php | 2 +- src/Testing/RethrowingErrorHandler.php | 2 +- src/Testing/TestResponseMixin.php | 2 +- src/Testing/TestResponseUtils.php | 1 + src/Tracing/Tracing.php | 2 +- src/Tracing/TracingServiceProvider.php | 8 +- src/Validation/BaseRulesDirective.php | 6 +- src/Validation/RulesGatherer.php | 6 +- src/Validation/Validator.php | 7 +- src/Validation/ValidatorDirective.php | 12 +- src/WhereConditions/Operator.php | 1 + src/WhereConditions/SQLOperator.php | 2 +- .../WhereConditionsBaseDirective.php | 8 +- .../WhereConditionsServiceProvider.php | 12 +- .../WhereHasConditionsDirective.php | 2 +- src/lighthouse.php | 8 +- tests/Console/CacheCommandTest.php | 6 +- tests/Console/IdeHelperCommandTest.php | 2 +- .../PrintFederationSchemaCommandTest.php | 12 +- tests/DBTestCase.php | 12 +- tests/Integration/Defer/DeferDBTest.php | 6 +- .../Defer/DeferIncludeSkipTest.php | 2 +- tests/Integration/Defer/DeferTest.php | 2 +- tests/Integration/ErrorTest.php | 2 +- .../Execution/ArgBuilderDirectiveTest.php | 12 +- .../DataLoader/RelationBatchLoaderTest.php | 12 +- .../RelationCountBatchLoaderTest.php | 4 +- .../MutationExecutor/BelongsToManyTest.php | 2 +- .../MutationExecutor/BelongsToTest.php | 10 +- .../MutationExecutor/HasManyTest.php | 4 +- .../Execution/MutationExecutor/HasOneTest.php | 20 +-- .../MutationExecutor/MorphManyTest.php | 2 +- .../MutationExecutor/MorphOneTest.php | 2 +- .../MutationExecutor/MorphToManyTest.php | 2 +- .../MutationExecutor/MorphToTest.php | 2 +- .../Federation/FederationEntitiesTest.php | 6 +- .../Federation/FederationSchemaTest.php | 2 +- tests/Integration/FileUploadTest.php | 4 +- tests/Integration/GlobalErrorRendererTest.php | 4 +- .../GlobalId/NodeDirectiveDBTest.php | 2 +- tests/Integration/GraphQLTest.php | 2 +- tests/Integration/LifecycleEventsTest.php | 2 +- .../OrderBy/OrderByDirectiveTest.php | 32 ++--- .../Pagination/PaginateDirectiveDBTest.php | 2 +- tests/Integration/RouteRegistrationTest.php | 1 + .../Directives/AggregateDirectiveTest.php | 2 +- .../Schema/Directives/AllDirectiveTest.php | 12 +- .../Directives/BuilderDirectiveTest.php | 7 +- .../Schema/Directives/CacheDirectiveTest.php | 8 +- .../Directives/CountDirectiveDBTest.php | 2 +- .../Schema/Directives/EqDirectiveTest.php | 6 +- .../Schema/Directives/EventDirectiveTest.php | 4 +- .../Directives/HasManyDirectiveTest.php | 4 +- .../Schema/Directives/HasOneDirectiveTest.php | 2 +- .../Directives/MorphManyDirectiveTest.php | 8 +- .../Directives/MorphToManyDirectiveTest.php | 2 +- .../Directives/ThrottleDirectiveTest.php | 2 +- .../Directives/WithCountDirectiveTest.php | 2 +- .../Schema/Directives/WithDirectiveTest.php | 6 +- .../Integration/Scout/SearchDirectiveTest.php | 2 +- .../SoftDeletesAndTrashedDirectiveTest.php | 18 +-- .../EchoBroadcaster/AuthorizeRequestsTest.php | 8 +- .../Subscriptions/SerializerTest.php | 2 +- .../Storage/RedisStorageManagerTest.php | 10 +- .../Subscriptions/SubscriptionTest.php | 1 + .../Integration/Auth/CanDirectiveDBTest.php | 4 +- .../Validation/RulesDirectiveTest.php | 2 +- .../WhereConditionsDirectiveTest.php | 12 +- tests/Laravel7ExceptionHandler.php | 1 - tests/PreLaravel7ExceptionHandler.php | 1 - tests/SerializingArrayStore.php | 3 +- tests/TestCase.php | 8 +- tests/TestsRedis.php | 2 +- tests/TestsSchemaCache.php | 2 +- tests/TestsSerialization.php | 6 +- tests/Unit/Events/BuildSchemaStringTest.php | 6 +- .../Arguments/ArgumentSetFactoryTest.php | 4 +- tests/Unit/Federation/SchemaValidatorTest.php | 2 +- tests/Unit/GlobalId/GlobalIdDirectiveTest.php | 2 +- tests/Unit/GlobalId/GlobalIdTest.php | 2 +- .../Unit/Pagination/PaginateDirectiveTest.php | 2 +- tests/Unit/Schema/AST/ASTBuilderTest.php | 4 +- tests/Unit/Schema/AST/ASTHelperTest.php | 2 +- tests/Unit/Schema/DirectiveLocatorTest.php | 3 +- .../Schema/Directives/BaseDirectiveTest.php | 6 +- .../Directives/ComplexityDirectiveTest.php | 2 +- .../Directives/DeprecatedDirectiveTest.php | 4 +- .../Directives/ThrottleDirectiveTest.php | 4 +- .../Schema/Execution/ContextFactoryTest.php | 3 +- .../Schema/Execution/Fixtures/FooContext.php | 2 +- tests/Unit/Schema/ResolverProviderTest.php | 2 +- .../Unit/Schema/Source/SchemaStitcherTest.php | 76 +++++++---- .../Unit/Schema/Types/Scalars/UploadTest.php | 8 +- .../Subscriptions/BroadcastManagerTest.php | 7 +- .../Broadcasters/EchoBroadcasterTest.php | 8 +- .../Subscriptions/Iterators/IteratorTest.php | 2 +- .../Iterators/SyncIteratorTest.php | 2 +- .../Storage/RedisStorageManagerTest.php | 9 +- tests/Unit/Subscriptions/SubscriptionTest.php | 3 +- .../Middleware/AttemptAuthenticationTest.php | 2 +- .../Unit/Testing/MakesGraphQLRequestsTest.php | 3 +- .../Unit/Tests/Unit/Auth/CanDirectiveTest.php | 16 +-- .../CustomFieldMiddlewareDirective.php | 1 + tests/Utils/Entities/Foo.php | 1 + tests/Utils/InterfacesSecondary/Bar.php | 1 - .../Utils/LaravelEnums/LocalizedUserType.php | 2 +- tests/Utils/Models/Closure.php | 1 - tests/Utils/ModelsSecondary/Category.php | 1 - tests/Utils/ModelsSecondary/OnlyHere.php | 1 - tests/Utils/Policies/TaskPolicy.php | 4 +- tests/Utils/Policies/UserPolicy.php | 6 +- tests/Utils/Scalars/Email.php | 4 +- tests/Utils/Unions/CustomStuff.php | 2 +- .../EmailCustomAttributeValidator.php | 2 +- .../EmailCustomMessageValidator.php | 2 +- .../Utils/Validators/FooClosureValidator.php | 4 +- tests/database/factories/RoleFactory.php | 2 +- 280 files changed, 1006 insertions(+), 853 deletions(-) create mode 100644 .php-cs-fixer.php delete mode 100644 .styleci.yml diff --git a/.gitattributes b/.gitattributes index 433b9b2d5d..19dc6d70c7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,7 +8,7 @@ /.editorconfig export-ignore /.gitattributes export-ignore /.gitignore export-ignore -/.styleci.yml export-ignore +/.php-cs-fixer.php /CHANGELOG.md export-ignore /CONTRIBUTING.md export-ignore /docker-compose.yml export-ignore diff --git a/.github/workflows/autoformat.yml b/.github/workflows/autoformat.yml index 39582357fe..444ba4ea2b 100644 --- a/.github/workflows/autoformat.yml +++ b/.github/workflows/autoformat.yml @@ -10,7 +10,15 @@ jobs: with: ref: ${{ github.head_ref }} - - uses: docker://ergebnis/composer-normalize-action:0.8.0 + - uses: shivammathur/setup-php@v2 + with: + coverage: none + extensions: mbstring + php-version: 7.4 + + - run: composer install --no-interaction --no-progress --no-suggest + + - run: composer normalize - uses: stefanzweifel/git-auto-commit-action@v4 with: @@ -30,3 +38,26 @@ jobs: commit_message: Prettify docs env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + php-cs-fixer: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + ref: ${{ github.head_ref }} + + - uses: shivammathur/setup-php@v2 + with: + coverage: none + extensions: mbstring + php-version: 7.4 + + - run: composer install --no-interaction --no-progress --no-suggest + + - run: vendor/bin/php-cs-fixer fix + + - run: git pull + + - uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: Apply php-cs-fixer changes diff --git a/.gitignore b/.gitignore index 83f1a988ac..554da11c9f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ phpunit.xml # Generated files .phpunit.result.cache +.php-cs-fixer.cache build # composer diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000000..213c898872 --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,12 @@ +notPath('vendor') + ->in(__DIR__) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return config($finder); diff --git a/.styleci.yml b/.styleci.yml deleted file mode 100644 index dc9b334e69..0000000000 --- a/.styleci.yml +++ /dev/null @@ -1,6 +0,0 @@ -preset: laravel -enabled: - - no_superfluous_phpdoc_tags -finder: - not-name: - - "_ide_helper.php" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3707b433dc..28a5447866 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -235,8 +235,9 @@ function bar(){ ## Code style -We use [StyleCI](https://styleci.io/) to ensure clean formatting, oriented -at the Laravel coding style. +We format the code automatically with [php-cs-fixer](https://github.com/friendsofphp/php-cs-fixer) + + make fix Prefer explicit naming and short, focused functions over excessive comments. diff --git a/Makefile b/Makefile index bf24f5808a..50065ea88a 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,9 @@ .PHONY: it -it: vendor stan test ## Run useful checks before commits +it: vendor fix stan test ## Run useful checks before commits .PHONY: help help: ## Displays this list of targets with descriptions - @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m%-30s\033[0m %s\n", $$1, $$2}' + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m%-30s\033[0m %s\n", $$1, $$2}' .PHONY: setup setup: build vendor ## Setup the local environment @@ -16,6 +16,10 @@ build: ## Build the local Docker containers up: ## Bring up the docker-compose stack docker-compose up -d +.PHONY: fix +fix: up + docker-compose exec php vendor/bin/php-cs-fixer fix + .PHONY: stan stan: up ## Runs static analysis docker-compose exec php vendor/bin/phpstan diff --git a/README.md b/README.md index bfe5f440fd..cefa5f5bc2 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ [![Continuous Integration](https://github.com/nuwave/lighthouse/workflows/Continuous%20Integration/badge.svg)](https://github.com/nuwave/lighthouse/actions) [![Code Coverage](https://codecov.io/gh/nuwave/lighthouse/branch/master/graph/badge.svg)](https://codecov.io/gh/nuwave/lighthouse) [![PHPStan](https://img.shields.io/badge/PHPStan-enabled-brightgreen.svg?style=flat)](https://github.com/phpstan/phpstan) -[![StyleCI](https://github.styleci.io/repos/59965104/shield?branch=master&style=flat)](https://github.styleci.io/repos/59965104) [![Packagist](https://img.shields.io/packagist/dt/nuwave/lighthouse.svg)](https://packagist.org/packages/nuwave/lighthouse) [![Latest Stable Version](https://poser.pugx.org/nuwave/lighthouse/v/stable)](https://packagist.org/packages/nuwave/lighthouse) diff --git a/_ide_helper.php b/_ide_helper.php index 3c2b6bfc79..c18a6c9df7 100644 --- a/_ide_helper.php +++ b/_ide_helper.php @@ -6,7 +6,8 @@ class TestResponse /** * Asserts that the response contains an error from a given category. * - * @param string $category The name of the expected error category. + * @param string $category the name of the expected error category + * * @return $this */ public function assertGraphQLErrorCategory(string $category): self @@ -17,7 +18,8 @@ public function assertGraphQLErrorCategory(string $category): self /** * Assert that the returned result contains exactly the given validation keys. * - * @param array $keys The validation keys the result should have. + * @param array $keys the validation keys the result should have + * * @return $this */ public function assertGraphQLValidationKeys(array $keys): self @@ -28,8 +30,9 @@ public function assertGraphQLValidationKeys(array $keys): self /** * Assert that a given validation error is present in the response. * - * @param string $key The validation key that should be present. - * @param string $message The expected validation message. + * @param string $key the validation key that should be present + * @param string $message the expected validation message + * * @return $this */ public function assertGraphQLValidationError(string $key, string $message): self @@ -55,7 +58,8 @@ class TestResponse /** * Assert the response contains an error with the given message. * - * @param string $message The expected error message. + * @param string $message the expected error message + * * @return $this */ public function assertGraphQLErrorMessage(string $message): self @@ -66,7 +70,8 @@ public function assertGraphQLErrorMessage(string $message): self /** * Assert the response contains an error from the given category. * - * @param string $category The name of the expected error category. + * @param string $category the name of the expected error category + * * @return $this */ public function assertGraphQLErrorCategory(string $category): self @@ -77,7 +82,8 @@ public function assertGraphQLErrorCategory(string $category): self /** * Assert the returned result contains exactly the given validation keys. * - * @param array $keys The validation keys the result should have. + * @param array $keys the validation keys the result should have + * * @return $this */ public function assertGraphQLValidationKeys(array $keys): self @@ -88,8 +94,9 @@ public function assertGraphQLValidationKeys(array $keys): self /** * Assert a given validation error is present in the response. * - * @param string $key The validation key that should be present. - * @param string $message The expected validation message. + * @param string $key the validation key that should be present + * @param string $message the expected validation message + * * @return $this */ public function assertGraphQLValidationError(string $key, string $message): self diff --git a/benchmarks/HugeResponseBench.php b/benchmarks/HugeResponseBench.php index 069cdb60eb..1850c4dece 100644 --- a/benchmarks/HugeResponseBench.php +++ b/benchmarks/HugeResponseBench.php @@ -38,7 +38,7 @@ public function resolve(): array 'children' => [], ]; - for ($i = 0; $i < 100; $i++) { + for ($i = 0; $i < 100; ++$i) { $parent['children'][] = [ 'name' => "child {$i}", 'parent' => $parent, diff --git a/composer.json b/composer.json index 6024f2fb30..150c3ca0e5 100644 --- a/composer.json +++ b/composer.json @@ -50,6 +50,7 @@ "laravel/lumen-framework": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", "laravel/scout": "^7 || ^8", "mll-lab/graphql-php-scalars": "^4", + "mll-lab/php-cs-fixer-config": "^4.4.1", "mockery/mockery": "^1", "nunomaduro/larastan": "^0.6 || ^0.7 || ^1", "orchestra/testbench": "3.6.* || 3.7.* || 3.8.* || 3.9.* || ^4 || ^5 || ^6", diff --git a/docs/master/api-reference/directives.md b/docs/master/api-reference/directives.md index f0fa823e9a..ff0274f669 100644 --- a/docs/master/api-reference/directives.md +++ b/docs/master/api-reference/directives.md @@ -1989,78 +1989,78 @@ type Query { Sort a result list by one or more given columns. """ directive @orderBy( - """ - Restrict the allowed column names to a well-defined list. - This improves introspection capabilities and security. - Mutually exclusive with the `columnsEnum` argument. - Only used when the directive is added on an argument. - """ - columns: [String!] - - """ - Use an existing enumeration type to restrict the allowed columns to a predefined list. - This allowes you to re-use the same enum for multiple fields. - Mutually exclusive with the `columns` argument. - Only used when the directive is added on an argument. - """ - columnsEnum: String - - """ - Allow clients to sort by aggregates on relations. - Only used when the directive is added on an argument. - """ - relations: [OrderByRelation!] - - """ - The database column for which the order by clause will be applied on. - Only used when the directive is added on a field. - """ - column: String - - """ - The direction of the order by clause. - Only used when the directive is added on a field. - """ - direction: OrderByDirection = ASC + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + Only used when the directive is added on an argument. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + Only used when the directive is added on an argument. + """ + columnsEnum: String + + """ + Allow clients to sort by aggregates on relations. + Only used when the directive is added on an argument. + """ + relations: [OrderByRelation!] + + """ + The database column for which the order by clause will be applied on. + Only used when the directive is added on a field. + """ + column: String + + """ + The direction of the order by clause. + Only used when the directive is added on a field. + """ + direction: OrderByDirection = ASC ) on ARGUMENT_DEFINITION | FIELD_DEFINITION """ Options for the `direction` argument on `@orderBy`. """ enum OrderByDirection { - """ - Sort in ascending order. - """ - ASC + """ + Sort in ascending order. + """ + ASC - """ - Sort in descending order. - """ - DESC + """ + Sort in descending order. + """ + DESC } """ Options for the `relations` argument on `@orderBy`. """ input OrderByRelation { - """ - TODO: description - """ - relation: String! - - """ - Restrict the allowed column names to a well-defined list. - This improves introspection capabilities and security. - Mutually exclusive with the `columnsEnum` argument. - """ - columns: [String!] - - """ - Use an existing enumeration type to restrict the allowed columns to a predefined list. - This allowes you to re-use the same enum for multiple fields. - Mutually exclusive with the `columns` argument. - """ - columnsEnum: String + """ + TODO: description + """ + relation: String! + + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with the `columnsEnum` argument. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allowes you to re-use the same enum for multiple fields. + Mutually exclusive with the `columns` argument. + """ + columnsEnum: String } ``` diff --git a/docs/master/digging-deeper/ordering.md b/docs/master/digging-deeper/ordering.md index 8c6ca1c048..175141ef5a 100644 --- a/docs/master/digging-deeper/ordering.md +++ b/docs/master/digging-deeper/ordering.md @@ -57,10 +57,9 @@ You may pass more than one sorting option to add a secondary ordering. ```graphql { - posts(orderBy: [ - { column: POSTED_AT, order: ASC } - { column: TITLE, order: DESC } - ]) { + posts( + orderBy: [{ column: POSTED_AT, order: ASC }, { column: TITLE, order: DESC }] + ) { title } } @@ -96,14 +95,10 @@ You must specify which relations and which of their columns are allowed. ```graphql type Query { - users( - orderBy: _ @orderBy(relations: [ - { - relation: "tasks" - columns: ["difficulty"] - } - ]) - ): [User!]! @all + users( + orderBy: _ + @orderBy(relations: [{ relation: "tasks", columns: ["difficulty"] }]) + ): [User!]! @all } ``` @@ -111,18 +106,14 @@ Lighthouse will automatically generate the appropriate input types and enum valu ```graphql { - users(orderBy: [ - { - tasks: { aggregate: COUNT } - order: ASC - } - { - tasks: { aggregate: MAX, column: DIFFICULTY } - order: DESC - } - ]) { - id - } + users( + orderBy: [ + { tasks: { aggregate: COUNT }, order: ASC } + { tasks: { aggregate: MAX, column: DIFFICULTY }, order: DESC } + ] + ) { + id + } } ``` diff --git a/rector.php b/rector.php index 92ef03b5de..4a0419d735 100644 --- a/rector.php +++ b/rector.php @@ -19,14 +19,14 @@ $parameters = $containerConfigurator->parameters(); $parameters->set(Option::SKIP, [ // Does not fit autoloading standards - __DIR__.'/tests/database/migrations', + __DIR__ . '/tests/database/migrations', // References PreLaravel7ExceptionHandler which is not compatible with newer Laravel - __DIR__.'/tests/TestCase.php', - __DIR__.'/tests/PreLaravel7ExceptionHandler.php', + __DIR__ . '/tests/TestCase.php', + __DIR__ . '/tests/PreLaravel7ExceptionHandler.php', // Gets stuck on WhereConditionsBaseDirective for some reason - __DIR__.'/src/WhereConditions', + __DIR__ . '/src/WhereConditions', // It is shorter and more efficient CallableThisArrayToAnonymousFunctionRector::class, diff --git a/src/Auth/CanDirective.php b/src/Auth/CanDirective.php index ead1007ea6..c30aa351fd 100644 --- a/src/Auth/CanDirective.php +++ b/src/Auth/CanDirective.php @@ -129,9 +129,10 @@ function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) /** * @param array $args - * @return iterable<\Illuminate\Database\Eloquent\Model|class-string<\Illuminate\Database\Eloquent\Model>> * * @throws \GraphQL\Error\Error + * + * @return iterable<\Illuminate\Database\Eloquent\Model|class-string<\Illuminate\Database\Eloquent\Model>> */ protected function modelsToCheck(ArgumentSet $argumentSet, array $args): iterable { @@ -146,7 +147,7 @@ protected function modelsToCheck(ArgumentSet $argumentSet, array $args): iterabl if ($find = $this->directiveArgValue('find')) { $findValue = Arr::get($args, $find); - if ($findValue === null) { + if (null === $findValue) { throw new Error(self::missingKeyToFindModel($find)); } @@ -239,6 +240,7 @@ function ($ability) use ($gate, $arguments) { * Additional arguments that are passed to @see Gate::check(). * * @param array $args + * * @return array */ protected function buildCheckArguments(array $args): array @@ -247,11 +249,11 @@ protected function buildCheckArguments(array $args): array // The injected args come before the static args if ($this->directiveArgValue('injectArgs')) { - $checkArguments [] = $args; + $checkArguments[] = $args; } if ($this->directiveHasArgument('args')) { - $checkArguments [] = $this->directiveArgValue('args'); + $checkArguments[] = $this->directiveArgValue('args'); } return $checkArguments; diff --git a/src/ClientDirectives/ClientDirective.php b/src/ClientDirectives/ClientDirective.php index 618ba97541..ab037e5a2d 100644 --- a/src/ClientDirectives/ClientDirective.php +++ b/src/ClientDirectives/ClientDirective.php @@ -50,7 +50,7 @@ public function forField(ResolveInfo $resolveInfo): array $arguments = []; foreach ($resolveInfo->fieldNodes as $fieldNode) { - $arguments [] = Values::getDirectiveValues($directive, $fieldNode, $resolveInfo->variableValues); + $arguments[] = Values::getDirectiveValues($directive, $fieldNode, $resolveInfo->variableValues); } return $arguments; @@ -61,7 +61,7 @@ public function forField(ResolveInfo $resolveInfo): array */ protected function definition(): Directive { - if ($this->definition !== null) { + if (null !== $this->definition) { return $this->definition; } @@ -70,7 +70,7 @@ protected function definition(): Directive $schema = $schemaBuilder->schema(); $definition = $schema->getDirective($this->name); - if ($definition === null) { + if (null === $definition) { throw new DefinitionException("Missing a schema definition for the client directive $this->name"); } diff --git a/src/Console/DirectiveCommand.php b/src/Console/DirectiveCommand.php index 29bc708bba..891bbeaac2 100644 --- a/src/Console/DirectiveCommand.php +++ b/src/Console/DirectiveCommand.php @@ -23,7 +23,7 @@ class DirectiveCommand extends LighthouseGeneratorCommand { /** @var array */ - const ARGUMENT_INTERFACES = [ + public const ARGUMENT_INTERFACES = [ ArgTransformerDirective::class, ArgBuilderDirective::class, ArgResolver::class, @@ -31,14 +31,14 @@ class DirectiveCommand extends LighthouseGeneratorCommand ]; /** @var array */ - const FIELD_INTERFACES = [ + public const FIELD_INTERFACES = [ FieldResolver::class, FieldMiddleware::class, FieldManipulator::class, ]; /** @var array */ - const TYPE_INTERFACES = [ + public const TYPE_INTERFACES = [ TypeManipulator::class, TypeMiddleware::class, TypeResolver::class, @@ -86,7 +86,7 @@ class DirectiveCommand extends LighthouseGeneratorCommand protected function getNameInput(): string { - return parent::getNameInput().'Directive'; + return parent::getNameInput() . 'Directive'; } protected function namespaceConfigKey(): string @@ -257,20 +257,20 @@ private function addLocation(string $location): void protected function getStub(): string { - return __DIR__.'/stubs/directive.stub'; + return __DIR__ . '/stubs/directive.stub'; } protected function interfaceMethods(string $interface): ?string { return $this->getFileIfExists( - __DIR__.'/stubs/directives/'.Str::snake($interface).'_methods.stub' + __DIR__ . '/stubs/directives/' . Str::snake($interface) . '_methods.stub' ); } protected function interfaceImports(string $interface): ?string { return $this->getFileIfExists( - __DIR__.'/stubs/directives/'.Str::snake($interface).'_imports.stub' + __DIR__ . '/stubs/directives/' . Str::snake($interface) . '_imports.stub' ); } diff --git a/src/Console/FieldGeneratorCommand.php b/src/Console/FieldGeneratorCommand.php index 8c61b8bb9f..f111231693 100644 --- a/src/Console/FieldGeneratorCommand.php +++ b/src/Console/FieldGeneratorCommand.php @@ -12,7 +12,7 @@ protected function getStub(): string ? 'field_full' : 'field_simple'; - return __DIR__."/stubs/{$stub}.stub"; + return __DIR__ . "/stubs/{$stub}.stub"; } /** diff --git a/src/Console/IdeHelperCommand.php b/src/Console/IdeHelperCommand.php index 5efa21c8ef..9c95fcba97 100644 --- a/src/Console/IdeHelperCommand.php +++ b/src/Console/IdeHelperCommand.php @@ -69,7 +69,7 @@ protected function schemaDirectiveDefinitions(DirectiveLocator $directiveLocator } $filePath = static::schemaDirectivesPath(); - \Safe\file_put_contents($filePath, self::GENERATED_NOTICE.$schema); + \Safe\file_put_contents($filePath, self::GENERATED_NOTICE . $schema); $this->info("Wrote schema directive definitions to $filePath."); } @@ -78,6 +78,7 @@ protected function schemaDirectiveDefinitions(DirectiveLocator $directiveLocator * Scan the given namespaces for directive classes. * * @param array $directiveNamespaces + * * @return array> */ protected function scanForDirectives(array $directiveNamespaces): array @@ -128,7 +129,7 @@ protected function define(string $directiveClass): string public static function schemaDirectivesPath(): string { - return base_path().'/schema-directives.graphql'; + return base_path() . '/schema-directives.graphql'; } protected function programmaticTypes(TypeRegistry $typeRegistry): void @@ -152,20 +153,20 @@ protected function programmaticTypes(TypeRegistry $typeRegistry): void }) ->implode("\n"); - \Safe\file_put_contents($filePath, self::GENERATED_NOTICE.$schema); + \Safe\file_put_contents($filePath, self::GENERATED_NOTICE . $schema); $this->info("Wrote definitions for programmatically registered types to $filePath."); } public static function programmaticTypesPath(): string { - return base_path().'/programmatic-types.graphql'; + return base_path() . '/programmatic-types.graphql'; } protected function phpIdeHelper(): void { $filePath = static::phpIdeHelperPath(); - $contents = \Safe\file_get_contents(__DIR__.'/../../_ide_helper.php'); + $contents = \Safe\file_get_contents(__DIR__ . '/../../_ide_helper.php'); \Safe\file_put_contents($filePath, $this->withGeneratedNotice($contents)); @@ -174,14 +175,14 @@ protected function phpIdeHelper(): void public static function phpIdeHelperPath(): string { - return base_path().'/_lighthouse_ide_helper.php'; + return base_path() . '/_lighthouse_ide_helper.php'; } protected function withGeneratedNotice(string $phpContents): string { return substr_replace( $phpContents, - self::OPENING_PHP_TAG.self::GENERATED_NOTICE, + self::OPENING_PHP_TAG . self::GENERATED_NOTICE, 0, strlen(self::OPENING_PHP_TAG) ); diff --git a/src/Console/InterfaceCommand.php b/src/Console/InterfaceCommand.php index 7969c23fc2..1b4952e2cb 100644 --- a/src/Console/InterfaceCommand.php +++ b/src/Console/InterfaceCommand.php @@ -17,6 +17,6 @@ protected function namespaceConfigKey(): string protected function getStub(): string { - return __DIR__.'/stubs/typeResolver.stub'; + return __DIR__ . '/stubs/typeResolver.stub'; } } diff --git a/src/Console/LighthouseGeneratorCommand.php b/src/Console/LighthouseGeneratorCommand.php index d5a3663b35..27ca267d29 100644 --- a/src/Console/LighthouseGeneratorCommand.php +++ b/src/Console/LighthouseGeneratorCommand.php @@ -29,7 +29,7 @@ protected function getNameInput(): string */ protected function getDefaultNamespace($rootNamespace): string { - $namespaces = config('lighthouse.namespaces.'.$this->namespaceConfigKey()); + $namespaces = config('lighthouse.namespaces.' . $this->namespaceConfigKey()); return static::commonNamespace((array) $namespaces); } @@ -48,13 +48,13 @@ abstract protected function namespaceConfigKey(): string; */ public static function commonNamespace(array $namespaces): string { - if ($namespaces === []) { + if ([] === $namespaces) { throw new InvalidArgumentException( 'A default namespace is required for code generation.' ); } - if (count($namespaces) === 1) { + if (1 === count($namespaces)) { return reset($namespaces); } @@ -81,12 +81,12 @@ public static function commonNamespace(array $namespaces): string break; } - $matching [] = $part; + $matching[] = $part; } // We could not determine a common part of the configured namespaces, // so we just assume the user will prefer the first one in the list. - if ($matching === []) { + if ([] === $matching) { return $preferredNamespaceFallback; } diff --git a/src/Console/PrintSchemaCommand.php b/src/Console/PrintSchemaCommand.php index 40845494e6..ae42cb3378 100644 --- a/src/Console/PrintSchemaCommand.php +++ b/src/Console/PrintSchemaCommand.php @@ -53,7 +53,7 @@ public function handle(ASTCache $cache, Filesystem $storage, SchemaBuilder $sche if ($this->option('write')) { $storage->put($filename, $schemaString); - $this->info('Wrote schema to the default file storage (usually storage/app) as "'.$filename.'".'); + $this->info('Wrote schema to the default file storage (usually storage/app) as "' . $filename . '".'); } else { $this->info($schemaString); } @@ -62,8 +62,9 @@ public function handle(ASTCache $cache, Filesystem $storage, SchemaBuilder $sche protected function toJson(Schema $schema): string { $introspectionResult = Introspection::fromSchema($schema); - if ($introspectionResult === null) { - throw new \Exception(<<<'MESSAGE' + if (null === $introspectionResult) { + throw new \Exception( + <<<'MESSAGE' Did not receive a valid introspection result. Check if your schema is correct with: diff --git a/src/Console/ScalarCommand.php b/src/Console/ScalarCommand.php index dc70547504..2e906c2a89 100644 --- a/src/Console/ScalarCommand.php +++ b/src/Console/ScalarCommand.php @@ -17,6 +17,6 @@ protected function namespaceConfigKey(): string protected function getStub(): string { - return __DIR__.'/stubs/scalar.stub'; + return __DIR__ . '/stubs/scalar.stub'; } } diff --git a/src/Console/SubscriptionCommand.php b/src/Console/SubscriptionCommand.php index 0a5da0d2f3..873d529d3b 100644 --- a/src/Console/SubscriptionCommand.php +++ b/src/Console/SubscriptionCommand.php @@ -19,6 +19,6 @@ protected function namespaceConfigKey(): string protected function getStub(): string { - return __DIR__.'/stubs/subscription.stub'; + return __DIR__ . '/stubs/subscription.stub'; } } diff --git a/src/Console/UnionCommand.php b/src/Console/UnionCommand.php index afc3fafbf9..a989dc3d81 100644 --- a/src/Console/UnionCommand.php +++ b/src/Console/UnionCommand.php @@ -17,6 +17,6 @@ protected function namespaceConfigKey(): string protected function getStub(): string { - return __DIR__.'/stubs/typeResolver.stub'; + return __DIR__ . '/stubs/typeResolver.stub'; } } diff --git a/src/Console/ValidateSchemaCommand.php b/src/Console/ValidateSchemaCommand.php index 5d88e1f44b..49e291ce23 100644 --- a/src/Console/ValidateSchemaCommand.php +++ b/src/Console/ValidateSchemaCommand.php @@ -38,8 +38,8 @@ public function handle( ); foreach ($directiveLocator->definitions() as $directiveDefinition) { // TODO consider a solution that feels less hacky - if ($directiveDefinition->name->value !== 'deprecated') { - $schemaConfig->directives [] = $directiveFactory->handle($directiveDefinition); + if ('deprecated' !== $directiveDefinition->name->value) { + $schemaConfig->directives[] = $directiveFactory->handle($directiveDefinition); } } diff --git a/src/Console/ValidatorCommand.php b/src/Console/ValidatorCommand.php index b8cbe3e334..46be79795b 100644 --- a/src/Console/ValidatorCommand.php +++ b/src/Console/ValidatorCommand.php @@ -35,6 +35,6 @@ protected function namespaceConfigKey(): string */ protected function getStub(): string { - return __DIR__.'/stubs/validator.stub'; + return __DIR__ . '/stubs/validator.stub'; } } diff --git a/src/Defer/Defer.php b/src/Defer/Defer.php index 32528f2e21..1bb0e958b4 100644 --- a/src/Defer/Defer.php +++ b/src/Defer/Defer.php @@ -67,6 +67,7 @@ class Defer implements CreatesResponse * @var float|int */ protected $maxExecutionTime = 0; + /** * @var int */ @@ -94,12 +95,13 @@ public function handleStartExecution(StartExecution $startExecution): void * Register deferred field. * * @param \Closure(): mixed $resolver - * @return mixed The data if it is already available. + * + * @return mixed the data if it is already available */ public function defer(Closure $resolver, string $path) { $data = $this->getData($path); - if ($data !== null) { + if (null !== $data) { return $data; } @@ -128,18 +130,20 @@ protected function getData(string $path) /** * @param \Closure(): mixed $resolver + * * @return mixed The loaded data */ protected function resolve(Closure $resolver, string $path) { unset($this->deferred[$path]); - $this->resolved [] = $path; + $this->resolved[] = $path; return $resolver(); } /** * @param \Closure(): mixed $originalResolver + * * @return mixed The loaded data */ public function findOrResolve(Closure $originalResolver, string $path) @@ -160,6 +164,7 @@ protected function hasData(string $path): bool * Return either a final response or a stream of responses. * * @param array $result + * * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\StreamedResponse */ public function createResponse(array $result): Response @@ -181,7 +186,7 @@ function (): void { && ! $this->maxExecutionTimeReached() && ! $this->maxNestedFieldsResolved($nested) ) { - $nested++; + ++$nested; $this->executeDeferred(); } @@ -221,7 +226,7 @@ protected function stream(): void */ protected function maxExecutionTimeReached(): bool { - if ($this->maxExecutionTime === 0) { + if (0 === $this->maxExecutionTime) { return false; } @@ -233,7 +238,7 @@ protected function maxExecutionTimeReached(): bool */ protected function maxNestedFieldsResolved(int $nested): bool { - if ($this->maxNestedFields === 0) { + if (0 === $this->maxNestedFields) { return false; } diff --git a/src/Defer/DeferServiceProvider.php b/src/Defer/DeferServiceProvider.php index 5d483b1e88..ee7c3bb9d5 100644 --- a/src/Defer/DeferServiceProvider.php +++ b/src/Defer/DeferServiceProvider.php @@ -37,7 +37,7 @@ function (ManipulateAST $manipulateAST): void { $dispatcher->listen( StartExecution::class, - Defer::class.'@handleStartExecution' + Defer::class . '@handleStartExecution' ); } diff --git a/src/Defer/DeferrableDirective.php b/src/Defer/DeferrableDirective.php index d412ec9233..c59728dfa7 100644 --- a/src/Defer/DeferrableDirective.php +++ b/src/Defer/DeferrableDirective.php @@ -75,7 +75,7 @@ protected function shouldDefer(TypeNode $fieldType, ResolveInfo $resolveInfo): b $defers = (new ClientDirective(self::DEFER_DIRECTIVE_NAME))->forField($resolveInfo); if ($this->anyFieldHasDefer($defers)) { - if ($resolveInfo->parentType->name === RootType::MUTATION) { + if (RootType::MUTATION === $resolveInfo->parentType->name) { throw new Error(self::THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_ROOT_MUTATION_FIELD); } if ($fieldType instanceof NonNullTypeNode) { @@ -86,7 +86,7 @@ protected function shouldDefer(TypeNode $fieldType, ResolveInfo $resolveInfo): b // Following the semantics of Apollo: // All declarations of a field have to contain @defer for the field to be deferred foreach ($defers as $defer) { - if ($defer === null || $defer === [Directive::IF_ARGUMENT_NAME => false]) { + if (null === $defer || $defer === [Directive::IF_ARGUMENT_NAME => false]) { return false; } } @@ -113,7 +113,7 @@ protected function shouldDefer(TypeNode $fieldType, ResolveInfo $resolveInfo): b protected function anyFieldHasDefer(array $defers): bool { foreach ($defers as $defer) { - if ($defer !== null) { + if (null !== $defer) { return true; } } diff --git a/src/Events/BuildExtensionsResponse.php b/src/Events/BuildExtensionsResponse.php index a353ed2e9c..cb7abf2f58 100644 --- a/src/Events/BuildExtensionsResponse.php +++ b/src/Events/BuildExtensionsResponse.php @@ -10,5 +10,4 @@ */ class BuildExtensionsResponse { - // } diff --git a/src/Events/RegisterDirectiveNamespaces.php b/src/Events/RegisterDirectiveNamespaces.php index 2252067915..7e5d7931e8 100644 --- a/src/Events/RegisterDirectiveNamespaces.php +++ b/src/Events/RegisterDirectiveNamespaces.php @@ -12,5 +12,4 @@ */ class RegisterDirectiveNamespaces { - // } diff --git a/src/Exceptions/FederationException.php b/src/Exceptions/FederationException.php index de28c21a96..ecdd6434df 100644 --- a/src/Exceptions/FederationException.php +++ b/src/Exceptions/FederationException.php @@ -6,5 +6,4 @@ class FederationException extends Exception { - // } diff --git a/src/Exceptions/InvalidDriverException.php b/src/Exceptions/InvalidDriverException.php index 19f95d79c1..49edfcf246 100644 --- a/src/Exceptions/InvalidDriverException.php +++ b/src/Exceptions/InvalidDriverException.php @@ -6,5 +6,4 @@ class InvalidDriverException extends Exception { - // } diff --git a/src/Exceptions/ParseException.php b/src/Exceptions/ParseException.php index 4be875213e..d8278f89e5 100644 --- a/src/Exceptions/ParseException.php +++ b/src/Exceptions/ParseException.php @@ -18,7 +18,7 @@ public function __construct(SyntaxError $error) if ($source instanceof Source && count($positions) > 0) { $position = $positions[0]; - $message .= ', near: '.\Safe\substr($source->body, max(0, $position - 50), 100); + $message .= ', near: ' . \Safe\substr($source->body, max(0, $position - 50), 100); } parent::__construct($message); diff --git a/src/Exceptions/ValidationException.php b/src/Exceptions/ValidationException.php index 12dd6aae4f..37aeb623a0 100644 --- a/src/Exceptions/ValidationException.php +++ b/src/Exceptions/ValidationException.php @@ -8,7 +8,7 @@ class ValidationException extends Exception implements RendersErrorsExtensions { - const CATEGORY = 'validation'; + public const CATEGORY = 'validation'; /** * @var \Illuminate\Contracts\Validation\Validator diff --git a/src/Execution/Arguments/ArgPartitioner.php b/src/Execution/Arguments/ArgPartitioner.php index d7056e840b..d1b23fd419 100644 --- a/src/Execution/Arguments/ArgPartitioner.php +++ b/src/Execution/Arguments/ArgPartitioner.php @@ -35,7 +35,7 @@ public static function nestedArgResolvers(ArgumentSet $argumentSet, $root): arra return static::partition( $argumentSet, static function (string $name, Argument $argument): bool { - return $argument->resolver !== null; + return null !== $argument->resolver; } ); } @@ -187,7 +187,7 @@ public static function methodReturnsRelation( $relationMethodCandidate = $modelReflection->getMethod($name); $returnType = $relationMethodCandidate->getReturnType(); - if ($returnType === null) { + if (null === $returnType) { return false; } @@ -196,7 +196,7 @@ public static function methodReturnsRelation( } if (! class_exists($returnType->getName())) { - throw new DefinitionException('Class '.$returnType->getName().' does not exist, did you forget to import the Eloquent relation class?'); + throw new DefinitionException('Class ' . $returnType->getName() . ' does not exist, did you forget to import the Eloquent relation class?'); } return is_a($returnType->getName(), $relationClass, true); diff --git a/src/Execution/Arguments/Argument.php b/src/Execution/Arguments/Argument.php index 42516168e2..2ddb8f1e9b 100644 --- a/src/Execution/Arguments/Argument.php +++ b/src/Execution/Arguments/Argument.php @@ -42,7 +42,7 @@ public function __construct() /** * Get the plain PHP value of this argument. * - * @return mixed The plain PHP value. + * @return mixed the plain PHP value */ public function toPlain() { @@ -53,6 +53,7 @@ public function toPlain() * Convert the given value to plain PHP values recursively. * * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet>|mixed|array $value + * * @return mixed|array */ protected static function toPlainRecursive($value) diff --git a/src/Execution/Arguments/ArgumentSet.php b/src/Execution/Arguments/ArgumentSet.php index ae1d0a318b..ed64299a99 100644 --- a/src/Execution/Arguments/ArgumentSet.php +++ b/src/Execution/Arguments/ArgumentSet.php @@ -59,11 +59,11 @@ public function has(string $key): bool { $argument = $this->arguments[$key] ?? null; - if ($argument === null) { + if (null === $argument) { return false; } - return $argument->value !== null; + return null !== $argument->value; } /** @@ -96,7 +96,7 @@ function ($value) { return $directive instanceof RenameDirective; }); - if ($renameDirective !== null) { + if (null !== $renameDirective) { $argumentSet->arguments[$renameDirective->attributeArgValue()] = $argument; } else { $argumentSet->arguments[$name] = $argument; @@ -111,6 +111,7 @@ function ($value) { * * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder * @param array $scopes + * * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Laravel\Scout\Builder */ public function enhanceBuilder(object $builder, array $scopes, Closure $directiveFilter = null): object @@ -197,7 +198,7 @@ protected static function applyFieldBuilderDirectives(self $argumentSet, object * * Works just like @see \Illuminate\Support\Arr::add(). * - * @param mixed $value Any value to inject. + * @param mixed $value any value to inject */ public function addValue(string $path, $value): self { diff --git a/src/Execution/Arguments/ArgumentSetFactory.php b/src/Execution/Arguments/ArgumentSetFactory.php index 5e11924e1c..8304435aa9 100644 --- a/src/Execution/Arguments/ArgumentSetFactory.php +++ b/src/Execution/Arguments/ArgumentSetFactory.php @@ -71,7 +71,7 @@ public function wrapArgs(Node $definition, array $args): ArgumentSet } elseif ($definition instanceof InputObjectTypeDefinitionNode) { $argDefinitions = $definition->fields; } else { - throw new InvalidArgumentException('Got unexpected node of type '.get_class($definition)); + throw new InvalidArgumentException('Got unexpected node of type ' . get_class($definition)); } $argumentDefinitionMap = $this->makeDefinitionMap($argDefinitions); @@ -91,6 +91,7 @@ public function wrapArgs(Node $definition, array $args): ArgumentSet * Make a map with the name as keys. * * @param iterable<\GraphQL\Language\AST\InputValueDefinitionNode> $argumentDefinitions + * * @return array */ protected function makeDefinitionMap($argumentDefinitions): array @@ -107,7 +108,7 @@ protected function makeDefinitionMap($argumentDefinitions): array /** * Wrap a single client-given argument with type information. * - * @param mixed $value The client given value. + * @param mixed $value the client given value */ protected function wrapInArgument($value, InputValueDefinitionNode $definition): Argument { @@ -126,12 +127,13 @@ protected function wrapInArgument($value, InputValueDefinitionNode $definition): * * @param mixed|array $valueOrValues * @param \Nuwave\Lighthouse\Execution\Arguments\ListType|\Nuwave\Lighthouse\Execution\Arguments\NamedType $type + * * @return array|mixed|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet */ protected function wrapWithType($valueOrValues, $type) { // No need to recurse down further if the value is null - if ($valueOrValues === null) { + if (null === $valueOrValues) { return null; } @@ -142,7 +144,7 @@ protected function wrapWithType($valueOrValues, $type) $values = []; foreach ($valueOrValues as $singleValue) { - $values [] = $this->wrapWithType($singleValue, $typeInList); + $values[] = $this->wrapWithType($singleValue, $typeInList); } return $values; @@ -154,7 +156,8 @@ protected function wrapWithType($valueOrValues, $type) /** * Wrap a client-given value with information from a named type. * - * @param mixed $value The client given value. + * @param mixed $value the client given value + * * @return \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|mixed */ protected function wrapWithNamedType($value, NamedType $namedType) diff --git a/src/Execution/Arguments/ArgumentTypeNodeConverter.php b/src/Execution/Arguments/ArgumentTypeNodeConverter.php index 12d43d329a..2a95d9929e 100644 --- a/src/Execution/Arguments/ArgumentTypeNodeConverter.php +++ b/src/Execution/Arguments/ArgumentTypeNodeConverter.php @@ -8,6 +8,7 @@ class ArgumentTypeNodeConverter extends TypeNodeConverter { /** * @param \Nuwave\Lighthouse\Execution\Arguments\ListType|\Nuwave\Lighthouse\Execution\Arguments\NamedType $type + * * @return \Nuwave\Lighthouse\Execution\Arguments\ListType|\Nuwave\Lighthouse\Execution\Arguments\NamedType */ protected function nonNull($type): object @@ -19,6 +20,7 @@ protected function nonNull($type): object /** * @param \Nuwave\Lighthouse\Execution\Arguments\NamedType $type + * * @return \Nuwave\Lighthouse\Execution\Arguments\ListType */ protected function listOf($type): object diff --git a/src/Execution/Arguments/UpdateModel.php b/src/Execution/Arguments/UpdateModel.php index b7818d8247..65b8775ee2 100644 --- a/src/Execution/Arguments/UpdateModel.php +++ b/src/Execution/Arguments/UpdateModel.php @@ -8,7 +8,7 @@ class UpdateModel implements ArgResolver { - const MISSING_PRIMARY_KEY_FOR_UPDATE = 'Missing primary key for update.'; + public const MISSING_PRIMARY_KEY_FOR_UPDATE = 'Missing primary key for update.'; /** * @var callable|\Nuwave\Lighthouse\Support\Contracts\ArgResolver @@ -34,7 +34,7 @@ public function __invoke($model, $args) ?? Arr::pull($args->arguments, $model->getKeyName()) ?? null; - if ($id === null) { + if (null === $id) { throw new Error(self::MISSING_PRIMARY_KEY_FOR_UPDATE); } diff --git a/src/Execution/Arguments/UpsertModel.php b/src/Execution/Arguments/UpsertModel.php index 4a15f215dc..1f3b28f6b6 100644 --- a/src/Execution/Arguments/UpsertModel.php +++ b/src/Execution/Arguments/UpsertModel.php @@ -30,12 +30,12 @@ public function __invoke($model, $args) ?? $args->arguments[$model->getKeyName()] ?? null; - if ($id !== null) { + if (null !== $id) { $existingModel = $model ->newQuery() ->find($id->value); - if ($existingModel !== null) { + if (null !== $existingModel) { $model = $existingModel; } } diff --git a/src/Execution/AuthenticationErrorHandler.php b/src/Execution/AuthenticationErrorHandler.php index 689cb706a6..f0761d4aa2 100644 --- a/src/Execution/AuthenticationErrorHandler.php +++ b/src/Execution/AuthenticationErrorHandler.php @@ -14,7 +14,7 @@ class AuthenticationErrorHandler implements ErrorHandler { public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } diff --git a/src/Execution/AuthorizationErrorHandler.php b/src/Execution/AuthorizationErrorHandler.php index cc8cca1e3f..8c58817181 100644 --- a/src/Execution/AuthorizationErrorHandler.php +++ b/src/Execution/AuthorizationErrorHandler.php @@ -14,7 +14,7 @@ class AuthorizationErrorHandler implements ErrorHandler { public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } diff --git a/src/Execution/BatchLoader/BatchLoaderRegistry.php b/src/Execution/BatchLoader/BatchLoaderRegistry.php index 9f4b1bc73b..aa07f8556e 100644 --- a/src/Execution/BatchLoader/BatchLoaderRegistry.php +++ b/src/Execution/BatchLoader/BatchLoaderRegistry.php @@ -18,9 +18,10 @@ abstract class BatchLoaderRegistry * * @param array $pathToField Path to the GraphQL field from the root, is used as a key for BatchLoader instances * @param callable(): TBatchLoader $makeInstance Function to instantiate the instance once - * @return TBatchLoader The result of calling makeInstance * * @throws \Exception + * + * @return TBatchLoader The result of calling makeInstance */ public static function instance(array $pathToField, callable $makeInstance): object { diff --git a/src/Execution/DataLoader/BatchLoader.php b/src/Execution/DataLoader/BatchLoader.php index e3392fa935..66838f099b 100644 --- a/src/Execution/DataLoader/BatchLoader.php +++ b/src/Execution/DataLoader/BatchLoader.php @@ -5,7 +5,7 @@ use GraphQL\Deferred; /** - * @deprecated implement your own batch loader instead. + * @deprecated implement your own batch loader instead * @see \Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry to resolve instances. */ abstract class BatchLoader @@ -77,7 +77,7 @@ function ($path): bool { ); $pathIgnoringLists = implode('.', $significantPathSegments); - return 'nuwave/lighthouse/batchloader/'.$pathIgnoringLists; + return 'nuwave/lighthouse/batchloader/' . $pathIgnoringLists; } /** @@ -115,6 +115,7 @@ public function load(string $key, array $metaInfo = []): Deferred * * @param array $keys * @param array $metaInfo + * * @return array<\GraphQL\Deferred> */ public function loadMany(array $keys, array $metaInfo = []): array diff --git a/src/Execution/ErrorPool.php b/src/Execution/ErrorPool.php index 38fca74a12..e2c887964d 100644 --- a/src/Execution/ErrorPool.php +++ b/src/Execution/ErrorPool.php @@ -19,7 +19,7 @@ class ErrorPool */ public function record(Throwable $throwable): void { - $this->throwables [] = $throwable; + $this->throwables[] = $throwable; } /** diff --git a/src/Execution/ExtensionErrorHandler.php b/src/Execution/ExtensionErrorHandler.php index bd19c6966a..bad78138c2 100644 --- a/src/Execution/ExtensionErrorHandler.php +++ b/src/Execution/ExtensionErrorHandler.php @@ -15,7 +15,7 @@ class ExtensionErrorHandler implements ErrorHandler { public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } diff --git a/src/Execution/ExtensionsResponse.php b/src/Execution/ExtensionsResponse.php index 780c0718c7..a1fa306b22 100644 --- a/src/Execution/ExtensionsResponse.php +++ b/src/Execution/ExtensionsResponse.php @@ -15,7 +15,7 @@ class ExtensionsResponse protected $key; /** - * @var mixed JSON-encodable content of the extension. + * @var mixed JSON-encodable content of the extension */ protected $content; @@ -37,7 +37,7 @@ public function key(): string } /** - * @return mixed JSON-encodable content of the extension. + * @return mixed JSON-encodable content of the extension */ public function content() { diff --git a/src/Execution/ModelsLoader/PaginatedModelsLoader.php b/src/Execution/ModelsLoader/PaginatedModelsLoader.php index 8fdfb4b783..2853d329f2 100644 --- a/src/Execution/ModelsLoader/PaginatedModelsLoader.php +++ b/src/Execution/ModelsLoader/PaginatedModelsLoader.php @@ -152,7 +152,7 @@ protected function loadDefaultWith(EloquentCollection $collection): void { /** @var \Illuminate\Database\Eloquent\Model|null $model */ $model = $collection->first(); - if ($model === null) { + if (null === $model) { return; } diff --git a/src/Execution/ModelsLoader/SimpleModelsLoader.php b/src/Execution/ModelsLoader/SimpleModelsLoader.php index 985c210443..ca13095477 100644 --- a/src/Execution/ModelsLoader/SimpleModelsLoader.php +++ b/src/Execution/ModelsLoader/SimpleModelsLoader.php @@ -32,7 +32,7 @@ public function load(EloquentCollection $parents): void /** * Extract the relation that was loaded. * - * @return mixed The model's relation. + * @return mixed the model's relation */ public function extract(Model $model) { diff --git a/src/Execution/ReportingErrorHandler.php b/src/Execution/ReportingErrorHandler.php index 40d97f79e6..9b6004a6ab 100644 --- a/src/Execution/ReportingErrorHandler.php +++ b/src/Execution/ReportingErrorHandler.php @@ -23,7 +23,7 @@ public function __construct(ExceptionHandler $exceptionHandler) public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } @@ -34,7 +34,7 @@ public function __invoke(?Error $error, Closure $next): ?array } $previous = $error->getPrevious(); - if ($previous !== null) { + if (null !== $previous) { // @phpstan-ignore-next-line Laravel versions prior to 7 are limited to accepting \Exception $this->exceptionHandler->report($previous); } diff --git a/src/Execution/Resolved.php b/src/Execution/Resolved.php index 77491b945d..75c2c4c60c 100644 --- a/src/Execution/Resolved.php +++ b/src/Execution/Resolved.php @@ -11,6 +11,7 @@ class Resolved * * @param \GraphQL\Deferred|mixed $resolved The result of calling a resolver * @param callable(mixed $result): mixed $handle A function that takes that result and transforms it + * * @return \GraphQL\Deferred|mixed The transformed result or enhanced Deferred */ public static function handle($resolved, callable $handle) diff --git a/src/Execution/Utils/Subscription.php b/src/Execution/Utils/Subscription.php index 527c4c0887..4ef235e9cb 100644 --- a/src/Execution/Utils/Subscription.php +++ b/src/Execution/Utils/Subscription.php @@ -35,7 +35,7 @@ public static function broadcast(string $subscriptionField, $root, ?bool $should $broadcaster = app(BroadcastsSubscriptions::class); // Default to the configuration setting if not specified - if ($shouldQueue === null) { + if (null === $shouldQueue) { $shouldQueue = config('lighthouse.subscriptions.queue_broadcasts', false); } diff --git a/src/Execution/ValidationErrorHandler.php b/src/Execution/ValidationErrorHandler.php index 1c4ddc51eb..2228271f6e 100644 --- a/src/Execution/ValidationErrorHandler.php +++ b/src/Execution/ValidationErrorHandler.php @@ -14,7 +14,7 @@ class ValidationErrorHandler implements ErrorHandler { public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } diff --git a/src/Federation/ASTManipulator.php b/src/Federation/ASTManipulator.php index f6120b1bc4..968ba49c2d 100644 --- a/src/Federation/ASTManipulator.php +++ b/src/Federation/ASTManipulator.php @@ -53,14 +53,14 @@ protected function addEntityUnion(DocumentAST &$documentAST): void /** @var \GraphQL\Language\AST\DirectiveNode $directive */ foreach ($type->directives as $directive) { - if ($directive->name->value === 'key') { + if ('key' === $directive->name->value) { $entities[] = $type->name->value; break; } } } - if (count($entities) === 0) { + if (0 === count($entities)) { throw new FederationException('There must be at least one type using the @key directive when federation is enabled.'); } @@ -83,13 +83,13 @@ protected function addRootFields(DocumentAST &$documentAST): void /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode $queryType */ $queryType = $documentAST->types[RootType::QUERY]; - $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ ' + $queryType->fields[] = Parser::fieldDefinition(/** @lang GraphQL */ ' _entities( representations: [_Any!]! ): [_Entity]! @field(resolver: "Nuwave\\\Lighthouse\\\Federation\\\Resolvers\\\Entities") '); - $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ ' + $queryType->fields[] = Parser::fieldDefinition(/** @lang GraphQL */ ' _service: _Service! @field(resolver: "Nuwave\\\Lighthouse\\\Federation\\\Resolvers\\\Service") '); } diff --git a/src/Federation/Directives/ExtendsDirective.php b/src/Federation/Directives/ExtendsDirective.php index cde062e1a6..dd3ffb0d84 100644 --- a/src/Federation/Directives/ExtendsDirective.php +++ b/src/Federation/Directives/ExtendsDirective.php @@ -6,7 +6,7 @@ class ExtendsDirective extends BaseDirective { - const NAME = 'extends'; + public const NAME = 'extends'; /** * @see https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#schema-modifications-glossary diff --git a/src/Federation/Directives/ExternalDirective.php b/src/Federation/Directives/ExternalDirective.php index 8be2740e63..c52d21a177 100644 --- a/src/Federation/Directives/ExternalDirective.php +++ b/src/Federation/Directives/ExternalDirective.php @@ -11,7 +11,7 @@ class ExternalDirective extends BaseDirective implements FieldResolver { - const NAME = 'external'; + public const NAME = 'external'; public static function definition(): string { diff --git a/src/Federation/Directives/KeyDirective.php b/src/Federation/Directives/KeyDirective.php index a46aaa9847..d5305e8807 100644 --- a/src/Federation/Directives/KeyDirective.php +++ b/src/Federation/Directives/KeyDirective.php @@ -9,7 +9,7 @@ class KeyDirective extends BaseDirective { - const NAME = 'key'; + public const NAME = 'key'; /** * @see https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#schema-modifications-glossary diff --git a/src/Federation/Directives/ProvidesDirective.php b/src/Federation/Directives/ProvidesDirective.php index 83ecac01a9..aaacf44442 100644 --- a/src/Federation/Directives/ProvidesDirective.php +++ b/src/Federation/Directives/ProvidesDirective.php @@ -6,7 +6,7 @@ class ProvidesDirective extends BaseDirective { - const NAME = 'provides'; + public const NAME = 'provides'; public static function definition(): string { diff --git a/src/Federation/Directives/RequiresDirective.php b/src/Federation/Directives/RequiresDirective.php index 4c25852b2e..e53837d01f 100644 --- a/src/Federation/Directives/RequiresDirective.php +++ b/src/Federation/Directives/RequiresDirective.php @@ -6,7 +6,7 @@ class RequiresDirective extends BaseDirective { - const NAME = 'requires'; + public const NAME = 'requires'; /** * @see https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#schema-modifications-glossary diff --git a/src/Federation/EntityResolverProvider.php b/src/Federation/EntityResolverProvider.php index 8a6a9c20d0..361249db93 100644 --- a/src/Federation/EntityResolverProvider.php +++ b/src/Federation/EntityResolverProvider.php @@ -79,7 +79,7 @@ public function resolver(string $typename): Closure ?? $this->resolverFromModel($typename) ?? null; - if ($resolver === null) { + if (null === $resolver) { throw new Error(self::missingResolver($typename)); } @@ -100,7 +100,7 @@ public function typeDefinition(string $typename): ObjectTypeDefinitionNode } catch (DefinitionException $definitionException) { // Signalizes the type is unknown, handled by the null check below } - if ($type === null) { + if (null === $type) { throw new Error(self::unknownTypename($typename)); } @@ -110,7 +110,7 @@ public function typeDefinition(string $typename): ObjectTypeDefinitionNode * @var (\GraphQL\Language\AST\Node&\GraphQL\Language\AST\TypeDefinitionNode)|null $definition */ $definition = $type->astNode; - if ($definition === null) { + if (null === $definition) { throw new FederationException("Must provide AST definition for type `{$typename}`."); } @@ -131,7 +131,7 @@ protected function resolverFromClass(string $typename): ?Closure 'class_exists' ); - if ($resolverClass === null) { + if (null === $resolverClass) { return null; } @@ -152,7 +152,7 @@ static function (string $classCandidate): bool { return is_subclass_of($classCandidate, Model::class); } ); - if ($modelClass === null) { + if (null === $modelClass) { return null; } @@ -200,12 +200,12 @@ protected function satisfiesKeyFields(SelectionSetNode $keyFields, array $repres foreach ($keyFields->selections as $field) { $fieldName = $field->name->value; $value = $representation[$fieldName] ?? null; - if ($value === null) { + if (null === $value) { return false; } $subSelection = $field->selectionSet; - if ($subSelection !== null) { + if (null !== $subSelection) { if (! is_array($value)) { return false; } @@ -235,7 +235,7 @@ protected function applySatisfiedSelection(Builder $builder, SelectionSetNode $k $value = $representation[$fieldName]; $subSelection = $field->selectionSet; - if ($subSelection === null) { + if (null === $subSelection) { $builder->where($fieldName, $value); return; @@ -269,8 +269,8 @@ function (SelectionSetNode $keyFields) use ($representation): bool { } ); - if ($satisfiedKeyFields === null) { - throw new Error('Representation does not satisfy any set of uniquely identifying keys: '.\Safe\json_encode($representation)); + if (null === $satisfiedKeyFields) { + throw new Error('Representation does not satisfy any set of uniquely identifying keys: ' . \Safe\json_encode($representation)); } return $satisfiedKeyFields; diff --git a/src/Federation/FederationPrinter.php b/src/Federation/FederationPrinter.php index 7641ab93d9..e11fb57787 100644 --- a/src/Federation/FederationPrinter.php +++ b/src/Federation/FederationPrinter.php @@ -25,19 +25,19 @@ class FederationPrinter { - const FEDERATION_TYPES = [ + public const FEDERATION_TYPES = [ '_Any', '_Entity', '_FieldSet', '_Service', ]; - const FEDERATION_FIELDS = [ + public const FEDERATION_FIELDS = [ '_service', '_entities', ]; - const FEDERATION_DIRECTIVES = [ + public const FEDERATION_DIRECTIVES = [ ExtendsDirective::NAME, ExternalDirective::NAME, KeyDirective::NAME, @@ -87,7 +87,7 @@ static function (Directive $directive): bool { $printDirectives = static function ($definition): string { /** @var Type|EnumValueDefinition|FieldArgument|FieldDefinition|InputObjectField $definition */ $astNode = $definition->astNode; - if ($astNode === null) { + if (null === $astNode) { return ''; } @@ -98,8 +98,8 @@ static function (Directive $directive): bool { static function (DirectiveNode $directive): bool { $name = $directive->name->value; - return $name === KeyDirective::NAME - || $name === ExtendsDirective::NAME; + return KeyDirective::NAME === $name + || ExtendsDirective::NAME === $name; } ) ); @@ -110,9 +110,9 @@ static function (DirectiveNode $directive): bool { static function (DirectiveNode $directive): bool { $name = $directive->name->value; - return $name === ProvidesDirective::NAME - || $name === RequiresDirective::NAME - || $name === ExternalDirective::NAME; + return ProvidesDirective::NAME === $name + || RequiresDirective::NAME === $name + || ExternalDirective::NAME === $name; } ) ); diff --git a/src/Federation/FederationServiceProvider.php b/src/Federation/FederationServiceProvider.php index 1c153132be..8b7dc55fa2 100644 --- a/src/Federation/FederationServiceProvider.php +++ b/src/Federation/FederationServiceProvider.php @@ -20,7 +20,7 @@ public function boot(EventsDispatcher $eventsDispatcher): void $eventsDispatcher->listen( RegisterDirectiveNamespaces::class, static function (): string { - return __NAMESPACE__.'\\Directives'; + return __NAMESPACE__ . '\\Directives'; } ); diff --git a/src/Federation/Resolvers/Entities.php b/src/Federation/Resolvers/Entities.php index 94c6dbaab1..4c186522c5 100644 --- a/src/Federation/Resolvers/Entities.php +++ b/src/Federation/Resolvers/Entities.php @@ -25,6 +25,7 @@ public function __construct(EntityResolverProvider $entityResolverProvider) /** * @param array{representations: array} $args + * * @return list */ public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array @@ -35,7 +36,7 @@ public function __invoke($root, array $args, GraphQLContext $context, ResolveInf $typename = $representation['__typename']; $resolver = $this->entityResolverProvider->resolver($typename); - $results [] = $resolver($representation); + $results[] = $resolver($representation); } return $results; diff --git a/src/Federation/Resolvers/Service.php b/src/Federation/Resolvers/Service.php index d4dbded9e4..1661994cac 100644 --- a/src/Federation/Resolvers/Service.php +++ b/src/Federation/Resolvers/Service.php @@ -10,6 +10,7 @@ class Service { /** * @param array $args Always empty + * * @return array{sdl: string} */ public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array diff --git a/src/Federation/SchemaPrinter.php b/src/Federation/SchemaPrinter.php index a849104325..98e97238b5 100644 --- a/src/Federation/SchemaPrinter.php +++ b/src/Federation/SchemaPrinter.php @@ -26,15 +26,15 @@ protected static function printFields(array $options, $type): string array_map( static function (FieldDefinition $f) use (&$firstInBlock, $options): string { $description = static::printDescription($options, $f, ' ', $firstInBlock) - .' ' - .$f->name - .static::printArgs($options, $f->args, ' ') - .': ' - .$f->getType() - .(isset($options['printDirectives']) + . ' ' + . $f->name + . static::printArgs($options, $f->args, ' ') + . ': ' + . $f->getType() + . (isset($options['printDirectives']) ? $options['printDirectives']($f) : '') - .static::printDeprecated($f); + . static::printDeprecated($f); $firstInBlock = false; @@ -69,7 +69,7 @@ protected static function printObjectLike(string $kind, Type $type, array $optio { $interfaces = $type->getInterfaces(); $implementedInterfaces = count($interfaces) > 0 - ? ' implements '.implode( + ? ' implements ' . implode( ' & ', array_map( static function (InterfaceType $interface): string { @@ -98,12 +98,12 @@ static function (InterfaceType $interface): string { */ public static function printDirectives(array $directives): string { - if (count($directives) === 0) { + if (0 === count($directives)) { return ''; } return ' ' - .implode( + . implode( ' ', Utils::map($directives, static function (DirectiveNode $directive): string { return Printer::doPrint($directive); diff --git a/src/Federation/SchemaValidator.php b/src/Federation/SchemaValidator.php index ff6b5cf5e3..152236d7e5 100644 --- a/src/Federation/SchemaValidator.php +++ b/src/Federation/SchemaValidator.php @@ -41,7 +41,7 @@ public function handle(ValidateSchema $validateSchema): void protected function validateObjectType(ObjectType $type): void { $ast = $type->astNode; - if ($ast !== null) { + if (null !== $ast) { $directives = $this->directiveLocator->associated($ast); /** @var \Nuwave\Lighthouse\Support\Contracts\Directive $directive */ @@ -78,7 +78,7 @@ protected function validateKeySelectionSet(SelectionSetNode $selectionSet, Objec } $nestedSelection = $selection->selectionSet; - if ($nestedSelection !== null) { + if (null !== $nestedSelection) { $type = $field->getType(); if ($type instanceof WrappingType) { $type = $type->getWrappedType(true); diff --git a/src/Federation/Types/Any.php b/src/Federation/Types/Any.php index 8a4bdd0ac6..65515dfac3 100644 --- a/src/Federation/Types/Any.php +++ b/src/Federation/Types/Any.php @@ -12,7 +12,7 @@ */ class Any extends ScalarType { - const MESSAGE = 'Expected an input with a field `__typename` and matching fields, got: '; + public const MESSAGE = 'Expected an input with a field `__typename` and matching fields, got: '; public $name = '_Any'; @@ -33,12 +33,12 @@ public function parseValue($value): array // We do as much validation as possible here, before entering resolvers if (! is_array($value)) { - throw new Error(self::MESSAGE.\Safe\json_encode($value)); + throw new Error(self::MESSAGE . \Safe\json_encode($value)); } $typename = $value['__typename'] ?? null; if (! is_string($typename)) { - throw new Error(self::MESSAGE.\Safe\json_encode($value)); + throw new Error(self::MESSAGE . \Safe\json_encode($value)); } /** @var \Nuwave\Lighthouse\Federation\EntityResolverProvider $entityResolverProvider */ diff --git a/src/GlobalId/GlobalId.php b/src/GlobalId/GlobalId.php index fc70d6041d..554e8addcc 100644 --- a/src/GlobalId/GlobalId.php +++ b/src/GlobalId/GlobalId.php @@ -20,14 +20,14 @@ class GlobalId implements GlobalIdContract { public function encode(string $type, $id): string { - return base64_encode($type.':'.$id); + return base64_encode($type . ':' . $id); } public function decode(string $globalID): array { $parts = explode(':', \Safe\base64_decode($globalID)); - if (count($parts) !== 2) { + if (2 !== count($parts)) { throw new GlobalIdException("Unexpectedly found more then 2 segments when decoding global id: {$globalID}."); } diff --git a/src/GlobalId/GlobalIdDirective.php b/src/GlobalId/GlobalIdDirective.php index 2b02b861c1..1d580fa1cb 100644 --- a/src/GlobalId/GlobalIdDirective.php +++ b/src/GlobalId/GlobalIdDirective.php @@ -81,6 +81,7 @@ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue * Decodes a global id given as an argument. * * @param string|null $argumentValue + * * @return string|array{0: string, 1: string}|null */ public function sanitize($argumentValue) diff --git a/src/GlobalId/GlobalIdServiceProvider.php b/src/GlobalId/GlobalIdServiceProvider.php index 1944ffd0ae..76a9215194 100644 --- a/src/GlobalId/GlobalIdServiceProvider.php +++ b/src/GlobalId/GlobalIdServiceProvider.php @@ -15,7 +15,7 @@ class GlobalIdServiceProvider extends ServiceProvider { - const NODE = 'Node'; + public const NODE = 'Node'; public function register(): void { @@ -66,10 +66,10 @@ interface $node @interface(resolveType: "Nuwave\\\Lighthouse\\\GlobalId\\\NodeRe /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode $queryType */ $queryType = $documentAST->types[RootType::QUERY]; - $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ <<<'GRAPHQL' + $queryType->fields[] = Parser::fieldDefinition(/** @lang GraphQL */ <<<'GRAPHQL' node(id: ID! @globalId): Node @field(resolver: "Nuwave\\Lighthouse\\GlobalId\\NodeRegistry@resolve") GRAPHQL -); + ); } protected function hasTypeImplementingNodeInterface(DocumentAST $documentAST): bool diff --git a/src/GlobalId/NodeDirective.php b/src/GlobalId/NodeDirective.php index c19c8a897c..9c374d1080 100644 --- a/src/GlobalId/NodeDirective.php +++ b/src/GlobalId/NodeDirective.php @@ -93,9 +93,9 @@ public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefiniti /** @var \GraphQL\Language\AST\NamedTypeNode $namedTypeNode */ $namedTypeNode = Parser::parseType(GlobalIdServiceProvider::NODE, ['noLocation' => true]); - $typeDefinition->interfaces [] = $namedTypeNode; + $typeDefinition->interfaces[] = $namedTypeNode; $globalIdFieldName = config('lighthouse.global_id_field'); - $typeDefinition->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ "{$globalIdFieldName}: ID! @globalId"); + $typeDefinition->fields[] = Parser::fieldDefinition(/** @lang GraphQL */ "{$globalIdFieldName}: ID! @globalId"); } } diff --git a/src/GlobalId/NodeRegistry.php b/src/GlobalId/NodeRegistry.php index 7513676157..c69e54ef33 100644 --- a/src/GlobalId/NodeRegistry.php +++ b/src/GlobalId/NodeRegistry.php @@ -60,9 +60,10 @@ public function registerNode(string $typeName, Closure $resolve): self * Get the appropriate resolver for the node and call it with the decoded id. * * @param array $args - * @return mixed The result of calling the resolver. * * @throws \GraphQL\Error\Error + * + * @return mixed the result of calling the resolver */ public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { diff --git a/src/GraphQL.php b/src/GraphQL.php index 4e015433e5..631a800890 100644 --- a/src/GraphQL.php +++ b/src/GraphQL.php @@ -102,6 +102,7 @@ public function __construct( * Run one ore more GraphQL operations against the schema. * * @param \GraphQL\Server\OperationParams|array $operationOrOperations + * * @return array|array> */ public function executeOperationOrOperations($operationOrOperations, GraphQLContext $context): array @@ -137,7 +138,7 @@ public function executeOperation(OperationParams $params, GraphQLContext $contex $errors = $this->graphQLHelper->validateOperationParams($params); $query = $params->query; - if (! is_string($query) || $query === '') { + if (! is_string($query) || '' === $query) { $errors[] = new RequestError( 'GraphQL Request parameter "query" is required and must not be empty.' ); @@ -215,17 +216,17 @@ public function executeQuery( /** @var array<\Nuwave\Lighthouse\Execution\ExtensionsResponse|null> $extensionsResponses */ $extensionsResponses = (array) $this->eventDispatcher->dispatch( - new BuildExtensionsResponse + new BuildExtensionsResponse() ); foreach ($extensionsResponses as $extensionsResponse) { - if ($extensionsResponse !== null) { + if (null !== $extensionsResponse) { $result->extensions[$extensionsResponse->key()] = $extensionsResponse->content(); } } foreach ($this->errorPool->errors() as $error) { - $result->errors [] = $error; + $result->errors[] = $error; } // Allow listeners to manipulate the result after each resolved query @@ -277,7 +278,7 @@ protected function errorsHandler(): \Closure // This allows the user to register multiple handlers and pipe the errors through. $handlers = []; foreach ($this->configRepository->get('lighthouse.error_handlers', []) as $handlerClass) { - $handlers [] = app($handlerClass); + $handlers[] = app($handlerClass); } return (new Collection($errors)) @@ -286,7 +287,7 @@ protected function errorsHandler(): \Closure ->send($error) ->through($handlers) ->then(function (?Error $error) use ($formatter): ?array { - if ($error === null) { + if (null === $error) { return null; } diff --git a/src/LighthouseServiceProvider.php b/src/LighthouseServiceProvider.php index f4ea6f7b99..2badc9fdb0 100644 --- a/src/LighthouseServiceProvider.php +++ b/src/LighthouseServiceProvider.php @@ -60,7 +60,7 @@ class LighthouseServiceProvider extends ServiceProvider /** * @var array> */ - const COMMANDS = [ + public const COMMANDS = [ CacheCommand::class, ClearCacheCommand::class, DirectiveCommand::class, @@ -78,7 +78,7 @@ class LighthouseServiceProvider extends ServiceProvider public function register(): void { - $this->mergeConfigFrom(__DIR__.'/lighthouse.php', 'lighthouse'); + $this->mergeConfigFrom(__DIR__ . '/lighthouse.php', 'lighthouse'); $this->app->singleton(GraphQL::class); $this->app->singleton(ASTBuilder::class); @@ -99,8 +99,7 @@ public function register(): void $this->app->bind(ProvidesResolver::class, ResolverProvider::class); $this->app->bind(ProvidesSubscriptionResolver::class, static function (): ProvidesSubscriptionResolver { - return new class implements ProvidesSubscriptionResolver - { + return new class() implements ProvidesSubscriptionResolver { public function provideSubscriptionResolver(FieldValue $fieldValue): Closure { throw new Exception( @@ -125,7 +124,7 @@ public function provideSubscriptionResolver(FieldValue $fieldValue): Closure } throw new Exception( - 'Could not correctly determine Laravel framework flavor, got '.get_class($app).'.' + 'Could not correctly determine Laravel framework flavor, got ' . get_class($app) . '.' ); }); @@ -141,14 +140,14 @@ public function provideSubscriptionResolver(FieldValue $fieldValue): Closure public function boot(ConfigRepository $configRepository): void { $this->publishes([ - __DIR__.'/lighthouse.php' => $this->app->configPath().'/lighthouse.php', + __DIR__ . '/lighthouse.php' => $this->app->configPath() . '/lighthouse.php', ], 'lighthouse-config'); $this->publishes([ - __DIR__.'/default-schema.graphql' => $configRepository->get('lighthouse.schema.register'), + __DIR__ . '/default-schema.graphql' => $configRepository->get('lighthouse.schema.register'), ], 'lighthouse-schema'); - $this->loadRoutesFrom(__DIR__.'/Support/Http/routes.php'); + $this->loadRoutesFrom(__DIR__ . '/Support/Http/routes.php'); $exceptionHandler = $this->app->make(ExceptionHandlerContract::class); if ( diff --git a/src/OrderBy/OrderByDirective.php b/src/OrderBy/OrderByDirective.php index 28d2a445a0..1ebe2cb329 100644 --- a/src/OrderBy/OrderByDirective.php +++ b/src/OrderBy/OrderByDirective.php @@ -116,9 +116,9 @@ public function handleBuilder($builder, $value): object $order = Arr::pull($orderByClause, 'order'); $column = Arr::pull($orderByClause, 'column'); - if ($column === null) { + if (null === $column) { if (! $builder instanceof Builder) { - throw new DefinitionException('Can not order by relations on non-Eloquent builders, got: '.get_class($builder)); + throw new DefinitionException('Can not order by relations on non-Eloquent builders, got: ' . get_class($builder)); } // TODO use array_key_first() in PHP 7.3 @@ -128,12 +128,12 @@ public function handleBuilder($builder, $value): object $relationValues = Arr::first($orderByClause); $aggregate = $relationValues['aggregate']; - if ($aggregate === 'count') { + if ('count' === $aggregate) { $builder->withCount($relation); $column = "{$relationSnake}_count"; } else { - $operator = 'with'.ucfirst($aggregate); + $operator = 'with' . ucfirst($aggregate); $relationColumn = $relationValues['column']; $builder->{$operator}($relation, $relationColumn); @@ -154,7 +154,7 @@ public function manipulateArgDefinition( ObjectTypeDefinitionNode &$parentType ): void { if (! $this->hasAllowedColumns() && ! $this->directiveHasArgument('relations')) { - $argDefinition->type = Parser::typeReference('['.OrderByServiceProvider::DEFAULT_ORDER_BY_CLAUSE.'!]'); + $argDefinition->type = Parser::typeReference('[' . OrderByServiceProvider::DEFAULT_ORDER_BY_CLAUSE . '!]'); return; } @@ -173,7 +173,7 @@ public function manipulateArgDefinition( $relationName = $relation['relation']; $relationUpper = ucfirst($relationName); - $inputName = $qualifiedOrderByPrefix.$relationUpper; + $inputName = $qualifiedOrderByPrefix . $relationUpper; $relationsInputs[$relationName] = $inputName; @@ -228,7 +228,7 @@ public function manipulateArgDefinition( $otherOptions = ['column']; foreach ($relationNames as $relationName) { if ($relationName !== $relation) { - $otherOptions [] = $relationName; + $otherOptions[] = $relationName; } } @@ -243,8 +243,8 @@ public function manipulateArgDefinition( $documentAST->setTypeDefinition(Parser::inputObjectTypeDefinition("{$inputMerged}}")); } else { - $restrictedOrderByName = $qualifiedOrderByPrefix.'OrderByClause'; - $argDefinition->type = Parser::typeReference('['.$restrictedOrderByName.'!]'); + $restrictedOrderByName = $qualifiedOrderByPrefix . 'OrderByClause'; + $argDefinition->type = Parser::typeReference('[' . $restrictedOrderByName . '!]'); $documentAST->setTypeDefinition( OrderByServiceProvider::createOrderByClauseInput( diff --git a/src/Pagination/ConnectionField.php b/src/Pagination/ConnectionField.php index edb4a9c360..a2627dac46 100644 --- a/src/Pagination/ConnectionField.php +++ b/src/Pagination/ConnectionField.php @@ -24,10 +24,10 @@ public function pageInfoResolver(LengthAwarePaginator $paginator): array return [ 'hasNextPage' => $paginator->hasMorePages(), 'hasPreviousPage' => $paginator->currentPage() > 1, - 'startCursor' => $firstItem !== null + 'startCursor' => null !== $firstItem ? Cursor::encode($firstItem) : null, - 'endCursor' => $lastItem !== null + 'endCursor' => null !== $lastItem ? Cursor::encode($lastItem) : null, 'total' => $paginator->total(), diff --git a/src/Pagination/PaginationArgs.php b/src/Pagination/PaginationArgs.php index 97b8316723..31bc69f6d6 100644 --- a/src/Pagination/PaginationArgs.php +++ b/src/Pagination/PaginationArgs.php @@ -57,7 +57,7 @@ public static function extractArgs(array $args, PaginationType $paginationType, // Make sure the maximum pagination count is not exceeded if ( - $paginateMaxCount !== null + null !== $paginateMaxCount && $instance->first > $paginateMaxCount ) { throw new Error( diff --git a/src/Pagination/PaginationManipulator.php b/src/Pagination/PaginationManipulator.php index 10757560a4..69d2a5b0f3 100644 --- a/src/Pagination/PaginationManipulator.php +++ b/src/Pagination/PaginationManipulator.php @@ -80,7 +80,7 @@ protected function registerConnection( ): void { $fieldTypeName = ASTHelper::getUnderlyingTypeName($fieldDefinition); - if ($edgeType !== null) { + if (null !== $edgeType) { $connectionEdgeName = $edgeType->name->value; $connectionTypeName = "{$connectionEdgeName}Connection"; } else { @@ -118,10 +118,10 @@ protected function registerConnection( ); $this->documentAST->setTypeDefinition($connectionEdge); - $fieldDefinition->arguments [] = Parser::inputValueDefinition( + $fieldDefinition->arguments[] = Parser::inputValueDefinition( self::countArgument($defaultCount, $maxCount) ); - $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' + $fieldDefinition->arguments[] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' "A cursor after which elements are returned." after: String GRAPHQL @@ -137,7 +137,7 @@ protected function addPaginationWrapperType(ObjectTypeDefinitionNode $objectType // Reuse existing types to preserve directives or other modifications made to it $existingType = $this->documentAST->types[$typeName] ?? null; - if ($existingType !== null) { + if (null !== $existingType) { if (! $existingType instanceof ObjectTypeDefinitionNode) { throw new DefinitionException( "Expected object type for pagination wrapper {$typeName}, found {$objectType->kind} instead." @@ -151,7 +151,7 @@ protected function addPaginationWrapperType(ObjectTypeDefinitionNode $objectType $this->modelClass && ! ASTHelper::hasDirective($objectType, ModelDirective::NAME) ) { - $objectType->directives [] = Parser::constDirective(/** @lang GraphQL */'@model(class: "'.addslashes($this->modelClass).'")'); + $objectType->directives[] = Parser::constDirective(/** @lang GraphQL */ '@model(class: "' . addslashes($this->modelClass) . '")'); } $this->documentAST->setTypeDefinition($objectType); @@ -180,14 +180,14 @@ protected function registerPaginator( ); $this->addPaginationWrapperType($paginatorType); - $fieldDefinition->arguments [] = Parser::inputValueDefinition( + $fieldDefinition->arguments[] = Parser::inputValueDefinition( self::countArgument($defaultCount, $maxCount) ); - $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' + $fieldDefinition->arguments[] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' "The offset from which items are returned." page: Int GRAPHQL -); + ); $fieldDefinition->type = $this->paginationResultType($paginatorTypeName); $parentType->fields = ASTHelper::mergeUniqueNodeList($parentType->fields, [$fieldDefinition], true); @@ -216,10 +216,10 @@ protected function registerSimplePaginator( ); $this->addPaginationWrapperType($paginatorType); - $fieldDefinition->arguments [] = Parser::inputValueDefinition( + $fieldDefinition->arguments[] = Parser::inputValueDefinition( self::countArgument($defaultCount, $maxCount) ); - $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' + $fieldDefinition->arguments[] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' "The offset from which items are returned." page: Int GRAPHQL @@ -236,17 +236,18 @@ protected static function countArgument(?int $defaultCount = null, ?int $maxCoun { $description = '"Limits number of fetched items.'; if ($maxCount) { - $description .= ' Maximum allowed value: '.$maxCount.'.'; + $description .= ' Maximum allowed value: ' . $maxCount . '.'; } $description .= "\"\n"; $definition = 'first: Int' - .($defaultCount - ? ' = '.$defaultCount + . ( + $defaultCount + ? ' = ' . $defaultCount : '!' ); - return $description.$definition; + return $description . $definition; } /** diff --git a/src/Pagination/PaginationType.php b/src/Pagination/PaginationType.php index 3ec7e982e4..da9dc6eb45 100644 --- a/src/Pagination/PaginationType.php +++ b/src/Pagination/PaginationType.php @@ -45,16 +45,16 @@ public function __construct(string $paginationType) public function isPaginator(): bool { - return $this->type === self::PAGINATOR; + return self::PAGINATOR === $this->type; } public function isConnection(): bool { - return $this->type === self::CONNECTION; + return self::CONNECTION === $this->type; } public function isSimple(): bool { - return $this->type === self::SIMPLE; + return self::SIMPLE === $this->type; } } diff --git a/src/Pagination/PaginatorField.php b/src/Pagination/PaginatorField.php index 08843d2730..311679f92e 100644 --- a/src/Pagination/PaginatorField.php +++ b/src/Pagination/PaginatorField.php @@ -11,6 +11,7 @@ class PaginatorField * Resolve paginator info for connection. * * @param \Illuminate\Pagination\LengthAwarePaginator $root + * * @return array */ public function paginatorInfoResolver(LengthAwarePaginator $root): array @@ -31,6 +32,7 @@ public function paginatorInfoResolver(LengthAwarePaginator $root): array * Resolve data for connection. * * @param \Illuminate\Pagination\LengthAwarePaginator $root + * * @return \Illuminate\Support\Collection */ public function dataResolver(LengthAwarePaginator $root): Collection diff --git a/src/Pagination/SimplePaginatorField.php b/src/Pagination/SimplePaginatorField.php index 9f5d4202a5..bbe4ac7546 100644 --- a/src/Pagination/SimplePaginatorField.php +++ b/src/Pagination/SimplePaginatorField.php @@ -11,6 +11,7 @@ class SimplePaginatorField * Resolve simple paginator info for connection. * * @param \Illuminate\Pagination\Paginator $root + * * @return array */ public function paginatorInfoResolver(Paginator $root): array @@ -28,6 +29,7 @@ public function paginatorInfoResolver(Paginator $root): array * Resolve data for connection. * * @param \Illuminate\Pagination\Paginator $root + * * @return \Illuminate\Support\Collection */ public function dataResolver(Paginator $root): Collection diff --git a/src/Schema/AST/ASTBuilder.php b/src/Schema/AST/ASTBuilder.php index 2cb4f5c037..3c7fea9b5e 100644 --- a/src/Schema/AST/ASTBuilder.php +++ b/src/Schema/AST/ASTBuilder.php @@ -176,7 +176,7 @@ protected function extendObjectLikeType(string $typeName, TypeExtensionNode $typ { /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InputObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode|null $extendedObjectLikeType */ $extendedObjectLikeType = $this->documentAST->types[$typeName] ?? null; - if ($extendedObjectLikeType === null) { + if (null === $extendedObjectLikeType) { if (RootType::isRootType($typeName)) { $extendedObjectLikeType = Parser::objectTypeDefinition(/** @lang GraphQL */ "type {$typeName}"); $this->documentAST->setTypeDefinition($extendedObjectLikeType); @@ -214,7 +214,7 @@ protected function extendEnumType(string $typeName, EnumTypeExtensionNode $typeE { /** @var \GraphQL\Language\AST\EnumTypeDefinitionNode|null $extendedEnum */ $extendedEnum = $this->documentAST->types[$typeName] ?? null; - if ($extendedEnum === null) { + if (null === $extendedEnum) { throw new DefinitionException( $this->missingBaseDefinition($typeName, $typeExtension) ); diff --git a/src/Schema/AST/ASTCache.php b/src/Schema/AST/ASTCache.php index 19cdb89801..dc0527386a 100644 --- a/src/Schema/AST/ASTCache.php +++ b/src/Schema/AST/ASTCache.php @@ -83,7 +83,7 @@ public function isEnabled(): bool public function set(DocumentAST $documentAST): void { - if ($this->version === 1) { + if (1 === $this->version) { $this->store()->set($this->key, $documentAST, $this->ttl); return; @@ -95,7 +95,7 @@ public function set(DocumentAST $documentAST): void public function clear(): void { - if ($this->version === 1) { + if (1 === $this->version) { $this->store()->forget($this->key); return; @@ -109,7 +109,7 @@ public function clear(): void */ public function fromCacheOrBuild(Closure $build): DocumentAST { - if ($this->version === 1) { + if (1 === $this->version) { return $this->store()->remember( $this->key, $this->ttl, diff --git a/src/Schema/AST/ASTHelper.php b/src/Schema/AST/ASTHelper.php index ec4fee422e..facf1dd996 100644 --- a/src/Schema/AST/ASTHelper.php +++ b/src/Schema/AST/ASTHelper.php @@ -42,6 +42,7 @@ class ASTHelper * @param \GraphQL\Language\AST\NodeList|array $addition * @param bool $overwriteDuplicates By default this function throws if a collision occurs. * If set to true, the fields of the original list will be overwritten. + * * @return \GraphQL\Language\AST\NodeList */ public static function mergeUniqueNodeList($original, $addition, bool $overwriteDuplicates = false): NodeList @@ -82,6 +83,7 @@ public static function mergeUniqueNodeList($original, $addition, bool $overwrite * * @param \GraphQL\Language\AST\NodeList $nodeList * @param TNode $node + * * @return \GraphQL\Language\AST\NodeList */ public static function prepend(NodeList $nodeList, Node $node): NodeList @@ -132,15 +134,16 @@ public static function getUnderlyingNamedTypeNode(Node $node): NamedTypeNode /** * Extract a named argument from a given directive node. * - * @param mixed $default Is returned if the directive does not have the argument. - * @return mixed The value given to the directive. + * @param mixed $default is returned if the directive does not have the argument + * + * @return mixed the value given to the directive */ public static function directiveArgValue(DirectiveNode $directive, string $name, $default = null) { /** @var \GraphQL\Language\AST\ArgumentNode|null $arg */ $arg = self::firstByName($directive->arguments, $name); - return $arg !== null + return null !== $arg ? AST::valueFromASTUntyped($arg->value) : $default; } @@ -150,7 +153,8 @@ public static function directiveArgValue(DirectiveNode $directive, string $name, * * @param \GraphQL\Language\AST\ValueNode&\GraphQL\Language\AST\Node $defaultValue * @param \GraphQL\Type\Definition\Type&\GraphQL\Type\Definition\InputType $argumentType - * @return mixed The plain PHP value. + * + * @return mixed the plain PHP value */ public static function defaultValueForArgument(ValueNode $defaultValue, Type $argumentType) { @@ -177,7 +181,7 @@ public static function defaultValueForArgument(ValueNode $defaultValue, Type $ar public static function directiveDefinition(Node $definitionNode, string $name): ?DirectiveNode { if (! property_exists($definitionNode, 'directives')) { - throw new Exception('Expected Node class with property `directives`, got: '.get_class($definitionNode)); + throw new Exception('Expected Node class with property `directives`, got: ' . get_class($definitionNode)); } /** @var \GraphQL\Language\AST\NodeList<\GraphQL\Language\AST\DirectiveNode> $directives */ $directives = $definitionNode->directives; @@ -190,7 +194,7 @@ public static function directiveDefinition(Node $definitionNode, string $name): */ public static function hasDirective(Node $definitionNode, string $name): bool { - return self::directiveDefinition($definitionNode, $name) !== null; + return null !== self::directiveDefinition($definitionNode, $name); } /** @@ -199,13 +203,14 @@ public static function hasDirective(Node $definitionNode, string $name): bool * @template TNode of \GraphQL\Language\AST\Node * * @param iterable $nodes + * * @return TNode|null */ public static function firstByName($nodes, string $name): ?Node { foreach ($nodes as $node) { if (! property_exists($node, 'name')) { - throw new Exception('Expected a Node with a name property, got: '.get_class($node)); + throw new Exception('Expected a Node with a name property, got: ' . get_class($node)); } if ($node->name->value === $name) { @@ -224,7 +229,7 @@ public static function namespaceForDirective(Node $definitionNode, string $direc { $namespaceDirective = static::directiveDefinition($definitionNode, NamespaceDirective::NAME); - return $namespaceDirective !== null + return null !== $namespaceDirective ? static::directiveArgValue($namespaceDirective, $directiveName) : null; } @@ -250,7 +255,7 @@ public static function attachDirectiveToObjectTypeFields(DocumentAST $documentAS */ public static function typeImplementsInterface(ObjectTypeDefinitionNode $type, string $interfaceName): bool { - return self::firstByName($type->interfaces, $interfaceName) !== null; + return null !== self::firstByName($type->interfaces, $interfaceName); } /** @@ -308,14 +313,15 @@ public static function qualifiedArgType( ObjectTypeDefinitionNode &$parentType ): string { return Str::studly($parentType->name->value) - .Str::studly($parentField->name->value) - .Str::studly($argDefinition->name->value); + . Str::studly($parentField->name->value) + . Str::studly($argDefinition->name->value); } /** * Given a collection of directives, returns the string value for the deprecation reason. * * @param \GraphQL\Language\AST\EnumValueDefinitionNode|\GraphQL\Language\AST\FieldDefinitionNode $node + * * @return string */ public static function deprecationReason(Node $node): ?string @@ -347,7 +353,7 @@ public static function extractDirectiveDefinition(string $definitionString): Dir $directive = null; foreach ($document->definitions as $definitionNode) { if ($definitionNode instanceof DirectiveDefinitionNode) { - if ($directive !== null) { + if (null !== $directive) { throw new DefinitionException( "Found multiple directives while trying to extract a single directive from this definition:\n\n{$definitionString}" ); @@ -357,7 +363,7 @@ public static function extractDirectiveDefinition(string $definitionString): Dir } } - if ($directive === null) { + if (null === $directive) { throw new DefinitionException( "Found no directive while trying to extract a single directive from this definition:\n\n{$definitionString}" ); @@ -378,7 +384,7 @@ public static function underlyingType(FieldDefinitionNode $field): Node $documentAST = $astBuilder->documentAST(); $type = $documentAST->types[$typeName] ?? null; - if ($type === null) { + if (null === $type) { throw new DefinitionException( "Type '$typeName' on '{$field->name->value}' can not be found in the schema.'" ); diff --git a/src/Schema/AST/DocumentAST.php b/src/Schema/AST/DocumentAST.php index d206af6bbe..1a8dd4f9a5 100644 --- a/src/Schema/AST/DocumentAST.php +++ b/src/Schema/AST/DocumentAST.php @@ -28,9 +28,9 @@ */ class DocumentAST implements Serializable, Arrayable { - const TYPES = 'types'; - const DIRECTIVES = 'directives'; - const CLASS_NAME_TO_OBJECT_TYPE_NAME = 'classNameToObjectTypeName'; + public const TYPES = 'types'; + public const DIRECTIVES = 'directives'; + public const CLASS_NAME_TO_OBJECT_TYPE_NAME = 'classNameToObjectTypeName'; /** * The types within the schema. @@ -90,7 +90,7 @@ public static function fromSource(string $schema): self throw new ParseException($syntaxError); } - $instance = new static; + $instance = new static(); foreach ($documentNode->definitions as $definition) { if ($definition instanceof TypeDefinitionNode) { @@ -128,11 +128,11 @@ static function (string $classCandidate): bool { } } elseif ($definition instanceof TypeExtensionNode) { // Multiple type extensions for the same name can exist - $instance->typeExtensions[$definition->name->value] [] = $definition; + $instance->typeExtensions[$definition->name->value][] = $definition; } elseif ($definition instanceof DirectiveDefinitionNode) { $instance->directives[$definition->name->value] = $definition; } else { - throw new Exception('Unknown definition type: '.get_class($definition)); + throw new Exception('Unknown definition type: ' . get_class($definition)); } } @@ -145,6 +145,7 @@ static function (string $classCandidate): bool { * This operation will overwrite existing definitions with the same name. * * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $type + * * @return $this */ public function setTypeDefinition(TypeDefinitionNode $type): self diff --git a/src/Schema/AST/TypeNodeConverter.php b/src/Schema/AST/TypeNodeConverter.php index e81490b56a..cb726df159 100644 --- a/src/Schema/AST/TypeNodeConverter.php +++ b/src/Schema/AST/TypeNodeConverter.php @@ -12,7 +12,8 @@ abstract class TypeNodeConverter * Convert an AST type to an executable type. * * @param \GraphQL\Language\AST\TypeNode&\GraphQL\Language\AST\Node $node - * @return mixed The executable type. + * + * @return mixed the executable type */ public function convert(TypeNode $node) { @@ -24,7 +25,8 @@ public function convert(TypeNode $node) * * @param \GraphQL\Language\AST\TypeNode&\GraphQL\Language\AST\Node $node * @param array $wrappers - * @return mixed The wrapped type. + * + * @return mixed the wrapped type */ protected function convertWrappedTypeNode(TypeNode $node, array $wrappers = []) { @@ -46,11 +48,11 @@ protected function convertWrappedTypeNode(TypeNode $node, array $wrappers = []) ->reverse() ->reduce( function ($type, string $kind) { - if ($kind === NodeKind::NON_NULL_TYPE) { + if (NodeKind::NON_NULL_TYPE === $kind) { return $this->nonNull($type); } - if ($kind === NodeKind::LIST_TYPE) { + if (NodeKind::LIST_TYPE === $kind) { return $this->listOf($type); } @@ -63,23 +65,25 @@ function ($type, string $kind) { /** * Wrap or mark the type as non-null. * - * @param mixed $type The type to wrap. - * @return mixed The type wrapped with non-null. + * @param mixed $type the type to wrap + * + * @return mixed the type wrapped with non-null */ abstract protected function nonNull($type); /** * Wrap or mark the type as a list. * - * @param mixed $type The type to wrap. - * @return mixed The type wrapped as a list. + * @param mixed $type the type to wrap + * + * @return mixed the type wrapped as a list */ abstract protected function listOf($type); /** * Get the named type for the given node name. * - * @return mixed Representation of the type with the given name. + * @return mixed representation of the type with the given name */ abstract protected function namedType(string $nodeName); } diff --git a/src/Schema/DirectiveLocator.php b/src/Schema/DirectiveLocator.php index 3eb9197604..26025192c0 100644 --- a/src/Schema/DirectiveLocator.php +++ b/src/Schema/DirectiveLocator.php @@ -60,15 +60,15 @@ public function __construct(EventsDispatcher $eventsDispatcher) */ public function namespaces(): array { - if ($this->directiveNamespaces === null) { - $this->directiveNamespaces = + if (null === $this->directiveNamespaces) { + $this->directiveNamespaces // When looking for a directive by name, the namespaces are tried in order - (new Collection([ + = (new Collection([ // User defined directives (top priority) config('lighthouse.namespaces.directives'), // Plugin developers defined directives - $this->eventsDispatcher->dispatch(new RegisterDirectiveNamespaces), + $this->eventsDispatcher->dispatch(new RegisterDirectiveNamespaces()), // Lighthouse defined directives 'Nuwave\\Lighthouse\\Schema\\Directives', @@ -127,7 +127,7 @@ public function definitions(): array $definitions = []; foreach ($this->classes() as $directiveClass) { - $definitions [] = ASTHelper::extractDirectiveDefinition($directiveClass::definition()); + $definitions[] = ASTHelper::extractDirectiveDefinition($directiveClass::definition()); } return $definitions; @@ -146,9 +146,9 @@ public function create(string $directiveName): Directive /** * Resolve the class for a given directive name. * - * @return class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> - * * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * + * @return class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> */ public function resolve(string $directiveName): string { @@ -158,11 +158,11 @@ public function resolve(string $directiveName): string } foreach ($this->namespaces() as $baseNamespace) { - $directiveClass = $baseNamespace.'\\'.static::className($directiveName); + $directiveClass = $baseNamespace . '\\' . static::className($directiveName); if (class_exists($directiveClass)) { if (! is_a($directiveClass, Directive::class, true)) { - throw new DirectiveException("Class $directiveClass must implement the interface ".Directive::class); + throw new DirectiveException("Class $directiveClass must implement the interface " . Directive::class); } $this->resolvedClassnames[$directiveName] = $directiveClass; @@ -178,7 +178,7 @@ public function resolve(string $directiveName): string */ protected static function className(string $directiveName): string { - return Str::studly($directiveName).'Directive'; + return Str::studly($directiveName) . 'Directive'; } /** @@ -211,7 +211,7 @@ public function setResolved(string $directiveName, string $directiveClass): self public function associated(Node $node): Collection { if (! property_exists($node, 'directives')) { - throw new Exception('Expected Node class with property `directives`, got: '.get_class($node)); + throw new Exception('Expected Node class with property `directives`, got: ' . get_class($node)); } return (new Collection($node->directives)) @@ -233,6 +233,7 @@ public function associated(Node $node): Collection * @template TDirective of \Nuwave\Lighthouse\Support\Contracts\Directive * * @param class-string $directiveClass + * * @return \Illuminate\Support\Collection */ public function associatedOfType(Node $node, string $directiveClass): Collection @@ -258,9 +259,10 @@ public function associatedOfType(Node $node, string $directiveClass): Collection * @template TDirective of \Nuwave\Lighthouse\Support\Contracts\Directive * * @param class-string $directiveClass - * @return TDirective|null * * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * + * @return TDirective|null */ public function exclusiveOfType(Node $node, string $directiveClass): ?Directive { @@ -273,12 +275,12 @@ public function exclusiveOfType(Node $node, string $directiveClass): ?Directive $directive::definition() ); - return '@'.$definition->name->value; + return '@' . $definition->name->value; }) ->implode(', '); if (! property_exists($node, 'name')) { - throw new Exception('Expected Node class with property `name`, got: '.get_class($node)); + throw new Exception('Expected Node class with property `name`, got: ' . get_class($node)); } throw new DirectiveException( diff --git a/src/Schema/Directives/ArgTraversalDirective.php b/src/Schema/Directives/ArgTraversalDirective.php index fde5a6b62a..92b3a97bff 100644 --- a/src/Schema/Directives/ArgTraversalDirective.php +++ b/src/Schema/Directives/ArgTraversalDirective.php @@ -54,9 +54,9 @@ function ($value) use ($directivesForArgument) { $value = $this->transform($value, $directivesForArgument); return $this->transformRecursively($value); - } else { - return $this->transform($value, $directivesForArgument); } + + return $this->transform($value, $directivesForArgument); }, $argument->value ); @@ -67,6 +67,7 @@ function ($value) use ($directivesForArgument) { /** * @param mixed $value The client given value + * * @return mixed The transformed value */ protected function transform($value, Collection $directivesForArgument) @@ -80,6 +81,7 @@ protected function transform($value, Collection $directivesForArgument) /** * @param mixed $value The client given value + * * @return mixed The transformed value */ abstract protected function applyDirective(Directive $directive, $value); diff --git a/src/Schema/Directives/BaseDirective.php b/src/Schema/Directives/BaseDirective.php index 9e6b7293f3..4a3101762f 100644 --- a/src/Schema/Directives/BaseDirective.php +++ b/src/Schema/Directives/BaseDirective.php @@ -115,6 +115,7 @@ public function directiveHasArgument(string $name): bool * Get the value of an argument on the directive. * * @param mixed|null $default + * * @return mixed|null */ protected function directiveArgValue(string $name, $default = null) @@ -140,9 +141,10 @@ protected function nodeName(): string * Get the model class from the `model` argument of the field. * * @param string $argumentName The default argument name "model" may be overwritten - * @return class-string<\Illuminate\Database\Eloquent\Model> * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return class-string<\Illuminate\Database\Eloquent\Model> */ protected function getModelClass(string $argumentName = 'model'): string { @@ -163,9 +165,10 @@ protected function getModelClass(string $argumentName = 'model'): string * * @param array $namespacesToTry * @param callable(string $className): bool $determineMatch - * @return class-string * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return class-string */ protected function namespaceClassName( string $classCandidate, @@ -209,9 +212,9 @@ protected function namespaceClassName( * e.g. "App\My\Class@methodName" * This validates that exactly two parts are given and are not empty. * - * @return array{0: string, 1: string} Contains two entries: [string $className, string $methodName] - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return array{0: string, 1: string} Contains two entries: [string $className, string $methodName] */ protected function getMethodArgumentParts(string $argumentName): array { diff --git a/src/Schema/Directives/CacheDirective.php b/src/Schema/Directives/CacheDirective.php index c6ffdac433..301ef35317 100644 --- a/src/Schema/Directives/CacheDirective.php +++ b/src/Schema/Directives/CacheDirective.php @@ -88,7 +88,7 @@ function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) // We found a matching value in the cache, so we can just return early // without actually running the query $value = $cache->get($cacheKey); - if ($value !== null) { + if (null !== $value) { return $value; } // In Laravel cache, null is considered as "non-existant" value. As mentioned in laravel documentation, @@ -128,7 +128,8 @@ function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) Resolved::handle($resolved, $storeInCache); return $resolved; - }); + } + ); return $fieldValue; } @@ -153,7 +154,7 @@ protected function setCacheKeyOnParent(TypeValue $typeValue): void // The cache key was already set, so we do not have to look again $typeValue->getCacheKey() // The Query type is exempt from requiring a cache key - || $typeValue->getTypeDefinitionName() === RootType::QUERY + || RootType::QUERY === $typeValue->getTypeDefinitionName() ) { return; } @@ -178,7 +179,7 @@ protected function setCacheKeyOnParent(TypeValue $typeValue): void if ( $field->type instanceof NonNullTypeNode && $field->type->type instanceof NamedTypeNode - && $field->type->type->name->value === 'ID' + && 'ID' === $field->type->type->name->value ) { $typeValue->setCacheKey($field->name->value); diff --git a/src/Schema/Directives/ComplexityDirective.php b/src/Schema/Directives/ComplexityDirective.php index 12e45cbf53..6f87bb762e 100644 --- a/src/Schema/Directives/ComplexityDirective.php +++ b/src/Schema/Directives/ComplexityDirective.php @@ -38,9 +38,9 @@ public function complexityResolver(FieldValue $fieldValue): callable ); return Utils::constructResolver($namespacedClassName, $methodName); - } else { - return [static::class, 'defaultComplexityResolver']; } + + return [static::class, 'defaultComplexityResolver']; } /** diff --git a/src/Schema/Directives/LazyLoadDirective.php b/src/Schema/Directives/LazyLoadDirective.php index 3ef7e3b7bc..a4124952c4 100644 --- a/src/Schema/Directives/LazyLoadDirective.php +++ b/src/Schema/Directives/LazyLoadDirective.php @@ -38,6 +38,7 @@ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue $fieldValue->resultHandler( /** * @param Collection|LengthAwarePaginator $items + * * @return Collection|LengthAwarePaginator */ static function ($items) use ($relations) { @@ -53,7 +54,7 @@ static function ($items) use ($relations) { public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType) { $relations = $this->directiveArgValue('relations'); - if (! is_array($relations) || count($relations) === 0) { + if (! is_array($relations) || 0 === count($relations)) { throw new DefinitionException( "Must specify non-empty list of relations in `@{$this->name()}` directive on `{$parentType->name->value}.{$fieldDefinition->name->value}`." ); diff --git a/src/Schema/Directives/LikeDirective.php b/src/Schema/Directives/LikeDirective.php index 57c7deb23c..efa30f6815 100644 --- a/src/Schema/Directives/LikeDirective.php +++ b/src/Schema/Directives/LikeDirective.php @@ -7,10 +7,10 @@ class LikeDirective extends BaseDirective implements ArgBuilderDirective, FieldBuilderDirective { - const ESCAPE = '\\'; - const PERCENTAGE = '%'; - const UNDERSCORE = '_'; - const PLACEHOLDER = '{}'; + public const ESCAPE = '\\'; + public const PERCENTAGE = '%'; + public const UNDERSCORE = '_'; + public const PLACEHOLDER = '{}'; public static function definition(): string { @@ -49,7 +49,7 @@ public static function definition(): string */ public function handleBuilder($builder, $value): object { - if ($value === null) { + if (null === $value) { return $builder; } @@ -86,7 +86,7 @@ protected function escapeWildcards(string $value): string { return str_replace( [self::ESCAPE, self::PERCENTAGE, self::UNDERSCORE], - [self::ESCAPE.self::ESCAPE, self::ESCAPE.self::PERCENTAGE, self::ESCAPE.self::UNDERSCORE], + [self::ESCAPE . self::ESCAPE, self::ESCAPE . self::PERCENTAGE, self::ESCAPE . self::UNDERSCORE], $value ); } diff --git a/src/Schema/Directives/LimitDirective.php b/src/Schema/Directives/LimitDirective.php index 148576b36b..a2a5198552 100644 --- a/src/Schema/Directives/LimitDirective.php +++ b/src/Schema/Directives/LimitDirective.php @@ -37,20 +37,20 @@ public function manipulateArgDefinition( ObjectTypeDefinitionNode &$parentType ): void { $argType = ASTHelper::getUnderlyingTypeName($argDefinition->type); - if ($argType !== Type::INT) { + if (Type::INT !== $argType) { throw new DefinitionException( - "The {$this->name()} directive must only be used on arguments of type ".Type::INT - .", got {$argType} on {$parentField->name->value}.{$this->nodeName()}." + "The {$this->name()} directive must only be used on arguments of type " . Type::INT + . ", got {$argType} on {$parentField->name->value}.{$this->nodeName()}." ); } - $parentField->directives [] = $this->directiveNode; + $parentField->directives[] = $this->directiveNode; } public function handleField(FieldValue $fieldValue, Closure $next) { $fieldValue->resultHandler(static function (?iterable $result, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): ?iterable { - if ($result === null) { + if (null === $result) { return null; } @@ -74,12 +74,12 @@ public function handleField(FieldValue $fieldValue, Closure $next) $limited = []; foreach ($result as $value) { - if ($limit === 0) { + if (0 === $limit) { break; } - $limit--; + --$limit; - $limited [] = $value; + $limited[] = $value; } return $limited; diff --git a/src/Schema/Directives/MethodDirective.php b/src/Schema/Directives/MethodDirective.php index 54a4df958f..3590ff809a 100644 --- a/src/Schema/Directives/MethodDirective.php +++ b/src/Schema/Directives/MethodDirective.php @@ -34,6 +34,7 @@ public function resolveField(FieldValue $fieldValue): FieldValue return $fieldValue->setResolver( /** * @param array $args + * * @return mixed Really anything */ function ($root, array $args) { @@ -45,7 +46,7 @@ function ($root, array $args) { $orderedArgs = []; foreach ($this->definitionNode->arguments as $argDefinition) { - $orderedArgs [] = $args[$argDefinition->name->value] ?? null; + $orderedArgs[] = $args[$argDefinition->name->value] ?? null; } return $root->{$method}(...$orderedArgs); diff --git a/src/Schema/Directives/ModelDirective.php b/src/Schema/Directives/ModelDirective.php index 37af1ade1c..dc4fe5360d 100644 --- a/src/Schema/Directives/ModelDirective.php +++ b/src/Schema/Directives/ModelDirective.php @@ -7,7 +7,7 @@ class ModelDirective extends BaseDirective { - const NAME = 'model'; + public const NAME = 'model'; public static function definition(): string { @@ -32,7 +32,7 @@ class: String! public static function modelClass(Node $node): ?string { $modelDirective = ASTHelper::directiveDefinition($node, self::NAME); - if ($modelDirective !== null) { + if (null !== $modelDirective) { return ASTHelper::directiveArgValue($modelDirective, 'class'); } diff --git a/src/Schema/Directives/ModifyModelExistenceDirective.php b/src/Schema/Directives/ModifyModelExistenceDirective.php index cc084a891e..bc815e8347 100644 --- a/src/Schema/Directives/ModifyModelExistenceDirective.php +++ b/src/Schema/Directives/ModifyModelExistenceDirective.php @@ -37,7 +37,7 @@ public function __construct(GlobalId $globalId, ErrorPool $errorPool) public static function couldNotModify(Model $user): string { - return 'Could not modify model '.get_class($user).' with ID '.$user->getKey().'.'; + return 'Could not modify model ' . get_class($user) . ' with ID ' . $user->getKey() . '.'; } public function resolveField(FieldValue $fieldValue): FieldValue @@ -58,7 +58,7 @@ function ($root, array $args) { $idOrIds ); - if ($modelOrModels === null) { + if (null === $modelOrModels) { return null; } @@ -110,21 +110,22 @@ public function manipulateFieldDefinition( ObjectTypeDefinitionNode &$parentType ): void { // Ensure there is only a single argument defined on the field. - if (count($fieldDefinition->arguments) !== 1) { + if (1 !== count($fieldDefinition->arguments)) { throw new DefinitionException( - 'The @'.$this->name()." directive requires the field {$this->nodeName()} to only contain a single argument." + 'The @' . $this->name() . " directive requires the field {$this->nodeName()} to only contain a single argument." ); } if (! $this->idArgument() instanceof NonNullTypeNode) { throw new DefinitionException( - 'The @'.$this->name()." directive requires the field {$this->nodeName()} to have a NonNull argument. Mark it with !" + 'The @' . $this->name() . " directive requires the field {$this->nodeName()} to have a NonNull argument. Mark it with !" ); } } /** * @param string|array $idOrIds + * * @return string|array */ protected function decodeIdOrIds($idOrIds) @@ -149,6 +150,7 @@ function (string $id): string { * * @param class-string<\Illuminate\Database\Eloquent\Model> $modelClass * @param string|int|array|array $idOrIds + * * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model>|null */ abstract protected function find(string $modelClass, $idOrIds); diff --git a/src/Schema/Directives/MutationExecutorDirective.php b/src/Schema/Directives/MutationExecutorDirective.php index 434aea6e13..d2c86556ba 100644 --- a/src/Schema/Directives/MutationExecutorDirective.php +++ b/src/Schema/Directives/MutationExecutorDirective.php @@ -31,7 +31,7 @@ public function resolveField(FieldValue $fieldValue): FieldValue return $fieldValue->setResolver( function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Model { $modelClass = $this->getModelClass(); - $model = new $modelClass; + $model = new $modelClass(); $executeMutation = function () use ($model, $resolveInfo): Model { /** @var \Illuminate\Database\Eloquent\Model $mutated */ @@ -58,6 +58,7 @@ function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) /** * @param \Illuminate\Database\Eloquent\Model $parent * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args + * * @return \Illuminate\Database\Eloquent\Model|array<\Illuminate\Database\Eloquent\Model> */ public function __invoke($parent, $args) @@ -78,6 +79,7 @@ public function __invoke($parent, $args) /** * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args + * * @return \Illuminate\Database\Eloquent\Model|array<\Illuminate\Database\Eloquent\Model> */ protected function executeMutation(Model $model, $args, ?Relation $parentRelation = null) diff --git a/src/Schema/Directives/NamespaceDirective.php b/src/Schema/Directives/NamespaceDirective.php index 31bfe19e17..b21ebf6cd6 100644 --- a/src/Schema/Directives/NamespaceDirective.php +++ b/src/Schema/Directives/NamespaceDirective.php @@ -43,11 +43,11 @@ protected function addNamespacesToFields(&$objectType): void foreach ($objectType->fields as $fieldDefinition) { $existingNamespaces = ASTHelper::directiveDefinition($fieldDefinition, self::NAME); - if ($existingNamespaces !== null) { + if (null !== $existingNamespaces) { $namespaceDirective->arguments = $namespaceDirective->arguments->merge($existingNamespaces->arguments); } - $fieldDefinition->directives [] = $namespaceDirective; + $fieldDefinition->directives[] = $namespaceDirective; } } diff --git a/src/Schema/Directives/NestDirective.php b/src/Schema/Directives/NestDirective.php index 49ea8c0713..866e8d7b08 100644 --- a/src/Schema/Directives/NestDirective.php +++ b/src/Schema/Directives/NestDirective.php @@ -23,8 +23,8 @@ public static function definition(): string /** * Delegate to nested arg resolvers. * - * @param mixed $root The result of the parent resolver. - * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args The slice of arguments that belongs to this nested resolver. + * @param mixed $root the result of the parent resolver + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args the slice of arguments that belongs to this nested resolver */ public function __invoke($root, $args) { diff --git a/src/Schema/Directives/RelationDirective.php b/src/Schema/Directives/RelationDirective.php index 5b04a48811..a453b5d78d 100644 --- a/src/Schema/Directives/RelationDirective.php +++ b/src/Schema/Directives/RelationDirective.php @@ -44,7 +44,7 @@ function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $reso $relationBatchLoader = BatchLoaderRegistry::instance( $this->qualifyPath($args, $resolveInfo), function () use ($relationName, $decorateBuilder, $paginationArgs): RelationBatchLoader { - $modelsLoader = $paginationArgs !== null + $modelsLoader = null !== $paginationArgs ? new PaginatedModelsLoader($relationName, $decorateBuilder, $paginationArgs) : new SimpleModelsLoader($relationName, $decorateBuilder); @@ -57,7 +57,7 @@ function () use ($relationName, $decorateBuilder, $paginationArgs): RelationBatc $decorateBuilder($relation); - return $paginationArgs !== null + return null !== $paginationArgs ? $paginationArgs->applyToBuilder($relation) : $relation->getResults(); } @@ -75,7 +75,7 @@ public function manipulateFieldDefinition( // We default to not changing the field if no pagination type is set explicitly. // This makes sense for relations, as there should not be too many entries. - if ($paginationType === null) { + if (null === $paginationType) { return; } @@ -116,7 +116,7 @@ protected function paginationArgs(array $args): ?PaginationArgs { $paginationType = $this->paginationType(); - return $paginationType !== null + return null !== $paginationType ? PaginationArgs::extractArgs($args, $paginationType, $this->paginationMaxCount()) : null; } @@ -125,7 +125,7 @@ protected function paginationType(): ?PaginationType { $type = $this->directiveArgValue('type'); - return $type !== null + return null !== $type ? new PaginationType($type) : null; } diff --git a/src/Schema/Directives/RelationDirectiveHelpers.php b/src/Schema/Directives/RelationDirectiveHelpers.php index 3c515856f1..58abb90285 100644 --- a/src/Schema/Directives/RelationDirectiveHelpers.php +++ b/src/Schema/Directives/RelationDirectiveHelpers.php @@ -46,6 +46,7 @@ protected function makeBuilderDecorator(ResolveInfo $resolveInfo): Closure /** * @param array $args + * * @return array */ protected function qualifyPath(array $args, ResolveInfo $resolveInfo): array @@ -54,12 +55,12 @@ protected function qualifyPath(array $args, ResolveInfo $resolveInfo): array $path = $resolveInfo->path; // In case we have no args, we can combine eager loads that are the same - if ($args === []) { + if ([] === $args) { array_pop($path); } // Each relation must be loaded separately - $path [] = $this->relation(); + $path[] = $this->relation(); // Scopes influence the result of the query return array_merge($path, $this->scopes()); diff --git a/src/Schema/Directives/ScopeDirective.php b/src/Schema/Directives/ScopeDirective.php index a99bb194a8..18c4466ccc 100644 --- a/src/Schema/Directives/ScopeDirective.php +++ b/src/Schema/Directives/ScopeDirective.php @@ -39,7 +39,7 @@ public function handleBuilder($builder, $value): object // @phpstan-ignore-next-line PHPStan thinks this exception does not occur - but it does. Magic. } catch (BadMethodCallException $exception) { throw new DefinitionException( - $exception->getMessage()." in @{$this->name()} directive on {$this->nodeName()} argument.", + $exception->getMessage() . " in @{$this->name()} directive on {$this->nodeName()} argument.", $exception->getCode(), $exception->getPrevious() ); diff --git a/src/Schema/Directives/ThrottleDirective.php b/src/Schema/Directives/ThrottleDirective.php index bf8118f330..4fa9e0c694 100644 --- a/src/Schema/Directives/ThrottleDirective.php +++ b/src/Schema/Directives/ThrottleDirective.php @@ -75,7 +75,7 @@ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue $limits = []; $name = $this->directiveArgValue('name'); - if ($name !== null) { + if (null !== $name) { // @phpstan-ignore-next-line won't be executed on Laravel < 8 $limiter = $this->limiter->limiter($name); @@ -90,20 +90,20 @@ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue if ($limiterResponse instanceof Response) { throw new DirectiveException( - "Expected named limiter {$name} to return an array, got instance of ".get_class($limiterResponse) + "Expected named limiter {$name} to return an array, got instance of " . get_class($limiterResponse) ); } foreach (Arr::wrap($limiterResponse) as $limit) { $limits[] = [ - 'key' => sha1($name.$limit->key), + 'key' => sha1($name . $limit->key), 'maxAttempts' => $limit->maxAttempts, 'decayMinutes' => $limit->decayMinutes, ]; } } else { $limits[] = [ - 'key' => sha1($this->directiveArgValue('prefix', '').$this->request->ip()), + 'key' => sha1($this->directiveArgValue('prefix', '') . $this->request->ip()), 'maxAttempts' => $this->directiveArgValue('maxAttempts') ?? 60, 'decayMinutes' => $this->directiveArgValue('decayMinutes') ?? 1.0, ]; @@ -131,7 +131,7 @@ function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType): void { $name = $this->directiveArgValue('name'); - if ($name !== null) { + if (null !== $name) { if (AppVersion::below(8.0)) { throw new DefinitionException('Named limiter requires Laravel 8.x or later'); } diff --git a/src/Schema/Directives/TrimDirective.php b/src/Schema/Directives/TrimDirective.php index 5e42979822..c7203158b2 100644 --- a/src/Schema/Directives/TrimDirective.php +++ b/src/Schema/Directives/TrimDirective.php @@ -74,6 +74,7 @@ protected function transformArgumentSet(ArgumentSet $argumentSet): ArgumentSet /** * @param mixed $value The client given value + * * @return mixed The transformed value */ protected function transformLeaf($value) diff --git a/src/Schema/Factories/ArgumentFactory.php b/src/Schema/Factories/ArgumentFactory.php index f2858aa196..7b0867eac5 100644 --- a/src/Schema/Factories/ArgumentFactory.php +++ b/src/Schema/Factories/ArgumentFactory.php @@ -12,6 +12,7 @@ class ArgumentFactory * Convert input value definitions to a executable types. * * @param iterable<\GraphQL\Language\AST\InputValueDefinitionNode> $definitionNodes + * * @return array> */ public function toTypeMap(iterable $definitionNodes): array diff --git a/src/Schema/Factories/DirectiveFactory.php b/src/Schema/Factories/DirectiveFactory.php index 6c6bdadca1..f92b2ecbd1 100644 --- a/src/Schema/Factories/DirectiveFactory.php +++ b/src/Schema/Factories/DirectiveFactory.php @@ -42,7 +42,7 @@ public function handle(DirectiveDefinitionNode $directive): Directive ]; } - $arguments [] = new FieldArgument($fieldArgumentConfig); + $arguments[] = new FieldArgument($fieldArgumentConfig); } $locations = []; diff --git a/src/Schema/Factories/FieldFactory.php b/src/Schema/Factories/FieldFactory.php index 7316992f44..ed5538e5dd 100644 --- a/src/Schema/Factories/FieldFactory.php +++ b/src/Schema/Factories/FieldFactory.php @@ -137,7 +137,7 @@ protected function complexity(FieldValue $fieldValue): ?callable ComplexityResolverDirective::class ); - if ($complexityDirective === null) { + if (null === $complexityDirective) { return null; } @@ -146,16 +146,15 @@ protected function complexity(FieldValue $fieldValue): ?callable public static function defaultResolver(FieldValue $fieldValue): callable { - if ($fieldValue->getParentName() === RootType::SUBSCRIPTION) { + if (RootType::SUBSCRIPTION === $fieldValue->getParentName()) { /** @var \Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver $providesSubscriptionResolver */ $providesSubscriptionResolver = app(ProvidesSubscriptionResolver::class); return $providesSubscriptionResolver->provideSubscriptionResolver($fieldValue); - } else { - /** @var \Nuwave\Lighthouse\Support\Contracts\ProvidesResolver $providesResolver */ - $providesResolver = app(ProvidesResolver::class); - - return $providesResolver->provideResolver($fieldValue); } + /** @var \Nuwave\Lighthouse\Support\Contracts\ProvidesResolver $providesResolver */ + $providesResolver = app(ProvidesResolver::class); + + return $providesResolver->provideResolver($fieldValue); } } diff --git a/src/Schema/ResolverProvider.php b/src/Schema/ResolverProvider.php index 05b85e7ce8..6c7465226c 100644 --- a/src/Schema/ResolverProvider.php +++ b/src/Schema/ResolverProvider.php @@ -21,7 +21,7 @@ public function provideResolver(FieldValue $fieldValue): Closure { if (RootType::isRootType($fieldValue->getParentName())) { $resolverClass = $this->findResolverClass($fieldValue, '__invoke'); - if ($resolverClass === null) { + if (null === $resolverClass) { $this->throwMissingResolver($fieldValue); } @@ -61,7 +61,8 @@ protected function throwMissingResolver(FieldValue $fieldValue): void $fieldName = $fieldValue->getFieldName(); $proposedResolverClass = ucfirst($fieldName); - throw new DefinitionException(<<directives as $directiveDefinition) { - $directives [] = $directiveFactory->handle($directiveDefinition); + $directives[] = $directiveFactory->handle($directiveDefinition); } $config->setDirectives( diff --git a/src/Schema/Source/SchemaStitcher.php b/src/Schema/Source/SchemaStitcher.php index 4f05ad9a13..0d2df69f0b 100644 --- a/src/Schema/Source/SchemaStitcher.php +++ b/src/Schema/Source/SchemaStitcher.php @@ -41,11 +41,11 @@ protected static function gatherSchemaImportsRecursively(string $path): string return (new Collection(\Safe\file($path))) ->map(function (string $line) use ($path): string { if (! Str::startsWith(trim($line), '#import ')) { - return rtrim($line, PHP_EOL).PHP_EOL; + return rtrim($line, PHP_EOL) . PHP_EOL; } $importFileName = trim(Str::after($line, '#import ')); - $importFilePath = dirname($path).'/'.$importFileName; + $importFilePath = dirname($path) . '/' . $importFileName; if (! Str::contains($importFileName, '*')) { try { diff --git a/src/Schema/TypeRegistry.php b/src/Schema/TypeRegistry.php index ee49e3b4d4..ecb847b6c4 100644 --- a/src/Schema/TypeRegistry.php +++ b/src/Schema/TypeRegistry.php @@ -106,7 +106,8 @@ public function setDocumentAST(DocumentAST $documentAST): self public function get(string $name): Type { if (! $this->has($name)) { - throw new DefinitionException(<<documentAST->types[$name] ?? null; - if ($typeDefinition === null) { + if (null === $typeDefinition) { return null; } @@ -327,16 +328,15 @@ protected function resolveObjectType(ObjectTypeDefinitionNode $objectDefinition) 'name' => $objectDefinition->name->value, 'description' => $objectDefinition->description->value ?? null, 'fields' => $this->makeFieldsLoader($objectDefinition), - 'interfaces' => + 'interfaces' /** * @return list<\GraphQL\Type\Definition\Type> - */ - function () use ($objectDefinition): array { + */ => function () use ($objectDefinition): array { $interfaces = []; // Might be a NodeList, so we can not use array_map() foreach ($objectDefinition->interfaces as $interface) { - $interfaces [] = $this->get($interface->name->value); + $interfaces[] = $this->get($interface->name->value); } return $interfaces; @@ -349,6 +349,7 @@ function () use ($objectDefinition): array { * Returns a closure that lazy loads the fields for a constructed type. * * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode $typeDefinition + * * @return \Closure(): array> */ protected function makeFieldsLoader($typeDefinition): Closure @@ -379,11 +380,10 @@ protected function resolveInputObjectType(InputObjectTypeDefinitionNode $inputDe return new InputObjectType([ 'name' => $inputDefinition->name->value, 'description' => $inputDefinition->description->value ?? null, - 'fields' => + 'fields' /** * @return array> - */ - function () use ($inputDefinition): array { + */ => function () use ($inputDefinition): array { return $this->argumentFactory->toTypeMap($inputDefinition->fields); }, 'astNode' => $inputDefinition, @@ -395,12 +395,12 @@ protected function resolveInterfaceType(InterfaceTypeDefinitionNode $interfaceDe $nodeName = $interfaceDefinition->name->value; if (($directiveNode = ASTHelper::directiveDefinition($interfaceDefinition, 'interface')) !== null) { - $interfaceDirective = (new InterfaceDirective)->hydrate($directiveNode, $interfaceDefinition); + $interfaceDirective = (new InterfaceDirective())->hydrate($directiveNode, $interfaceDefinition); $typeResolver = $interfaceDirective->getResolverFromArgument('resolveType'); } else { - $typeResolver = - $this->typeResolverFromClass( + $typeResolver + = $this->typeResolverFromClass( $nodeName, (array) config('lighthouse.namespaces.interfaces') ) @@ -433,7 +433,7 @@ protected function possibleImplementations(InterfaceTypeDefinitionNode $interfac $typeDefinition instanceof ObjectTypeDefinitionNode && ASTHelper::typeImplementsInterface($typeDefinition, $name) ) { - $implementations [] = $typeDefinition->name->value; + $implementations[] = $typeDefinition->name->value; } } @@ -467,6 +467,7 @@ function (string $className): bool { * Default type resolver for resolving interfaces or union types. * * @param list $possibleTypes + * * @return Closure(mixed): Type */ protected function typeResolverFallback(array $possibleTypes): Closure @@ -483,7 +484,7 @@ protected function typeResolverFallback(array $possibleTypes): Closure if (null !== $explicitSchemaMapping) { $actuallyPossibleTypes = array_intersect($possibleTypes, $explicitSchemaMapping); - if (count($actuallyPossibleTypes) !== 1) { + if (1 !== count($actuallyPossibleTypes)) { throw new DefinitionException( self::unresolvableAbstractTypeMapping($fqcn, $actuallyPossibleTypes) ); @@ -504,12 +505,12 @@ protected function resolveUnionType(UnionTypeDefinitionNode $unionDefinition): U $nodeName = $unionDefinition->name->value; if (($directiveNode = ASTHelper::directiveDefinition($unionDefinition, 'union')) !== null) { - $unionDirective = (new UnionDirective)->hydrate($directiveNode, $unionDefinition); + $unionDirective = (new UnionDirective())->hydrate($directiveNode, $unionDefinition); $typeResolver = $unionDirective->getResolverFromArgument('resolveType'); } else { - $typeResolver = - $this->typeResolverFromClass( + $typeResolver + = $this->typeResolverFromClass( $nodeName, (array) config('lighthouse.namespaces.unions') ) @@ -521,11 +522,10 @@ protected function resolveUnionType(UnionTypeDefinitionNode $unionDefinition): U return new UnionType([ 'name' => $nodeName, 'description' => $unionDefinition->description->value ?? null, - 'types' => + 'types' /** * @return list<\GraphQL\Type\Definition\Type> - */ - function () use ($unionDefinition): array { + */ => function () use ($unionDefinition): array { $types = []; foreach ($unionDefinition->types as $type) { @@ -556,7 +556,7 @@ protected function possibleUnionTypes(UnionTypeDefinitionNode $unionDefinition): $types = []; foreach ($unionDefinition->types as $type) { - $types [] = $type->name->value; + $types[] = $type->name->value; } return $types; diff --git a/src/Schema/Types/GraphQLSubscription.php b/src/Schema/Types/GraphQLSubscription.php index adc6087892..989ad3f33e 100644 --- a/src/Schema/Types/GraphQLSubscription.php +++ b/src/Schema/Types/GraphQLSubscription.php @@ -35,7 +35,8 @@ public function encodeTopic(Subscriber $subscriber, string $fieldName) /** * Decode topic name. * - * @param mixed $root The root value. + * @param mixed $root the root value + * * @return string */ public function decodeTopic(string $fieldName, $root) @@ -48,9 +49,10 @@ public function decodeTopic(string $fieldName, $root) /** * Resolve the subscription. * - * @param mixed $root The root value. + * @param mixed $root the root value * @param array $args - * @return mixed The root value. + * + * @return mixed the root value */ public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { @@ -67,7 +69,8 @@ abstract public function authorize(Subscriber $subscriber, Request $request); /** * Filter which subscribers should receive the subscription. * - * @param mixed $root The root value. + * @param mixed $root the root value + * * @return bool */ abstract public function filter(Subscriber $subscriber, $root); diff --git a/src/Schema/Types/Scalars/DateScalar.php b/src/Schema/Types/Scalars/DateScalar.php index 59a457e530..0a3368c74d 100644 --- a/src/Schema/Types/Scalars/DateScalar.php +++ b/src/Schema/Types/Scalars/DateScalar.php @@ -72,8 +72,8 @@ protected function tryParsingDate($value, string $exceptionClass): Carbon // We want to know if we have exactly a Carbon\Carbon, not a subclass thereof // @noRector Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector && ( - get_class($value) === \Carbon\Carbon::class - || get_class($value) === \Carbon\CarbonImmutable::class + \Carbon\Carbon::class === get_class($value) + || \Carbon\CarbonImmutable::class === get_class($value) ) ) { /** @var \Carbon\Carbon|\Carbon\CarbonImmutable $value */ @@ -112,7 +112,7 @@ abstract protected function format(Carbon $carbon): string; /** * Try turning a client value into a Carbon instance. * - * @param mixed $value A possibly faulty client value. + * @param mixed $value a possibly faulty client value */ abstract protected function parse($value): Carbon; } diff --git a/src/Schema/Types/Scalars/Upload.php b/src/Schema/Types/Scalars/Upload.php index a1a3362961..17ea3ffe29 100644 --- a/src/Schema/Types/Scalars/Upload.php +++ b/src/Schema/Types/Scalars/Upload.php @@ -31,7 +31,7 @@ public function parseValue($value): UploadedFile { if (! $value instanceof UploadedFile) { throw new Error( - 'Could not get uploaded file, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec Instead got: '.Utils::printSafe($value) + 'Could not get uploaded file, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec Instead got: ' . Utils::printSafe($value) ); } diff --git a/src/Schema/Values/CacheValue.php b/src/Schema/Values/CacheValue.php index 783e8f03ab..3582255053 100644 --- a/src/Schema/Values/CacheValue.php +++ b/src/Schema/Values/CacheValue.php @@ -9,7 +9,7 @@ class CacheValue { /** - * @var mixed|null The root that was passed to the query. + * @var mixed|null the root that was passed to the query */ protected $root; @@ -45,12 +45,12 @@ class CacheValue protected $isPrivate; /** - * @var mixed The key to use for caching this field. + * @var mixed the key to use for caching this field */ protected $fieldKey; /** - * @param mixed|null $root The root that was passed to the query. + * @param mixed|null $root the root that was passed to the query * @param array $args */ public function __construct( @@ -79,18 +79,18 @@ public function getKey(): string $parts = []; $user = $this->context->user(); - if ($this->isPrivate && $user !== null) { - $parts [] = 'auth'; - $parts [] = $user->getAuthIdentifier(); + if ($this->isPrivate && null !== $user) { + $parts[] = 'auth'; + $parts[] = $user->getAuthIdentifier(); } - $parts [] = strtolower($this->resolveInfo->parentType->name); - $parts [] = $this->fieldKey; - $parts [] = strtolower($this->resolveInfo->fieldName); + $parts[] = strtolower($this->resolveInfo->parentType->name); + $parts[] = $this->fieldKey; + $parts[] = strtolower($this->resolveInfo->fieldName); $argKeys = $this->argKeys(); if ($argKeys->isNotEmpty()) { - $parts [] = $argKeys->implode(':'); + $parts[] = $argKeys->implode(':'); } return $this->implode($parts); @@ -144,7 +144,7 @@ protected function argKeys(): Collection */ protected function fieldKey() { - if ($this->root === null) { + if (null === $this->root) { return; } diff --git a/src/Schema/Values/FieldValue.php b/src/Schema/Values/FieldValue.php index a4ff72e54d..c70eb4505f 100644 --- a/src/Schema/Values/FieldValue.php +++ b/src/Schema/Values/FieldValue.php @@ -215,7 +215,7 @@ public function setComplexity(Closure $complexity): self */ public function getReturnType(): Type { - if ($this->returnType === null) { + if (null === $this->returnType) { /** @var \Nuwave\Lighthouse\Schema\ExecutableTypeNodeConverter $typeNodeConverter */ $typeNodeConverter = app(ExecutableTypeNodeConverter::class); $this->returnType = $typeNodeConverter->convert($this->field->type); diff --git a/src/Scout/ScoutEnhancer.php b/src/Scout/ScoutEnhancer.php index b579581dea..c6e1d95774 100644 --- a/src/Scout/ScoutEnhancer.php +++ b/src/Scout/ScoutEnhancer.php @@ -71,12 +71,12 @@ public function enhanceBuilder(): ScoutBuilder } if (! $this->builder instanceof EloquentBuilder) { - throw new ScoutException('Can only get Model from \Illuminate\Database\Eloquent\Builder, got: '.get_class($this->builder)); + throw new ScoutException('Can only get Model from \Illuminate\Database\Eloquent\Builder, got: ' . get_class($this->builder)); } $model = $this->builder->getModel(); if (! Utils::classUsesTrait($model, Searchable::class)) { - throw new ScoutException('Model class '.get_class($model).' does not implement trait '.Searchable::class); + throw new ScoutException('Model class ' . get_class($model) . ' does not implement trait ' . Searchable::class); } // @phpstan-ignore-next-line Can not use traits as types @@ -118,7 +118,7 @@ protected function gather(ArgumentSet $argumentSet): void ->contains(Utils::instanceofMatcher(SearchDirective::class)); if ($argumentHasSearchDirective && is_string($argument->value)) { - $this->searchArguments [] = $argument; + $this->searchArguments[] = $argument; } $argumentHasArgBuilderDirective = $argument @@ -130,11 +130,11 @@ protected function gather(ArgumentSet $argumentSet): void ->contains(Utils::instanceofMatcher(ScoutBuilderDirective::class)); if ($argumentHasArgBuilderDirective && ! $argumentHasScoutBuilderDirective) { - $this->argumentsWithOnlyArgBuilders [] = $argument; + $this->argumentsWithOnlyArgBuilders[] = $argument; } if ($argumentHasScoutBuilderDirective) { - $this->argumentsWithScoutBuilderDirectives [] = $argument; + $this->argumentsWithScoutBuilderDirectives[] = $argument; } Utils::applyEach( diff --git a/src/Scout/SearchDirective.php b/src/Scout/SearchDirective.php index 3aa2848212..536f45a8ec 100644 --- a/src/Scout/SearchDirective.php +++ b/src/Scout/SearchDirective.php @@ -29,7 +29,7 @@ public function search(ScoutBuilder $builder): void if (null !== $within) { if (! is_string($within)) { throw new DefinitionException( - "Expected the value of the `within` argument of @{$this->name()} on {$this->nodeName()} to be a string, got: ".\Safe\json_encode($within) + "Expected the value of the `within` argument of @{$this->name()} on {$this->nodeName()} to be a string, got: " . \Safe\json_encode($within) ); } diff --git a/src/SoftDeletes/SoftDeletesDirective.php b/src/SoftDeletes/SoftDeletesDirective.php index 088411b4d3..eecbfa93ca 100644 --- a/src/SoftDeletes/SoftDeletesDirective.php +++ b/src/SoftDeletes/SoftDeletesDirective.php @@ -25,7 +25,7 @@ public static function definition(): string public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType): void { - $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' + $fieldDefinition->arguments[] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' """ Allows to filter if trashed elements should be fetched. """ diff --git a/src/SoftDeletes/TrashedDirective.php b/src/SoftDeletes/TrashedDirective.php index cb69429bda..cdb5380836 100644 --- a/src/SoftDeletes/TrashedDirective.php +++ b/src/SoftDeletes/TrashedDirective.php @@ -29,13 +29,13 @@ public static function definition(): string public function handleBuilder($builder, $value): object { if (! $builder instanceof EloquentBuilder) { - throw new Exception('Can not get model from builder of class: '.get_class($builder)); + throw new Exception('Can not get model from builder of class: ' . get_class($builder)); } $model = $builder->getModel(); $this->assertModelUsesSoftDeletes($model); - if ($value === null) { + if (null === $value) { return $builder; } @@ -51,7 +51,7 @@ public function handleBuilder($builder, $value): object // @phpstan-ignore-next-line because it involves mixins return $builder->withoutTrashed(); default: - throw new InvalidArgument('Unexpected value for Trashed filter: '.$value); + throw new InvalidArgument('Unexpected value for Trashed filter: ' . $value); } } @@ -61,7 +61,7 @@ public function handleScoutBuilder(ScoutBuilder $builder, $value): ScoutBuilder $this->assertModelUsesSoftDeletes($model); - if ($value === null) { + if (null === $value) { return $builder; } @@ -71,7 +71,7 @@ public function handleScoutBuilder(ScoutBuilder $builder, $value): ScoutBuilder case 'only': return $builder->onlyTrashed(); default: - throw new ScoutException('Unexpected value for Trashed filter: '.$value); + throw new ScoutException('Unexpected value for Trashed filter: ' . $value); } } diff --git a/src/Subscriptions/Authorizer.php b/src/Subscriptions/Authorizer.php index dff9d12564..629c17444b 100644 --- a/src/Subscriptions/Authorizer.php +++ b/src/Subscriptions/Authorizer.php @@ -47,7 +47,7 @@ public function authorize(Request $request): bool $channel = $this->sanitizeChannelName($channel); $subscriber = $this->storage->subscriberByChannel($channel); - if ($subscriber === null) { + if (null === $subscriber) { return false; } diff --git a/src/Subscriptions/BroadcastManager.php b/src/Subscriptions/BroadcastManager.php index 00712a212a..c8ffd70007 100644 --- a/src/Subscriptions/BroadcastManager.php +++ b/src/Subscriptions/BroadcastManager.php @@ -46,7 +46,7 @@ protected function createPusherDriver(array $config): PusherBroadcaster $connection = $config['connection'] ?? 'pusher'; $driverConfig = config("broadcasting.connections.{$connection}"); - if (empty($driverConfig) || $driverConfig['driver'] !== 'pusher') { + if (empty($driverConfig) || 'pusher' !== $driverConfig['driver']) { throw new RuntimeException("Could not initialize Pusher broadcast driver for connection: {$connection}."); } diff --git a/src/Subscriptions/BroadcastSubscriptionJob.php b/src/Subscriptions/BroadcastSubscriptionJob.php index a8142cb6de..2c84fb2b9d 100644 --- a/src/Subscriptions/BroadcastSubscriptionJob.php +++ b/src/Subscriptions/BroadcastSubscriptionJob.php @@ -10,7 +10,8 @@ class BroadcastSubscriptionJob implements ShouldQueue { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * The subscription field that was requested. @@ -29,7 +30,7 @@ class BroadcastSubscriptionJob implements ShouldQueue /** * The root element to be passed when resolving the subscription. * - * @var mixed User defined. + * @var mixed user defined */ public $root; diff --git a/src/Subscriptions/Broadcasters/EchoBroadcaster.php b/src/Subscriptions/Broadcasters/EchoBroadcaster.php index 0614b6860d..4dfc00b6ca 100644 --- a/src/Subscriptions/Broadcasters/EchoBroadcaster.php +++ b/src/Subscriptions/Broadcasters/EchoBroadcaster.php @@ -32,7 +32,7 @@ public function authorized(Request $request): JsonResponse { $userId = md5( $request->input('channel_name') - .$request->input('socket_id') + . $request->input('socket_id') ); return new JsonResponse([ diff --git a/src/Subscriptions/Broadcasters/PusherBroadcaster.php b/src/Subscriptions/Broadcasters/PusherBroadcaster.php index deaf538e8a..943ad571fd 100644 --- a/src/Subscriptions/Broadcasters/PusherBroadcaster.php +++ b/src/Subscriptions/Broadcasters/PusherBroadcaster.php @@ -57,7 +57,7 @@ public function unauthorized(Request $request): JsonResponse public function hook(Request $request): JsonResponse { foreach ($request->input('events', []) as $event) { - if ($event['name'] === 'channel_vacated') { + if ('channel_vacated' === $event['name']) { $this->storage->deleteSubscriber($event['channel']); } } diff --git a/src/Subscriptions/Contracts/Broadcaster.php b/src/Subscriptions/Contracts/Broadcaster.php index 07bb9d437a..4eaa4a578d 100644 --- a/src/Subscriptions/Contracts/Broadcaster.php +++ b/src/Subscriptions/Contracts/Broadcaster.php @@ -34,6 +34,7 @@ public function hook(Request $request); * Send data to subscriber. * * @param mixed $data The data to broadcast + * * @return void */ public function broadcast(Subscriber $subscriber, $data); diff --git a/src/Subscriptions/Contracts/SubscriptionIterator.php b/src/Subscriptions/Contracts/SubscriptionIterator.php index bc0461d966..1354af543d 100644 --- a/src/Subscriptions/Contracts/SubscriptionIterator.php +++ b/src/Subscriptions/Contracts/SubscriptionIterator.php @@ -10,9 +10,10 @@ interface SubscriptionIterator /** * Process subscribers through the given callbacks. * - * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> $subscribers The subscribers that receive the current subscription. - * @param \Closure(\Nuwave\Lighthouse\Subscriptions\Subscriber): void $handleSubscriber Receives each subscriber in the passed in collection. - * @param \Closure|null $handleError Is called when $handleSubscriber throws. + * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> $subscribers the subscribers that receive the current subscription + * @param \Closure(\Nuwave\Lighthouse\Subscriptions\Subscriber): void $handleSubscriber Receives each subscriber in the passed in collection + * @param \Closure|null $handleError is called when $handleSubscriber throws + * * @return void */ public function process(Collection $subscribers, Closure $handleSubscriber, Closure $handleError = null); diff --git a/src/Subscriptions/Events/EchoSubscriptionEvent.php b/src/Subscriptions/Events/EchoSubscriptionEvent.php index 81f847b8d3..bf97424026 100644 --- a/src/Subscriptions/Events/EchoSubscriptionEvent.php +++ b/src/Subscriptions/Events/EchoSubscriptionEvent.php @@ -14,12 +14,12 @@ class EchoSubscriptionEvent implements ShouldBroadcastNow public $channel; /** - * @var mixed The data to broadcast. + * @var mixed the data to broadcast */ public $data; /** - * @param mixed $data The data to broadcast. + * @param mixed $data the data to broadcast */ public function __construct(string $channel, $data) { diff --git a/src/Subscriptions/Exceptions/UnauthorizedSubscriber.php b/src/Subscriptions/Exceptions/UnauthorizedSubscriber.php index 7755e48486..5af9a68b53 100644 --- a/src/Subscriptions/Exceptions/UnauthorizedSubscriber.php +++ b/src/Subscriptions/Exceptions/UnauthorizedSubscriber.php @@ -6,5 +6,4 @@ class UnauthorizedSubscriber extends Error { - // } diff --git a/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php b/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php index afc76ca2be..b081815459 100644 --- a/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php +++ b/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php @@ -46,14 +46,14 @@ public function process(Collection $subscribers, Closure $handleSubscriber, Clos $subscribers->each(static function (Subscriber $item) use ($handleSubscriber, $handleError, $guard): void { // If there is an authenticated user set in the context, set that user as the authenticated user $user = $item->context->user(); - if ($user !== null) { + if (null !== $user) { $guard->setUser($user); } try { $handleSubscriber($item); } catch (Exception $e) { - if ($handleError === null) { + if (null === $handleError) { throw $e; } diff --git a/src/Subscriptions/Iterators/SyncIterator.php b/src/Subscriptions/Iterators/SyncIterator.php index bab81e2131..3699ba13d7 100644 --- a/src/Subscriptions/Iterators/SyncIterator.php +++ b/src/Subscriptions/Iterators/SyncIterator.php @@ -15,7 +15,7 @@ public function process(Collection $subscribers, Closure $handleSubscriber, Clos try { $handleSubscriber($item); } catch (Exception $e) { - if ($handleError === null) { + if (null === $handleError) { throw $e; } diff --git a/src/Subscriptions/Storage/CacheStorageManager.php b/src/Subscriptions/Storage/CacheStorageManager.php index 59082473ee..889c00ee85 100644 --- a/src/Subscriptions/Storage/CacheStorageManager.php +++ b/src/Subscriptions/Storage/CacheStorageManager.php @@ -44,13 +44,13 @@ public function __construct(CacheFactory $cacheFactory, ConfigRepository $config { $storage = $config->get('lighthouse.subscriptions.storage') ?? 'file'; if (! is_string($storage)) { - throw new Exception('Config setting lighthouse.subscriptions.storage must be a string or `null`, got: '.\Safe\json_encode($storage)); + throw new Exception('Config setting lighthouse.subscriptions.storage must be a string or `null`, got: ' . \Safe\json_encode($storage)); } $this->cache = $cacheFactory->store($storage); $ttl = $config->get('lighthouse.subscriptions.storage_ttl'); if (! is_null($ttl) && ! is_int($ttl)) { - throw new Exception('Config setting lighthouse.subscriptions.storage_ttl must be a int or `null`, got: '.\Safe\json_encode($ttl)); + throw new Exception('Config setting lighthouse.subscriptions.storage_ttl must be a int or `null`, got: ' . \Safe\json_encode($ttl)); } $this->ttl = $ttl; } @@ -79,7 +79,7 @@ public function storeSubscriber(Subscriber $subscriber, string $topic): void $this->addSubscriberToTopic($subscriber); $channelKey = self::channelKey($subscriber->channel); - if ($this->ttl === null) { + if (null === $this->ttl) { $this->cache->forever($channelKey, $subscriber); } else { // TODO: Change to just pass the ttl directly when support for Laravel <=5.7 is dropped @@ -91,7 +91,7 @@ public function deleteSubscriber(string $channel): ?Subscriber { $subscriber = $this->cache->pull(self::channelKey($channel)); - if ($subscriber !== null) { + if (null !== $subscriber) { $this->removeSubscriberFromTopic($subscriber); } @@ -105,7 +105,7 @@ public function deleteSubscriber(string $channel): ?Subscriber */ protected function storeTopic(string $key, Collection $topic): void { - if ($this->ttl === null) { + if (null === $this->ttl) { $this->cache->forever($key, $topic); } else { // TODO: Change to just pass the ttl directly when support for Laravel <=5.7 is dropped @@ -160,11 +160,11 @@ protected function removeSubscriberFromTopic(Subscriber $subscriber): void protected static function channelKey(string $channel): string { - return self::SUBSCRIBER_KEY.".{$channel}"; + return self::SUBSCRIBER_KEY . ".{$channel}"; } protected static function topicKey(string $topic): string { - return self::TOPIC_KEY.".{$topic}"; + return self::TOPIC_KEY . ".{$topic}"; } } diff --git a/src/Subscriptions/Storage/RedisStorageManager.php b/src/Subscriptions/Storage/RedisStorageManager.php index 703a34eefb..81ef8cc6fe 100644 --- a/src/Subscriptions/Storage/RedisStorageManager.php +++ b/src/Subscriptions/Storage/RedisStorageManager.php @@ -60,7 +60,7 @@ public function subscribersByTopic(string $topic): Collection // As explained in storeSubscriber, we use redis sets to store the names of subscribers of a topic. // We can retrieve all members of a set using the command smembers. $subscriberIds = $this->connection->command('smembers', [$this->topicKey($topic)]); - if (count($subscriberIds) === 0) { + if (0 === count($subscriberIds)) { return new Collection(); } @@ -92,7 +92,7 @@ public function storeSubscriber(Subscriber $subscriber, string $topic): void $subscriber->channel, ]); // ...and refresh the ttl of this set as well. - if ($this->ttl !== null) { + if (null !== $this->ttl) { $this->connection->command('expire', [$topicKey, $this->ttl]); } @@ -102,7 +102,7 @@ public function storeSubscriber(Subscriber $subscriber, string $topic): void $this->channelKey($subscriber->channel), $this->serialize($subscriber), ]; - if ($this->ttl !== null) { + if (null !== $this->ttl) { $setCommand = 'setex'; array_splice($setArguments, 1, 0, [$this->ttl]); } @@ -114,7 +114,7 @@ public function deleteSubscriber(string $channel): ?Subscriber $key = $this->channelKey($channel); $subscriber = $this->getSubscriber($key); - if ($subscriber !== null) { + if (null !== $subscriber) { // Like in storeSubscriber (but in reverse), we delete the subscriber... $this->connection->command('del', [$key]); // ...and remove it from the set of subscribers of this topic. @@ -143,24 +143,25 @@ protected function getSubscriber(string $channelKey): ?Subscriber protected function channelKey(string $channel): string { - return self::SUBSCRIBER_KEY.'.'.$channel; + return self::SUBSCRIBER_KEY . '.' . $channel; } protected function topicKey(string $topic): string { - return self::TOPIC_KEY.'.'.$topic; + return self::TOPIC_KEY . '.' . $topic; } /** - * @param mixed $value Value to serialize. - * @return mixed Storable value. + * @param mixed $value value to serialize + * + * @return mixed storable value * * @see \Illuminate\Cache\RedisStore::serialize */ protected function serialize($value) { $isProperNumber = is_numeric($value) - && ($value !== INF && $value !== -INF) + && (INF !== $value && $value !== -INF) && ! is_nan(floatval($value)); return $isProperNumber @@ -169,8 +170,9 @@ protected function serialize($value) } /** - * @param mixed $value Value to unserialize. - * @return mixed Unserialized value. + * @param mixed $value value to unserialize + * + * @return mixed unserialized value */ protected function unserialize($value) { diff --git a/src/Subscriptions/Subscriber.php b/src/Subscriptions/Subscriber.php index c653d2d029..ce4c1ca422 100644 --- a/src/Subscriptions/Subscriber.php +++ b/src/Subscriptions/Subscriber.php @@ -51,7 +51,7 @@ class Subscriber implements Serializable /** * The root element of the query. * - * @var mixed Can be anything. + * @var mixed can be anything */ public $root; @@ -181,7 +181,7 @@ public function setRoot($root): self */ public static function uniqueChannelName(): string { - return 'private-lighthouse-'.Str::random(32).'-'.time(); + return 'private-lighthouse-' . Str::random(32) . '-' . time(); } protected function contextSerializer(): ContextSerializer diff --git a/src/Subscriptions/SubscriptionRegistry.php b/src/Subscriptions/SubscriptionRegistry.php index bad521801b..4ac65f0f4d 100644 --- a/src/Subscriptions/SubscriptionRegistry.php +++ b/src/Subscriptions/SubscriptionRegistry.php @@ -89,7 +89,7 @@ public function has(string $key): bool * * @return array * - * @deprecated Use the `GraphQL\Type\Schema::subscriptionType()->getFieldNames()` method directly. + * @deprecated use the `GraphQL\Type\Schema::subscriptionType()->getFieldNames()` method directly */ public function keys(): array { @@ -139,7 +139,7 @@ public function subscriptions(Subscriber $subscriber): Collection Utils::instanceofMatcher(OperationDefinitionNode::class) ) ->filter(function (OperationDefinitionNode $node): bool { - return $node->operation === 'subscription'; + return 'subscription' === $node->operation; }) ->flatMap(function (OperationDefinitionNode $node): array { return (new Collection($node->selectionSet->selections)) @@ -153,7 +153,7 @@ public function subscriptions(Subscriber $subscriber): Collection return $this->subscription($subscriptionField); } - return new NotFoundSubscription; + return new NotFoundSubscription(); }); } @@ -173,7 +173,7 @@ public function handleBuildExtensionsResponse(BuildExtensionsResponse $buildExte ? reset($this->subscribers) : null; - if ($channel === null && ($subscriptionsConfig['exclude_empty'] ?? false)) { + if (null === $channel && ($subscriptionsConfig['exclude_empty'] ?? false)) { return null; } @@ -203,7 +203,7 @@ protected function subscriptionType(): ObjectType { $subscriptionType = $this->schemaBuilder->schema()->getSubscriptionType(); - if ($subscriptionType === null) { + if (null === $subscriptionType) { throw new DefinitionException('Schema is missing subscription root type.'); } diff --git a/src/Subscriptions/SubscriptionResolverProvider.php b/src/Subscriptions/SubscriptionResolverProvider.php index 66111b1d3c..861eadc1f6 100644 --- a/src/Subscriptions/SubscriptionResolverProvider.php +++ b/src/Subscriptions/SubscriptionResolverProvider.php @@ -31,16 +31,16 @@ public function __construct(SubscriptionRegistry $subscriptionRegistry) /** * Provide a resolver for a subscription field in case no resolver directive is defined. * - * @return \Closure(mixed, array, \Nuwave\Lighthouse\Support\Contracts\GraphQLContext, \GraphQL\Type\Definition\ResolveInfo): mixed - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return \Closure(mixed, array, \Nuwave\Lighthouse\Support\Contracts\GraphQLContext, \GraphQL\Type\Definition\ResolveInfo): mixed */ public function provideSubscriptionResolver(FieldValue $fieldValue): Closure { $fieldName = $fieldValue->getFieldName(); $directive = ASTHelper::directiveDefinition($fieldValue->getField(), SubscriptionDirective::NAME); - if ($directive !== null) { + if (null !== $directive) { $className = ASTHelper::directiveArgValue($directive, 'class'); } else { $className = Str::studly($fieldName); diff --git a/src/Subscriptions/SubscriptionRouter.php b/src/Subscriptions/SubscriptionRouter.php index 5ff2bda01c..cc74431a1e 100644 --- a/src/Subscriptions/SubscriptionRouter.php +++ b/src/Subscriptions/SubscriptionRouter.php @@ -13,12 +13,12 @@ public function pusher($router): void { $router->post('graphql/subscriptions/auth', [ 'as' => 'lighthouse.subscriptions.auth', - 'uses' => SubscriptionController::class.'@authorize', + 'uses' => SubscriptionController::class . '@authorize', ]); $router->post('graphql/subscriptions/webhook', [ 'as' => 'lighthouse.subscriptions.webhook', - 'uses' => SubscriptionController::class.'@webhook', + 'uses' => SubscriptionController::class . '@webhook', ]); } @@ -29,7 +29,7 @@ public function echoRoutes($router): void { $router->post('graphql/subscriptions/auth', [ 'as' => 'lighthouse.subscriptions.auth', - 'uses' => SubscriptionController::class.'@authorize', + 'uses' => SubscriptionController::class . '@authorize', ]); } } diff --git a/src/Subscriptions/SubscriptionServiceProvider.php b/src/Subscriptions/SubscriptionServiceProvider.php index ee03d7ff3b..ab4b78e985 100644 --- a/src/Subscriptions/SubscriptionServiceProvider.php +++ b/src/Subscriptions/SubscriptionServiceProvider.php @@ -52,18 +52,18 @@ public function boot(EventsDispatcher $eventsDispatcher, ConfigRepository $confi { $eventsDispatcher->listen( StartExecution::class, - SubscriptionRegistry::class.'@handleStartExecution' + SubscriptionRegistry::class . '@handleStartExecution' ); $eventsDispatcher->listen( BuildExtensionsResponse::class, - SubscriptionRegistry::class.'@handleBuildExtensionsResponse' + SubscriptionRegistry::class . '@handleBuildExtensionsResponse' ); $eventsDispatcher->listen( RegisterDirectiveNamespaces::class, static function (): string { - return __NAMESPACE__.'\\Directives'; + return __NAMESPACE__ . '\\Directives'; } ); @@ -72,7 +72,7 @@ static function (): string { // If authentication is used, we can log in subscribers when broadcasting an update if ($this->app->bound(AuthManager::class)) { config([ - 'auth.guards.'.SubscriptionGuard::GUARD_NAME => [ + 'auth.guards.' . SubscriptionGuard::GUARD_NAME => [ 'driver' => SubscriptionGuard::GUARD_NAME, ], ]); @@ -80,7 +80,7 @@ static function (): string { $this->app->bind(SubscriptionIterator::class, AuthenticatingSyncIterator::class); $this->app->make(AuthManager::class)->extend(SubscriptionGuard::GUARD_NAME, static function () { - return new SubscriptionGuard; + return new SubscriptionGuard(); }); } } diff --git a/src/Support/Contracts/ArgBuilderDirective.php b/src/Support/Contracts/ArgBuilderDirective.php index cff8daaee6..bd5d998df2 100644 --- a/src/Support/Contracts/ArgBuilderDirective.php +++ b/src/Support/Contracts/ArgBuilderDirective.php @@ -7,9 +7,10 @@ interface ArgBuilderDirective extends Directive /** * Add additional constraints to the builder based on the given argument value. * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder The builder used to resolve the field. - * @param mixed $value The client given value of the argument. - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder The modified builder. + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder the builder used to resolve the field + * @param mixed $value the client given value of the argument + * + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder the modified builder */ public function handleBuilder($builder, $value); } diff --git a/src/Support/Contracts/ArgDirective.php b/src/Support/Contracts/ArgDirective.php index 24ee7e48c6..45f84134a7 100644 --- a/src/Support/Contracts/ArgDirective.php +++ b/src/Support/Contracts/ArgDirective.php @@ -8,5 +8,4 @@ */ interface ArgDirective extends Directive { - // } diff --git a/src/Support/Contracts/ArgDirectiveForArray.php b/src/Support/Contracts/ArgDirectiveForArray.php index d10d8b887f..04c4528ed4 100644 --- a/src/Support/Contracts/ArgDirectiveForArray.php +++ b/src/Support/Contracts/ArgDirectiveForArray.php @@ -8,5 +8,4 @@ */ interface ArgDirectiveForArray extends Directive { - // } diff --git a/src/Support/Contracts/ArgResolver.php b/src/Support/Contracts/ArgResolver.php index 73df264e02..d5eb50cc0e 100644 --- a/src/Support/Contracts/ArgResolver.php +++ b/src/Support/Contracts/ArgResolver.php @@ -5,8 +5,9 @@ interface ArgResolver { /** - * @param mixed $root The result of the parent resolver. - * @param mixed|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $value The slice of arguments that belongs to this nested resolver. + * @param mixed $root the result of the parent resolver + * @param mixed|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $value the slice of arguments that belongs to this nested resolver + * * @return mixed|null May return the modified $root */ public function __invoke($root, $value); diff --git a/src/Support/Contracts/ArgSanitizerDirective.php b/src/Support/Contracts/ArgSanitizerDirective.php index a7e283a034..b8cbc66dde 100644 --- a/src/Support/Contracts/ArgSanitizerDirective.php +++ b/src/Support/Contracts/ArgSanitizerDirective.php @@ -8,7 +8,8 @@ interface ArgSanitizerDirective extends Directive * Sanitize the value of an argument given to a field. * * @param mixed $argumentValue The value given by the client - * @return mixed The sanitized value. + * + * @return mixed the sanitized value */ public function sanitize($argumentValue); } diff --git a/src/Support/Contracts/ArgTransformerDirective.php b/src/Support/Contracts/ArgTransformerDirective.php index 802fb46cc2..5206bd6308 100644 --- a/src/Support/Contracts/ArgTransformerDirective.php +++ b/src/Support/Contracts/ArgTransformerDirective.php @@ -7,8 +7,9 @@ interface ArgTransformerDirective extends Directive /** * Apply transformations on the value of an argument given to a field. * - * @param mixed $argumentValue The client given value. - * @return mixed The transformed value. + * @param mixed $argumentValue the client given value + * + * @return mixed the transformed value */ public function transform($argumentValue); } diff --git a/src/Support/Contracts/CanStreamResponse.php b/src/Support/Contracts/CanStreamResponse.php index 34bedc72fb..72fa66ff12 100644 --- a/src/Support/Contracts/CanStreamResponse.php +++ b/src/Support/Contracts/CanStreamResponse.php @@ -9,6 +9,7 @@ interface CanStreamResponse * * @param array $data * @param array $paths + * * @return void This function is expected to emit a stream as a side effect */ public function stream(array $data, array $paths, bool $isFinalChunk); diff --git a/src/Support/Contracts/CreatesResponse.php b/src/Support/Contracts/CreatesResponse.php index c0126594db..ba5b7d3ef0 100644 --- a/src/Support/Contracts/CreatesResponse.php +++ b/src/Support/Contracts/CreatesResponse.php @@ -8,6 +8,7 @@ interface CreatesResponse * Create a HTTP response from the final result. * * @param array|array> $result + * * @return \Symfony\Component\HttpFoundation\Response */ public function createResponse(array $result); diff --git a/src/Support/Contracts/FieldBuilderDirective.php b/src/Support/Contracts/FieldBuilderDirective.php index e2a7e74c6b..46c5e9d37c 100644 --- a/src/Support/Contracts/FieldBuilderDirective.php +++ b/src/Support/Contracts/FieldBuilderDirective.php @@ -7,8 +7,9 @@ interface FieldBuilderDirective extends Directive /** * Add additional constraints to the builder. * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder The builder used to resolve the field. - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder The modified builder. + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder the builder used to resolve the field + * + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder the modified builder */ public function handleFieldBuilder(object $builder): object; } diff --git a/src/Support/Contracts/FieldMiddleware.php b/src/Support/Contracts/FieldMiddleware.php index dd5c77546e..73882d52f3 100644 --- a/src/Support/Contracts/FieldMiddleware.php +++ b/src/Support/Contracts/FieldMiddleware.php @@ -11,6 +11,7 @@ interface FieldMiddleware extends Directive * Wrap around the final field resolver. * * @param \Closure(\Nuwave\Lighthouse\Schema\Values\FieldValue $field): \Nuwave\Lighthouse\Schema\Values\FieldValue $next + * * @return \Nuwave\Lighthouse\Schema\Values\FieldValue */ public function handleField(FieldValue $fieldValue, Closure $next); diff --git a/src/Support/Contracts/TypeManipulator.php b/src/Support/Contracts/TypeManipulator.php index 65d58f20f5..efcec13866 100644 --- a/src/Support/Contracts/TypeManipulator.php +++ b/src/Support/Contracts/TypeManipulator.php @@ -11,6 +11,7 @@ interface TypeManipulator extends Directive * Apply manipulations from a type definition node. * * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $typeDefinition + * * @return void */ public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition); diff --git a/src/Support/DriverManager.php b/src/Support/DriverManager.php index 35f90947c7..5eb2b3b28b 100644 --- a/src/Support/DriverManager.php +++ b/src/Support/DriverManager.php @@ -44,7 +44,7 @@ public function __construct(Application $app) /** * Get a driver instance by name. * - * @return object The driver instance. + * @return object the driver instance */ public function driver(?string $name = null) { @@ -56,7 +56,7 @@ public function driver(?string $name = null) /** * Attempt to get the driver from the local cache. * - * @return object The resolved driver. + * @return object the resolved driver */ protected function get(string $name) { @@ -105,9 +105,9 @@ public function extend(string $driver, Closure $callback): self /** * Resolve the given driver. * - * @return object The resolved driver. - * * @throws \InvalidArgumentException + * + * @return object the resolved driver */ protected function resolve(string $name) { @@ -117,7 +117,7 @@ protected function resolve(string $name) return $this->validateDriver($this->callCustomCreator($config)); } - $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; + $driverMethod = 'create' . ucfirst($config['driver']) . 'Driver'; if (method_exists($this, $driverMethod)) { return $this->validateDriver($this->{$driverMethod}($config)); @@ -130,7 +130,8 @@ protected function resolve(string $name) * Call a custom driver creator. * * @param array $config - * @return object The created driver. + * + * @return object the created driver */ protected function callCustomCreator(array $config) { @@ -141,16 +142,17 @@ protected function callCustomCreator(array $config) * Validate driver implements the proper interface. * * @param object $driver - * @return object * * @throws \Nuwave\Lighthouse\Exceptions\InvalidDriverException + * + * @return object */ protected function validateDriver($driver) { $interface = $this->interface(); if (! (new ReflectionClass($driver))->implementsInterface($interface)) { - throw new InvalidDriverException(get_class($driver)." does not implement {$interface}"); + throw new InvalidDriverException(get_class($driver) . " does not implement {$interface}"); } return $driver; @@ -160,7 +162,8 @@ protected function validateDriver($driver) * Dynamically call the default driver instance. * * @param array $parameters - * @return mixed Whatever the driver returned. + * + * @return mixed whatever the driver returned */ public function __call(string $method, array $parameters) { diff --git a/src/Support/Http/Middleware/AcceptJson.php b/src/Support/Http/Middleware/AcceptJson.php index da14910503..aa32f385ec 100644 --- a/src/Support/Http/Middleware/AcceptJson.php +++ b/src/Support/Http/Middleware/AcceptJson.php @@ -14,8 +14,8 @@ */ class AcceptJson { - const ACCEPT = 'Accept'; - const APPLICATION_JSON = 'application/json'; + public const ACCEPT = 'Accept'; + public const APPLICATION_JSON = 'application/json'; /** * @return \Symfony\Component\HttpFoundation\Response|\Illuminate\Http\JsonResponse diff --git a/src/Support/Http/Middleware/AttemptAuthentication.php b/src/Support/Http/Middleware/AttemptAuthentication.php index 48d436c062..57e2202625 100644 --- a/src/Support/Http/Middleware/AttemptAuthentication.php +++ b/src/Support/Http/Middleware/AttemptAuthentication.php @@ -24,6 +24,7 @@ public function __construct(AuthFactory $authFactory) /** * @param string ...$guards + * * @return mixed Any kind of response */ public function handle(Request $request, Closure $next, ...$guards) diff --git a/src/Support/Http/Middleware/LogGraphQLQueries.php b/src/Support/Http/Middleware/LogGraphQLQueries.php index 6cf727ddbf..8abdabcaea 100644 --- a/src/Support/Http/Middleware/LogGraphQLQueries.php +++ b/src/Support/Http/Middleware/LogGraphQLQueries.php @@ -11,7 +11,7 @@ */ class LogGraphQLQueries { - const MESSAGE = 'Received GraphQL query'; + public const MESSAGE = 'Received GraphQL query'; /** * @var \Psr\Log\LoggerInterface diff --git a/src/Support/Http/Responses/ResponseStream.php b/src/Support/Http/Responses/ResponseStream.php index c896c74237..44a66d5a4b 100644 --- a/src/Support/Http/Responses/ResponseStream.php +++ b/src/Support/Http/Responses/ResponseStream.php @@ -52,12 +52,12 @@ public function stream(array $data, array $paths, bool $isFinalChunk): void protected function boundary(): string { - return self::EOL.'---'.self::EOL; + return self::EOL . '---' . self::EOL; } protected function terminatingBoundary(): string { - return self::EOL.'-----'.self::EOL; + return self::EOL . '-----' . self::EOL; } /** @@ -71,17 +71,17 @@ protected function chunk(array $data, bool $terminating): string $length = $terminating ? strlen($json) - : strlen($json.self::EOL); + : strlen($json . self::EOL); $chunk = implode(self::EOL, [ 'Content-Type: application/json', - 'Content-Length: '.$length, + 'Content-Length: ' . $length, '', $json, '', ]); - return $this->boundary().$chunk; + return $this->boundary() . $chunk; } /** diff --git a/src/Support/Http/Responses/Stream.php b/src/Support/Http/Responses/Stream.php index 78c09e7038..bb4d6f582a 100644 --- a/src/Support/Http/Responses/Stream.php +++ b/src/Support/Http/Responses/Stream.php @@ -10,6 +10,7 @@ abstract class Stream * Get error from chunk if it exists. * * @param array $data + * * @return array>|null */ protected function chunkError(string $path, array $data): ?array diff --git a/src/Support/Traits/GeneratesColumnsEnum.php b/src/Support/Traits/GeneratesColumnsEnum.php index 4d4728db69..31d46c2748 100644 --- a/src/Support/Traits/GeneratesColumnsEnum.php +++ b/src/Support/Traits/GeneratesColumnsEnum.php @@ -29,7 +29,7 @@ protected function hasAllowedColumns(): bool if ($hasColumns && $hasColumnsEnum) { throw new DefinitionException( - 'The @'.$this->name().' directive can only have one of the following arguments: `columns`, `columnsEnum`.' + 'The @' . $this->name() . ' directive can only have one of the following arguments: `columns`, `columnsEnum`.' ); } @@ -39,7 +39,7 @@ protected function hasAllowedColumns(): bool /** * Generate the enumeration type for the list of allowed columns. * - * @return string The name of the used enum. + * @return string the name of the used enum */ protected function generateColumnsEnum( DocumentAST &$documentAST, @@ -53,7 +53,7 @@ protected function generateColumnsEnum( return $columnsEnum; } - $allowedColumnsEnumName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).'Column'; + $allowedColumnsEnumName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType) . 'Column'; $documentAST ->setTypeDefinition( @@ -87,7 +87,7 @@ function (string $columnName): string { strtoupper( Str::snake($columnName) ) - .' @enum(value: "'.$columnName.'")'; + . ' @enum(value: "' . $columnName . '")'; }, $allowedColumns ); diff --git a/src/Support/Utils.php b/src/Support/Utils.php index 752637e104..1882e1b44c 100644 --- a/src/Support/Utils.php +++ b/src/Support/Utils.php @@ -17,6 +17,7 @@ class Utils * * @param array $namespacesToTry * @param callable(string $className): bool $determineMatch + * * @return class-string|null */ public static function namespaceClassname(string $classCandidate, array $namespacesToTry, callable $determineMatch): ?string @@ -27,7 +28,7 @@ public static function namespaceClassname(string $classCandidate, array $namespa } foreach ($namespacesToTry as $namespace) { - $className = $namespace.'\\'.$classCandidate; + $className = $namespace . '\\' . $classCandidate; if ($determineMatch($className)) { /** @var class-string $className */ @@ -41,8 +42,8 @@ public static function namespaceClassname(string $classCandidate, array $namespa /** * Construct a closure that passes through the arguments. * - * @param class-string $className This class is resolved through the container. - * @param string $methodName The method that gets passed the arguments of the closure. + * @param class-string $className this class is resolved through the container + * @param string $methodName the method that gets passed the arguments of the closure * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ @@ -63,10 +64,11 @@ public static function constructResolver(string $className, string $methodName): * * Returns a default value in case of error. * - * @param mixed $object Object with protected member. - * @param string $memberName Name of object's protected member. - * @param mixed|null $default Default value to return in case of access error. - * @return mixed Value of object's protected member. + * @param mixed $object object with protected member + * @param string $memberName name of object's protected member + * @param mixed|null $default default value to return in case of access error + * + * @return mixed value of object's protected member */ public static function accessProtected($object, string $memberName, $default = null) { @@ -85,9 +87,10 @@ public static function accessProtected($object, string $memberName, $default = n * Apply a callback to a value or each value in an array. * * @param mixed|array $valueOrValues + * * @return mixed|array */ - public static function applyEach(\Closure $callback, $valueOrValues) + public static function applyEach(Closure $callback, $valueOrValues) { if (is_array($valueOrValues)) { return array_map($callback, $valueOrValues); @@ -113,6 +116,7 @@ class_uses_recursive($class) * Construct a callback that checks if its input is a given class. * * @param class-string $classLike + * * @return Closure(mixed): bool */ public static function instanceofMatcher(string $classLike): Closure diff --git a/src/Testing/MakesGraphQLRequests.php b/src/Testing/MakesGraphQLRequests.php index a97e6123e1..6e7251dd15 100644 --- a/src/Testing/MakesGraphQLRequests.php +++ b/src/Testing/MakesGraphQLRequests.php @@ -42,6 +42,7 @@ trait MakesGraphQLRequests * @param array $variables The variables to include in the query * @param array $extraParams Extra parameters to add to the JSON payload * @param array $headers HTTP headers to pass to the POST request + * * @return \Illuminate\Testing\TestResponse */ protected function graphQL( @@ -52,7 +53,7 @@ protected function graphQL( ) { $params = ['query' => $query]; - if ($variables !== []) { + if ([] !== $variables) { $params += ['variables' => $variables]; } @@ -69,6 +70,7 @@ protected function graphQL( * * @param array $data JSON-serializable payload * @param array $headers HTTP headers to pass to the POST request + * * @return \Illuminate\Testing\TestResponse */ protected function postGraphQL(array $data, array $headers = []) @@ -90,6 +92,7 @@ protected function postGraphQL(array $data, array $headers = []) * @param array> $map * @param array|array $files * @param array $headers Will be merged with Content-Type: multipart/form-data + * * @return \Illuminate\Testing\TestResponse */ protected function multipartGraphQL( @@ -125,7 +128,7 @@ protected function multipartGraphQL( */ protected function introspect() { - if ($this->introspectionResult !== null) { + if (null !== $this->introspectionResult) { return $this->introspectionResult; } @@ -159,7 +162,7 @@ protected function introspectDirective(string $name): ?array */ protected function introspectByName(string $path, string $name): ?array { - if ($this->introspectionResult === null) { + if (null === $this->introspectionResult) { $this->introspect(); } @@ -191,6 +194,7 @@ protected function graphQLEndpointUrl(): string * @param array $variables The variables to include in the query * @param array $extraParams Extra parameters to add to the HTTP payload * @param array $headers HTTP headers to pass to the POST request + * * @return array The chunked results */ protected function streamGraphQL( @@ -199,7 +203,7 @@ protected function streamGraphQL( array $extraParams = [], array $headers = [] ): array { - if ($this->deferStream === null) { + if (null === $this->deferStream) { $this->setUpDeferStream(); } @@ -219,7 +223,7 @@ protected function streamGraphQL( */ protected function setUpDeferStream(): void { - $this->deferStream = new MemoryStream; + $this->deferStream = new MemoryStream(); Container::getInstance()->singleton(CanStreamResponse::class, function (): MemoryStream { return $this->deferStream; diff --git a/src/Testing/MakesGraphQLRequestsLumen.php b/src/Testing/MakesGraphQLRequestsLumen.php index b7f62ae30d..049df21c8f 100644 --- a/src/Testing/MakesGraphQLRequestsLumen.php +++ b/src/Testing/MakesGraphQLRequestsLumen.php @@ -51,7 +51,7 @@ protected function graphQL( ): self { $params = ['query' => $query]; - if ($variables !== []) { + if ([] !== $variables) { $params += ['variables' => $variables]; } @@ -91,6 +91,7 @@ protected function postGraphQL(array $data, array $headers = []): self * @param array> $map * @param array<\Illuminate\Http\Testing\File>|array> $files * @param array $headers Will be merged with Content-Type: multipart/form-data + * * @return $this */ protected function multipartGraphQL( @@ -194,6 +195,7 @@ protected function graphQLEndpointUrl(): string * @param array $variables The variables to include in the query * @param array $extraParams Extra parameters to add to the HTTP payload * @param array $headers HTTP headers to pass to the POST request + * * @return array The chunked results */ protected function streamGraphQL( @@ -222,7 +224,7 @@ protected function streamGraphQL( */ protected function setUpDeferStream(): void { - $this->deferStream = new MemoryStream; + $this->deferStream = new MemoryStream(); Container::getInstance()->singleton(CanStreamResponse::class, function (): MemoryStream { return $this->deferStream; diff --git a/src/Testing/MockResolver.php b/src/Testing/MockResolver.php index f554c0edd7..e301d0414f 100644 --- a/src/Testing/MockResolver.php +++ b/src/Testing/MockResolver.php @@ -11,7 +11,7 @@ class MockResolver /** * @noRector \Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector * - * @return mixed|void Anything whatsoever. + * @return mixed|void anything whatsoever */ public function __invoke() { diff --git a/src/Testing/RethrowingErrorHandler.php b/src/Testing/RethrowingErrorHandler.php index 96797b44d1..1630cc4c93 100644 --- a/src/Testing/RethrowingErrorHandler.php +++ b/src/Testing/RethrowingErrorHandler.php @@ -13,7 +13,7 @@ class RethrowingErrorHandler implements ErrorHandler { public function __invoke(?Error $error, Closure $next): ?array { - if ($error === null) { + if (null === $error) { return $next(null); } diff --git a/src/Testing/TestResponseMixin.php b/src/Testing/TestResponseMixin.php index 6c481290e4..e36f60cf10 100644 --- a/src/Testing/TestResponseMixin.php +++ b/src/Testing/TestResponseMixin.php @@ -65,7 +65,7 @@ public function assertGraphQLErrorMessage(): Closure Assert::assertContains( $message, $messages, - "Expected the GraphQL response to contain error message `{$message}`, got: ".\Safe\json_encode($messages) + "Expected the GraphQL response to contain error message `{$message}`, got: " . \Safe\json_encode($messages) ); return $this; diff --git a/src/Testing/TestResponseUtils.php b/src/Testing/TestResponseUtils.php index 3eda5583f5..4383fc7658 100644 --- a/src/Testing/TestResponseUtils.php +++ b/src/Testing/TestResponseUtils.php @@ -13,6 +13,7 @@ class TestResponseUtils { /** * @param \Illuminate\Testing\TestResponse $response + * * @return array>|null */ public static function extractValidationErrors($response): ?array diff --git a/src/Tracing/Tracing.php b/src/Tracing/Tracing.php index 42a6e57b57..7c7e0ea675 100644 --- a/src/Tracing/Tracing.php +++ b/src/Tracing/Tracing.php @@ -97,7 +97,7 @@ public function handleBuildExtensionsResponse(BuildExtensionsResponse $buildExte */ public function record(ResolveInfo $resolveInfo, $start, $end): void { - $this->resolverTraces [] = [ + $this->resolverTraces[] = [ 'path' => $resolveInfo->path, 'parentType' => $resolveInfo->parentType->name, 'returnType' => $resolveInfo->returnType->__toString(), diff --git a/src/Tracing/TracingServiceProvider.php b/src/Tracing/TracingServiceProvider.php index e2c2348860..585f4e407f 100644 --- a/src/Tracing/TracingServiceProvider.php +++ b/src/Tracing/TracingServiceProvider.php @@ -28,22 +28,22 @@ static function (): string { $eventsDispatcher->listen( ManipulateAST::class, - Tracing::class.'@handleManipulateAST' + Tracing::class . '@handleManipulateAST' ); $eventsDispatcher->listen( StartRequest::class, - Tracing::class.'@handleStartRequest' + Tracing::class . '@handleStartRequest' ); $eventsDispatcher->listen( StartExecution::class, - Tracing::class.'@handleStartExecution' + Tracing::class . '@handleStartExecution' ); $eventsDispatcher->listen( BuildExtensionsResponse::class, - Tracing::class.'@handleBuildExtensionsResponse' + Tracing::class . '@handleBuildExtensionsResponse' ); } } diff --git a/src/Validation/BaseRulesDirective.php b/src/Validation/BaseRulesDirective.php index 00f67d7cae..4253e9251f 100644 --- a/src/Validation/BaseRulesDirective.php +++ b/src/Validation/BaseRulesDirective.php @@ -32,7 +32,7 @@ public function rules(): array public function messages(): array { $messages = $this->directiveArgValue('messages'); - if ($messages === null) { + if (null === $messages) { return []; } @@ -78,7 +78,7 @@ protected function validateRulesArg(): void $this->invalidApplyArgument($rules); } - if (count($rules) === 0) { + if (0 === count($rules)) { $this->invalidApplyArgument($rules); } @@ -92,7 +92,7 @@ protected function validateRulesArg(): void protected function validateMessageArg(): void { $messages = $this->directiveArgValue('messages'); - if ($messages === null) { + if (null === $messages) { return; } diff --git a/src/Validation/RulesGatherer.php b/src/Validation/RulesGatherer.php index 0a46f8d147..0503ed5e6d 100644 --- a/src/Validation/RulesGatherer.php +++ b/src/Validation/RulesGatherer.php @@ -195,6 +195,7 @@ public function extractValidationForArgument(ArgumentValidation $directive, arra /** * @param array $rulesOrMessages * @param array $path + * * @return array */ protected function wrap(array $rulesOrMessages, array $path): array @@ -220,6 +221,7 @@ protected function wrap(array $rulesOrMessages, array $path): array * * @param array $rules * @param array $argumentPath + * * @return array|object> */ protected function qualifyArgumentReferences(array $rules, array $argumentPath): array @@ -248,7 +250,7 @@ static function ($rule) use ($argumentPath) { $name = $parsed[0]; $args = $parsed[1]; - if ($name === 'WithReference') { + if ('WithReference' === $name) { $indexes = explode('_', $args[1]); array_splice($args, 1, 1); foreach ($indexes as $index) { @@ -316,7 +318,7 @@ static function (string $field) use ($argumentPath): string { // Laravel expects the rule to be a flat array of name, arg1, arg2, ... $flatArgs = [$name]; foreach ($args as $arg) { - $flatArgs [] = $arg; + $flatArgs[] = $arg; } return $flatArgs; diff --git a/src/Validation/Validator.php b/src/Validation/Validator.php index aaf062c4fa..45ce18e973 100644 --- a/src/Validation/Validator.php +++ b/src/Validation/Validator.php @@ -36,9 +36,10 @@ public function setArgs(ArgumentSet $args): void /** * Retrieve the value of an argument. * - * @param string $key The key of the argument, may use dot notation to get nested values. - * @param mixed|null $default Returned in case the argument is not present. - * @return mixed The value of the argument or the default. + * @param string $key the key of the argument, may use dot notation to get nested values + * @param mixed|null $default returned in case the argument is not present + * + * @return mixed the value of the argument or the default */ protected function arg(string $key, $default = null) { diff --git a/src/Validation/ValidatorDirective.php b/src/Validation/ValidatorDirective.php index 4fc74e0f75..491bb16bc9 100644 --- a/src/Validation/ValidatorDirective.php +++ b/src/Validation/ValidatorDirective.php @@ -63,7 +63,7 @@ public function attributes(): array protected function validator(): Validator { - if ($this->validator === null) { + if (null === $this->validator) { /** @var \Nuwave\Lighthouse\Validation\Validator $validator */ $validator = app( // We precomputed and validated the full class name at schema build time @@ -89,7 +89,7 @@ public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefiniti if ($this->directiveHasArgument('class')) { $classCandidate = $this->directiveArgValue('class'); } else { - $classCandidate = $typeDefinition->name->value.'Validator'; + $classCandidate = $typeDefinition->name->value . 'Validator'; } $this->setFullClassnameOnDirective($typeDefinition, $classCandidate); @@ -104,9 +104,9 @@ public function manipulateFieldDefinition( $classCandidate = $this->directiveArgValue('class'); } else { $classCandidate = $parentType->name->value - .'\\' - .ucfirst($fieldDefinition->name->value) - .'Validator'; + . '\\' + . ucfirst($fieldDefinition->name->value) + . 'Validator'; } $this->setFullClassnameOnDirective($fieldDefinition, $classCandidate); @@ -128,7 +128,7 @@ protected function setFullClassnameOnDirective(Node &$definition, string $classC if ($directive->name->value === $this->name()) { $directive->arguments = ASTHelper::mergeUniqueNodeList( $directive->arguments, - [Parser::argument('class: "'.addslashes($validatorClass).'"')], + [Parser::argument('class: "' . addslashes($validatorClass) . '"')], true ); } diff --git a/src/WhereConditions/Operator.php b/src/WhereConditions/Operator.php index fd07d3952d..1d6247419a 100644 --- a/src/WhereConditions/Operator.php +++ b/src/WhereConditions/Operator.php @@ -32,6 +32,7 @@ public function defaultHasOperator(): string; * * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder * @param array $whereConditions + * * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder */ public function applyConditions($builder, array $whereConditions, string $boolean); diff --git a/src/WhereConditions/SQLOperator.php b/src/WhereConditions/SQLOperator.php index 9f214303c2..7244250d2a 100644 --- a/src/WhereConditions/SQLOperator.php +++ b/src/WhereConditions/SQLOperator.php @@ -85,7 +85,7 @@ public function applyConditions($builder, array $whereConditions, string $boolea $operator = $whereConditions['operator']; $arity = $this->operatorArity($operator); - if ($arity === 3) { + if (3 === $arity) { // Usually, the operator is passed as the second argument to the condition // method, e.g. ->where('some_col', '=', $value) $args[] = $operator; diff --git a/src/WhereConditions/WhereConditionsBaseDirective.php b/src/WhereConditions/WhereConditionsBaseDirective.php index 4e1e8393b4..5da8a0b4bb 100644 --- a/src/WhereConditions/WhereConditionsBaseDirective.php +++ b/src/WhereConditions/WhereConditionsBaseDirective.php @@ -34,6 +34,7 @@ public function __construct(Operator $operator) /** * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder * @param array $whereConditions + * * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder */ public function handleWhereConditions( @@ -134,7 +135,7 @@ public function manipulateArgDefinition( ObjectTypeDefinitionNode &$parentType ): void { if ($this->hasAllowedColumns()) { - $restrictedWhereConditionsName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).$this->generatedInputSuffix(); + $restrictedWhereConditionsName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType) . $this->generatedInputSuffix(); $argDefinition->type = Parser::namedType($restrictedWhereConditionsName); $allowedColumnsEnumName = $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType); @@ -168,7 +169,7 @@ protected static function assertValidColumnReference(string $column): void // - must not start with a digit, dot or hyphen // - must contain only alphanumerics, digits, underscores, dots, hyphens or JSON references $match = \Safe\preg_match('/^(?![0-9.-])([A-Za-z0-9_.-]|->)*$/', $column); - if ($match === 0) { + if (0 === $match) { throw new Error( self::invalidColumnName($column) ); @@ -182,12 +183,13 @@ protected static function assertValidColumnReference(string $column): void * example when multiple tables with a column "id" are involved. * * @param array $condition + * * @return array */ protected function prefixConditionWithTableName(array $condition, Model $model): array { if ($column = $condition['column'] ?? null) { - $condition['column'] = $model->getTable().'.'.$column; + $condition['column'] = $model->getTable() . '.' . $column; } return $condition; diff --git a/src/WhereConditions/WhereConditionsServiceProvider.php b/src/WhereConditions/WhereConditionsServiceProvider.php index b3cb88f737..1d1c1af7b5 100644 --- a/src/WhereConditions/WhereConditionsServiceProvider.php +++ b/src/WhereConditions/WhereConditionsServiceProvider.php @@ -67,14 +67,14 @@ function (ManipulateAST $manipulateAST): void { public static function createWhereConditionsInputType(string $name, string $description, string $columnType): InputObjectTypeDefinitionNode { - $hasRelationInputName = $name.self::DEFAULT_WHERE_RELATION_CONDITIONS; + $hasRelationInputName = $name . self::DEFAULT_WHERE_RELATION_CONDITIONS; /** @var \Nuwave\Lighthouse\WhereConditions\Operator $operator */ $operator = app(Operator::class); $operatorName = Parser::enumTypeDefinition( - $operator->enumDefinition() - ) + $operator->enumDefinition() + ) ->name ->value; $operatorDefault = $operator->default(); @@ -106,15 +106,15 @@ public static function createWhereConditionsInputType(string $name, string $desc public static function createHasConditionsInputType(string $name, string $description): InputObjectTypeDefinitionNode { - $hasRelationInputName = $name.self::DEFAULT_WHERE_RELATION_CONDITIONS; + $hasRelationInputName = $name . self::DEFAULT_WHERE_RELATION_CONDITIONS; $defaultHasAmount = self::DEFAULT_HAS_AMOUNT; /** @var \Nuwave\Lighthouse\WhereConditions\Operator $operator */ $operator = app(Operator::class); $operatorName = Parser::enumTypeDefinition( - $operator->enumDefinition() - ) + $operator->enumDefinition() + ) ->name ->value; $operatorDefault = $operator->defaultHasOperator(); diff --git a/src/WhereConditions/WhereHasConditionsDirective.php b/src/WhereConditions/WhereHasConditionsDirective.php index 63c3d3a384..1a31d10caa 100644 --- a/src/WhereConditions/WhereHasConditionsDirective.php +++ b/src/WhereConditions/WhereHasConditionsDirective.php @@ -52,7 +52,7 @@ public function handleBuilder($builder, $value): object } if (! $builder instanceof EloquentBuilder) { - throw new Exception('Can not get model from builder of class: '.get_class($builder)); + throw new Exception('Can not get model from builder of class: ' . get_class($builder)); } $model = $builder->getModel(); diff --git a/src/lighthouse.php b/src/lighthouse.php index 8f732fc973..3a4c3d3ef6 100644 --- a/src/lighthouse.php +++ b/src/lighthouse.php @@ -1,7 +1,6 @@ env('LIGHTHOUSE_CACHE_ENABLE', env('APP_ENV') !== 'local'), + 'enable' => env('LIGHTHOUSE_CACHE_ENABLE', 'local' !== env('APP_ENV')), /* * Allowed values: @@ -399,13 +398,13 @@ ], 'pusher' => [ 'driver' => 'pusher', - 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@pusher', + 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class . '@pusher', 'connection' => 'pusher', ], 'echo' => [ 'driver' => 'echo', 'connection' => env('LIGHTHOUSE_SUBSCRIPTION_REDIS_CONNECTION', 'default'), - 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@echoRoutes', + 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class . '@echoRoutes', ], ], @@ -463,5 +462,4 @@ */ 'entities_resolver_namespace' => 'App\\GraphQL\\Entities', ], - ]; diff --git a/tests/Console/CacheCommandTest.php b/tests/Console/CacheCommandTest.php index 695cfb9a99..0485273ede 100644 --- a/tests/Console/CacheCommandTest.php +++ b/tests/Console/CacheCommandTest.php @@ -51,7 +51,7 @@ public function testCacheVersion1(): void $cache = $this->app->make(CacheRepository::class); $this->assertFalse($cache->has($key)); - $this->commandTester(new CacheCommand)->execute([]); + $this->commandTester(new CacheCommand())->execute([]); $this->assertTrue($cache->has($key)); $this->assertInstanceOf(DocumentAST::class, $cache->get($key)); @@ -66,7 +66,7 @@ public function testCacheVersion2(): void $path = $this->schemaCachePath(); $this->assertFalse($filesystem->exists($path)); - $this->commandTester(new CacheCommand)->execute([]); + $this->commandTester(new CacheCommand())->execute([]); $this->assertTrue($filesystem->exists($path)); $this->assertInstanceOf(DocumentAST::class, DocumentAST::fromArray(require $path)); @@ -77,6 +77,6 @@ public function testCacheVersionUnknown(): void $this->config->set('lighthouse.cache.version', 3); $this->expectException(UnknownCacheVersionException::class); - $this->commandTester(new CacheCommand)->execute([]); + $this->commandTester(new CacheCommand())->execute([]); } } diff --git a/tests/Console/IdeHelperCommandTest.php b/tests/Console/IdeHelperCommandTest.php index 21b29acd8d..b74132eda9 100644 --- a/tests/Console/IdeHelperCommandTest.php +++ b/tests/Console/IdeHelperCommandTest.php @@ -86,7 +86,7 @@ public function testGeneratesIdeHelperFiles(): void $ideHelper = \Safe\file_get_contents(IdeHelperCommand::phpIdeHelperPath()); $this->assertStringContainsString( - IdeHelperCommand::OPENING_PHP_TAG.IdeHelperCommand::GENERATED_NOTICE, + IdeHelperCommand::OPENING_PHP_TAG . IdeHelperCommand::GENERATED_NOTICE, $ideHelper ); } diff --git a/tests/Console/PrintFederationSchemaCommandTest.php b/tests/Console/PrintFederationSchemaCommandTest.php index 086e015f2c..28deb0c8c5 100644 --- a/tests/Console/PrintFederationSchemaCommandTest.php +++ b/tests/Console/PrintFederationSchemaCommandTest.php @@ -9,8 +9,8 @@ class PrintFederationSchemaCommandTest extends TestCase { - protected const SCHEMA_TYPE = /** @lang GraphQL */ - <<<'GRAPHQL' + protected const SCHEMA_TYPE /** @lang GraphQL */ + = <<<'GRAPHQL' type Foo @key(fields: "id") { id: ID! @external foo: String! @@ -18,8 +18,8 @@ class PrintFederationSchemaCommandTest extends TestCase GRAPHQL; - protected const SCHEMA_QUERY = /** @lang GraphQL */ - <<<'GRAPHQL' + protected const SCHEMA_QUERY /** @lang GraphQL */ + = <<<'GRAPHQL' type Query { foo: Int! } @@ -35,7 +35,7 @@ protected function getPackageProviders($app): array public function testPrintsSchemaAsGraphQLSDL(): void { - $this->schema = self::SCHEMA_TYPE.self::SCHEMA_QUERY; + $this->schema = self::SCHEMA_TYPE . self::SCHEMA_QUERY; $tester = $this->commandTester(new PrintSchemaCommand()); $tester->execute(['--federation' => true]); @@ -46,7 +46,7 @@ public function testPrintsSchemaAsGraphQLSDL(): void public function testWritesSchema(): void { - $this->schema = self::SCHEMA_TYPE.self::SCHEMA_QUERY; + $this->schema = self::SCHEMA_TYPE . self::SCHEMA_QUERY; Storage::fake(); $tester = $this->commandTester(new PrintSchemaCommand()); diff --git a/tests/DBTestCase.php b/tests/DBTestCase.php index e30c0ab564..1187e9a00a 100644 --- a/tests/DBTestCase.php +++ b/tests/DBTestCase.php @@ -7,8 +7,8 @@ abstract class DBTestCase extends TestCase { - const DEFAULT_CONNECTION = 'mysql'; - const ALTERNATE_CONNECTION = 'alternate'; + public const DEFAULT_CONNECTION = 'mysql'; + public const ALTERNATE_CONNECTION = 'alternate'; /** * Indicates if migrations ran. @@ -23,7 +23,7 @@ public function setUp(): void if (! static::$migrated) { $this->artisan('migrate:fresh', [ - '--path' => __DIR__.'/database/migrations', + '--path' => __DIR__ . '/database/migrations', '--realpath' => true, ]); @@ -38,7 +38,7 @@ public function setUp(): void DB::table($table->{$columnName})->truncate(); } - $this->withFactories(__DIR__.'/database/factories'); + $this->withFactories(__DIR__ . '/database/factories'); } protected function getEnvironmentSetUp($app): void @@ -49,8 +49,8 @@ protected function getEnvironmentSetUp($app): void $config = $app->make(ConfigRepository::class); $config->set('database.default', self::DEFAULT_CONNECTION); - $config->set('database.connections.'.self::DEFAULT_CONNECTION, $this->mysqlOptions()); - $config->set('database.connections.'.self::ALTERNATE_CONNECTION, $this->mysqlOptions()); + $config->set('database.connections.' . self::DEFAULT_CONNECTION, $this->mysqlOptions()); + $config->set('database.connections.' . self::ALTERNATE_CONNECTION, $this->mysqlOptions()); } /** diff --git a/tests/Integration/Defer/DeferDBTest.php b/tests/Integration/Defer/DeferDBTest.php index 4d0e5bf602..cd954bbb55 100644 --- a/tests/Integration/Defer/DeferDBTest.php +++ b/tests/Integration/Defer/DeferDBTest.php @@ -46,7 +46,7 @@ public function testDeferBelongsToFields(): void $queries = 0; DB::listen(function () use (&$queries): void { - $queries++; + ++$queries; }); $chunks = $this->streamGraphQL(/** @lang GraphQL */ ' @@ -100,7 +100,7 @@ public function testDeferNestedRelationshipFields(): void $queries = 0; DB::listen(function () use (&$queries): void { - $queries++; + ++$queries; }); $chunks = $this->streamGraphQL(/** @lang GraphQL */ ' @@ -174,7 +174,7 @@ public function testDeferNestedListFields(): void $queries = 0; DB::listen(function () use (&$queries): void { - $queries++; + ++$queries; }); $chunks = $this->streamGraphQL(/** @lang GraphQL */ ' diff --git a/tests/Integration/Defer/DeferIncludeSkipTest.php b/tests/Integration/Defer/DeferIncludeSkipTest.php index b923c60888..99c5fb46be 100644 --- a/tests/Integration/Defer/DeferIncludeSkipTest.php +++ b/tests/Integration/Defer/DeferIncludeSkipTest.php @@ -10,7 +10,7 @@ class DeferIncludeSkipTest extends TestCase protected $schema = /** @lang GraphQL */ ' directive @include(if: Boolean!) on FIELD directive @skip(if: Boolean!) on FIELD - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; protected function getPackageProviders($app): array { diff --git a/tests/Integration/Defer/DeferTest.php b/tests/Integration/Defer/DeferTest.php index 26f54291b7..93189c4b61 100644 --- a/tests/Integration/Defer/DeferTest.php +++ b/tests/Integration/Defer/DeferTest.php @@ -633,7 +633,7 @@ public function testThrowsIfTryingToDeferRootMutationFields(): void type Mutation { updateUser(name: String!): User @mock } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $this->graphQL(/** @lang GraphQL */ ' mutation UpdateUser { diff --git a/tests/Integration/ErrorTest.php b/tests/Integration/ErrorTest.php index 633ffb4ec6..330a550a51 100644 --- a/tests/Integration/ErrorTest.php +++ b/tests/Integration/ErrorTest.php @@ -130,7 +130,7 @@ public function testRethrowsInternalExceptions(): void public function testReturnsMultipleErrors(): void { - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' input TestInput { string: String! integer: Int! diff --git a/tests/Integration/Execution/ArgBuilderDirectiveTest.php b/tests/Integration/Execution/ArgBuilderDirectiveTest.php index ddcc9ca426..53f102fe0e 100644 --- a/tests/Integration/Execution/ArgBuilderDirectiveTest.php +++ b/tests/Integration/Execution/ArgBuilderDirectiveTest.php @@ -187,7 +187,7 @@ public function testAttachWhereBetweenFilterToQuery(): void $this->graphQL(/** @lang GraphQL */ ' { users( - createdBetween: ["'.$start.'", "'.$end.'"] + createdBetween: ["' . $start . '", "' . $end . '"] ) { id } @@ -222,8 +222,8 @@ public function testUseInputObjectsForWhereBetweenFilter(): void { users( created: { - start: "'.$start.'" - end: "'.$end.'" + start: "' . $start . '" + end: "' . $end . '" } ) { id @@ -253,7 +253,7 @@ public function testAttachWhereNotBetweenFilterToQuery(): void $this->graphQL(/** @lang GraphQL */ ' { users( - notCreatedBetween: ["'.$start.'", "'.$end.'"] + notCreatedBetween: ["' . $start . '", "' . $end . '"] ) { id } @@ -280,7 +280,7 @@ public function testAttachWhereClauseFilterToQuery(): void $this->graphQL(/** @lang GraphQL */ ' { - users(created_at: "'.$year.'") { + users(created_at: "' . $year . '") { id } } @@ -302,7 +302,7 @@ public function testOnlyProcessesFilledArguments(): void $this->graphQL(/** @lang GraphQL */ ' { - users(name: "'.$users->first()->name.'") { + users(name: "' . $users->first()->name . '") { id } } diff --git a/tests/Integration/Execution/DataLoader/RelationBatchLoaderTest.php b/tests/Integration/Execution/DataLoader/RelationBatchLoaderTest.php index baeb6a0dfd..253b6b9904 100644 --- a/tests/Integration/Execution/DataLoader/RelationBatchLoaderTest.php +++ b/tests/Integration/Execution/DataLoader/RelationBatchLoaderTest.php @@ -104,7 +104,7 @@ public function testBatchloadRelations(bool $batchloadRelations, int $expectedQu $queryCount = 0; DB::listen(function () use (&$queryCount): void { - $queryCount++; + ++$queryCount; }); $this @@ -152,7 +152,7 @@ public function testDoesNotBatchloadRelationsWithDifferentDatabaseConnections(): $queryCount = 0; DB::listen(function () use (&$queryCount): void { - $queryCount++; + ++$queryCount; }); $this @@ -204,7 +204,7 @@ public function testCombineEagerLoadsThatAreTheSame(): void $queryCount = 0; DB::listen(function () use (&$queryCount): void { - $queryCount++; + ++$queryCount; }); $this->graphQL(/** @lang GraphQL */ ' @@ -265,7 +265,7 @@ public function testSplitsEagerLoadsByScopes(): void $queryCount = 0; DB::listen(function () use (&$queryCount): void { - $queryCount++; + ++$queryCount; }); $this->graphQL(/** @lang GraphQL */ ' @@ -302,7 +302,7 @@ public function testSplitsEagerLoadsWithArguments(): void $queryCount = 0; DB::listen(function () use (&$queryCount): void { - $queryCount++; + ++$queryCount; }); $this->graphQL(/** @lang GraphQL */ ' @@ -514,7 +514,7 @@ public function testCombineEagerLoadsThatAreTheSameRecursively(): void $queries = 0; DB::listen(static function () use (&$queries): void { - $queries++; + ++$queries; }); $this diff --git a/tests/Integration/Execution/DataLoader/RelationCountBatchLoaderTest.php b/tests/Integration/Execution/DataLoader/RelationCountBatchLoaderTest.php index d529ed7077..3dcd2eb05c 100644 --- a/tests/Integration/Execution/DataLoader/RelationCountBatchLoaderTest.php +++ b/tests/Integration/Execution/DataLoader/RelationCountBatchLoaderTest.php @@ -68,14 +68,14 @@ public function testResolveBatchedCountsFromBatchedRequests(): void ->assertJson([ [ 'data' => [ - 'user' => [ + 'user' => [ 'tasks_count' => 3, ], ], ], [ 'data' => [ - 'user' => [ + 'user' => [ 'tasks_count' => 3, ], ], diff --git a/tests/Integration/Execution/MutationExecutor/BelongsToManyTest.php b/tests/Integration/Execution/MutationExecutor/BelongsToManyTest.php index aa57c1a31c..d15e290919 100644 --- a/tests/Integration/Execution/MutationExecutor/BelongsToManyTest.php +++ b/tests/Integration/Execution/MutationExecutor/BelongsToManyTest.php @@ -105,7 +105,7 @@ class BelongsToManyTest extends DBTestCase id: ID! # role ID meta: String } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testSyncWithoutDetaching(): void { diff --git a/tests/Integration/Execution/MutationExecutor/BelongsToTest.php b/tests/Integration/Execution/MutationExecutor/BelongsToTest.php index ea79dae300..a7fecddb25 100644 --- a/tests/Integration/Execution/MutationExecutor/BelongsToTest.php +++ b/tests/Integration/Execution/MutationExecutor/BelongsToTest.php @@ -78,7 +78,7 @@ class BelongsToTest extends DBTestCase disconnect: Boolean delete: Boolean } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateAndConnectWithBelongsTo(): void { @@ -777,7 +777,7 @@ public function testUpsertAcrossTwoNestedBelongsToRelations(): void input UpsertRoleInput { name: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $this->graphQL(/** @lang GraphQL */ ' mutation { @@ -859,7 +859,7 @@ public function testUpsertAcrossTwoNestedBelongsToRelationsAndOverrideExistingMo input UpsertRoleUsersRelation { sync: [ID!] } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; // Create the first User with a Role. $this->graphQL(/** @lang GraphQL */ ' @@ -995,7 +995,7 @@ public function testCreateMultipleBelongsToThatDontExistYet(): void id: ID! name: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $this->graphQL(/** @lang GraphQL */ ' mutation { @@ -1092,7 +1092,7 @@ public function testCreateMultipleBelongsToThatDontExistYetWithExistingRecords() id: ID name: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $query = /** @lang GraphQL */ ' mutation { diff --git a/tests/Integration/Execution/MutationExecutor/HasManyTest.php b/tests/Integration/Execution/MutationExecutor/HasManyTest.php index f675350a99..53dbcf8620 100644 --- a/tests/Integration/Execution/MutationExecutor/HasManyTest.php +++ b/tests/Integration/Execution/MutationExecutor/HasManyTest.php @@ -81,7 +81,7 @@ class HasManyTest extends DBTestCase id: ID name: String } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateWithNewHasMany(): void { @@ -653,7 +653,7 @@ public function testUpsertAcrossPivotTableOverrideExistingModel(): void input UpsertRoleUsersRelation { sync: [ID!] } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; // Create the first User with a Role. $this->graphQL(/** @lang GraphQL */ ' diff --git a/tests/Integration/Execution/MutationExecutor/HasOneTest.php b/tests/Integration/Execution/MutationExecutor/HasOneTest.php index 2fcb0d3450..ca88d9d1d6 100644 --- a/tests/Integration/Execution/MutationExecutor/HasOneTest.php +++ b/tests/Integration/Execution/MutationExecutor/HasOneTest.php @@ -76,7 +76,7 @@ class HasOneTest extends DBTestCase id: ID title: String } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateWithNewHasOne(): void { @@ -288,18 +288,18 @@ public function testUpdateWithNewHasOne(string $action): void } } GRAPHQL - )->assertJson([ - 'data' => [ - "${action}Task" => [ + )->assertJson([ + 'data' => [ + "${action}Task" => [ + 'id' => '1', + 'name' => 'foo', + 'post' => [ 'id' => '1', - 'name' => 'foo', - 'post' => [ - 'id' => '1', - 'title' => 'bar', - ], + 'title' => 'bar', ], ], - ]); + ], + ]); } /** diff --git a/tests/Integration/Execution/MutationExecutor/MorphManyTest.php b/tests/Integration/Execution/MutationExecutor/MorphManyTest.php index b80745e9f3..d7e195a969 100644 --- a/tests/Integration/Execution/MutationExecutor/MorphManyTest.php +++ b/tests/Integration/Execution/MutationExecutor/MorphManyTest.php @@ -80,7 +80,7 @@ class MorphManyTest extends DBTestCase id: ID url: String } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateWithNewMorphMany(): void { diff --git a/tests/Integration/Execution/MutationExecutor/MorphOneTest.php b/tests/Integration/Execution/MutationExecutor/MorphOneTest.php index e8e22949a2..a08d7f375c 100644 --- a/tests/Integration/Execution/MutationExecutor/MorphOneTest.php +++ b/tests/Integration/Execution/MutationExecutor/MorphOneTest.php @@ -75,7 +75,7 @@ class MorphOneTest extends DBTestCase id: ID url: String } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateWithNewMorphOne(): void { diff --git a/tests/Integration/Execution/MutationExecutor/MorphToManyTest.php b/tests/Integration/Execution/MutationExecutor/MorphToManyTest.php index 1b4d753c57..c44e035337 100644 --- a/tests/Integration/Execution/MutationExecutor/MorphToManyTest.php +++ b/tests/Integration/Execution/MutationExecutor/MorphToManyTest.php @@ -57,7 +57,7 @@ class MorphToManyTest extends DBTestCase id: ID! name: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testCreateATaskWithExistingTagsByUsingConnect(): void { diff --git a/tests/Integration/Execution/MutationExecutor/MorphToTest.php b/tests/Integration/Execution/MutationExecutor/MorphToTest.php index 2486776e79..6b38452097 100644 --- a/tests/Integration/Execution/MutationExecutor/MorphToTest.php +++ b/tests/Integration/Execution/MutationExecutor/MorphToTest.php @@ -69,7 +69,7 @@ class MorphToTest extends DBTestCase disconnect: Boolean delete: Boolean } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testConnectsMorphTo(): void { diff --git a/tests/Integration/Federation/FederationEntitiesTest.php b/tests/Integration/Federation/FederationEntitiesTest.php index 292f61d9bd..611f3c8c38 100644 --- a/tests/Integration/Federation/FederationEntitiesTest.php +++ b/tests/Integration/Federation/FederationEntitiesTest.php @@ -63,7 +63,7 @@ public function testThrowsWhenTypeIsUnknown(): void id: ID! @external foo: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $response = $this->graphQL(/** @lang GraphQL */ ' { @@ -92,7 +92,7 @@ public function testThrowsWhenNoKeySelectionIsSatisfied(): void id: ID! @external foo: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $response = $this->graphQL(/** @lang GraphQL */ ' { @@ -121,7 +121,7 @@ public function testThrowsWhenMissingResolver(): void id: ID! @external foo: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $response = $this->graphQL(/** @lang GraphQL */ ' { diff --git a/tests/Integration/Federation/FederationSchemaTest.php b/tests/Integration/Federation/FederationSchemaTest.php index 59c94b0913..ccfe245888 100644 --- a/tests/Integration/Federation/FederationSchemaTest.php +++ b/tests/Integration/Federation/FederationSchemaTest.php @@ -33,7 +33,7 @@ public function testServiceQueryShouldReturnValidSdl(): void GRAPHQL; - $this->schema = $foo.$query; + $this->schema = $foo . $query; $sdl = $this->_serviceSdl(); diff --git a/tests/Integration/FileUploadTest.php b/tests/Integration/FileUploadTest.php index d51b2d7909..8aa6299a4b 100644 --- a/tests/Integration/FileUploadTest.php +++ b/tests/Integration/FileUploadTest.php @@ -14,7 +14,7 @@ class FileUploadTest extends TestCase type Mutation { upload(file: Upload!): Boolean } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; /** * https://github.com/jaydenseric/graphql-multipart-request-spec#single-file. @@ -22,7 +22,7 @@ class FileUploadTest extends TestCase public function testResolvesUploadViaMultipartRequest(): void { $operations = [ - 'query' => /** @lang GraphQL */' + 'query' => /** @lang GraphQL */ ' mutation ($file: Upload!) { upload(file: $file) } diff --git a/tests/Integration/GlobalErrorRendererTest.php b/tests/Integration/GlobalErrorRendererTest.php index f73a80fc85..dfc36ee84b 100644 --- a/tests/Integration/GlobalErrorRendererTest.php +++ b/tests/Integration/GlobalErrorRendererTest.php @@ -10,8 +10,8 @@ class GlobalErrorRendererTest extends TestCase { - const MESSAGE = 'foo'; - const EXTENSIONS_CONTENT = ['bar' => 'baz']; + public const MESSAGE = 'foo'; + public const EXTENSIONS_CONTENT = ['bar' => 'baz']; protected function getEnvironmentSetUp($app): void { diff --git a/tests/Integration/GlobalId/NodeDirectiveDBTest.php b/tests/Integration/GlobalId/NodeDirectiveDBTest.php index 23c9e64401..3be2d8d6fe 100644 --- a/tests/Integration/GlobalId/NodeDirectiveDBTest.php +++ b/tests/Integration/GlobalId/NodeDirectiveDBTest.php @@ -178,7 +178,7 @@ public function resolveNode(int $id): array */ public function testResolveModelsNodes(string $directiveDefinition): void { - $this->schema .= /** @lang GraphQL */" + $this->schema .= /** @lang GraphQL */ " type User {$directiveDefinition} { name: String! } diff --git a/tests/Integration/GraphQLTest.php b/tests/Integration/GraphQLTest.php index de49be6b38..d3bfacaf2b 100644 --- a/tests/Integration/GraphQLTest.php +++ b/tests/Integration/GraphQLTest.php @@ -35,7 +35,7 @@ public function testResolvesQueryViaGetRequest(): void $this ->getJson( 'graphql?' - .http_build_query( + . http_build_query( [ 'query' => /** @lang GraphQL */ ' { diff --git a/tests/Integration/LifecycleEventsTest.php b/tests/Integration/LifecycleEventsTest.php index 0551c6dd7c..25477232ee 100644 --- a/tests/Integration/LifecycleEventsTest.php +++ b/tests/Integration/LifecycleEventsTest.php @@ -31,7 +31,7 @@ public function testDispatchesProperLifecycleEvents(): void if (Str::startsWith($name, 'Nuwave\\Lighthouse')) { // We only fire class-based events, so the payload // always holds exactly a single class instance. - $events [] = $payload[0]; + $events[] = $payload[0]; } }); diff --git a/tests/Integration/OrderBy/OrderByDirectiveTest.php b/tests/Integration/OrderBy/OrderByDirectiveTest.php index ab4c3362bf..67288fc9c1 100644 --- a/tests/Integration/OrderBy/OrderByDirectiveTest.php +++ b/tests/Integration/OrderBy/OrderByDirectiveTest.php @@ -22,9 +22,9 @@ public function testGeneratesInputWithFullyQualifiedName(): void $schema = $this->buildSchema($schemaString); $input = $schema->getType( 'Query' // Parent - .'Foo' // Field - .'OrderBy' // Arg - .'OrderByClause' // Suffix + . 'Foo' // Field + . 'OrderBy' // Arg + . 'OrderByClause' // Suffix ); $this->assertInstanceOf(InputObjectType::class, $input); } @@ -49,34 +49,34 @@ public function testGeneratesInputWithFullyQualifiedNameUsingRelations(): void $clause = $schema->getType( 'Query' // Parent - .'Foo' // Field - .'OrderBy' // Arg - .'RelationOrderByClause' // Suffix + . 'Foo' // Field + . 'OrderBy' // Arg + . 'RelationOrderByClause' // Suffix ); $this->assertInstanceOf(InputObjectType::class, $clause); $foo = $schema->getType( 'Query' // Parent - .'Foo' // Field - .'OrderBy' // Arg - .'Foo' // Relation + . 'Foo' // Field + . 'OrderBy' // Arg + . 'Foo' // Relation ); $this->assertInstanceOf(InputObjectType::class, $foo); $baz = $schema->getType( 'Query' // Parent - .'Foo' // Field - .'OrderBy' // Arg - .'Baz' // Relation + . 'Foo' // Field + . 'OrderBy' // Arg + . 'Baz' // Relation ); $this->assertInstanceOf(InputObjectType::class, $baz); $bazEnum = $schema->getType( 'Query' // Parent - .'Foo' // Field - .'OrderBy' // Arg - .'Baz' // Relation - .'Column' // Suffix + . 'Foo' // Field + . 'OrderBy' // Arg + . 'Baz' // Relation + . 'Column' // Suffix ); $this->assertInstanceOf(EnumType::class, $bazEnum); } diff --git a/tests/Integration/Pagination/PaginateDirectiveDBTest.php b/tests/Integration/Pagination/PaginateDirectiveDBTest.php index 98e2b365fb..0a8c6c1a93 100644 --- a/tests/Integration/Pagination/PaginateDirectiveDBTest.php +++ b/tests/Integration/Pagination/PaginateDirectiveDBTest.php @@ -65,7 +65,7 @@ public function testSpecifyCustomBuilder(): void } type Query { - users: [User!]! @paginate(builder: "'.$this->qualifyTestResolver('builder').'") + users: [User!]! @paginate(builder: "' . $this->qualifyTestResolver('builder') . '") } '; diff --git a/tests/Integration/RouteRegistrationTest.php b/tests/Integration/RouteRegistrationTest.php index e9f970c460..b9c071a735 100644 --- a/tests/Integration/RouteRegistrationTest.php +++ b/tests/Integration/RouteRegistrationTest.php @@ -13,6 +13,7 @@ class RouteRegistrationTest extends TestCase * Get package providers. * * @param \Illuminate\Foundation\Application $app + * * @return array */ protected function getPackageProviders($app): array diff --git a/tests/Integration/Schema/Directives/AggregateDirectiveTest.php b/tests/Integration/Schema/Directives/AggregateDirectiveTest.php index 0f446e2ade..52b45549c6 100644 --- a/tests/Integration/Schema/Directives/AggregateDirectiveTest.php +++ b/tests/Integration/Schema/Directives/AggregateDirectiveTest.php @@ -121,7 +121,7 @@ public function testSumRelationEagerLoad(): void $queries = 0; DB::listen(static function () use (&$queries): void { - $queries++; + ++$queries; }); $this->graphQL(/** @lang GraphQL */ ' diff --git a/tests/Integration/Schema/Directives/AllDirectiveTest.php b/tests/Integration/Schema/Directives/AllDirectiveTest.php index c01a272e04..445c9d34ac 100644 --- a/tests/Integration/Schema/Directives/AllDirectiveTest.php +++ b/tests/Integration/Schema/Directives/AllDirectiveTest.php @@ -14,7 +14,7 @@ public function testGetAllModelsAsRootField(): void $count = 2; factory(User::class, $count)->create(); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type User { id: ID! } @@ -38,7 +38,7 @@ public function testExplicitModelName(): void $count = 2; factory(User::class, $count)->create(); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Foo { id: ID! } @@ -62,7 +62,7 @@ public function testRenamedModelWithModelDirective(): void $count = 2; factory(User::class, $count)->create(); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Foo @model(class: "User") { id: ID! } @@ -88,7 +88,7 @@ public function testGetAllAsNestedField(): void 'task_id' => 1, ]); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type User { posts: [Post!]! @all } @@ -143,7 +143,7 @@ public function testGetAllModelsFiltered(): void $users = factory(User::class, 3)->create(); $userName = $users->first()->name; - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type User { id: ID! name: String! @@ -175,7 +175,7 @@ public function testSpecifyCustomBuilder(): void } type Query { - users: [User!]! @all(builder: "'.$this->qualifyTestResolver('builder').'") + users: [User!]! @all(builder: "' . $this->qualifyTestResolver('builder') . '") } '; diff --git a/tests/Integration/Schema/Directives/BuilderDirectiveTest.php b/tests/Integration/Schema/Directives/BuilderDirectiveTest.php index 50b3c4dc38..52e6b8bfea 100644 --- a/tests/Integration/Schema/Directives/BuilderDirectiveTest.php +++ b/tests/Integration/Schema/Directives/BuilderDirectiveTest.php @@ -12,7 +12,7 @@ public function testCallsCustomBuilderMethod(): void $this->schema = /** @lang GraphQL */ ' type Query { users( - limit: Int @builder(method: "'.$this->qualifyTestResolver('limit').'") + limit: Int @builder(method: "' . $this->qualifyTestResolver('limit') . '") ): [User!]! @all } @@ -36,7 +36,7 @@ public function testCallsCustomBuilderMethodOnFieldWithValue(): void { $this->schema = /** @lang GraphQL */ ' type Query { - users: [User!]! @all @builder(method: "'.$this->qualifyTestResolver('limit').'" value: 1) + users: [User!]! @all @builder(method: "' . $this->qualifyTestResolver('limit') . '" value: 1) } type User { @@ -59,7 +59,7 @@ public function testCallsCustomBuilderMethodOnFieldWithoutValue(): void { $this->schema = /** @lang GraphQL */ ' type Query { - users: [User!]! @all @builder(method: "'.$this->qualifyTestResolver('limit').'") + users: [User!]! @all @builder(method: "' . $this->qualifyTestResolver('limit') . '") } type User { @@ -80,6 +80,7 @@ public function testCallsCustomBuilderMethodOnFieldWithoutValue(): void /** * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + * * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder */ public function limit(object $builder, int $value = 2): object diff --git a/tests/Integration/Schema/Directives/CacheDirectiveTest.php b/tests/Integration/Schema/Directives/CacheDirectiveTest.php index a49b830844..a22cd8b44d 100644 --- a/tests/Integration/Schema/Directives/CacheDirectiveTest.php +++ b/tests/Integration/Schema/Directives/CacheDirectiveTest.php @@ -268,7 +268,7 @@ public function testCacheHasManyResolver(): void $query = /** @lang GraphQL */ ' { - user(id: '.$user->getKey().') { + user(id: ' . $user->getKey() . ') { id name posts(first: 3) { @@ -283,7 +283,7 @@ public function testCacheHasManyResolver(): void $dbQueryCountForPost = 0; DB::listen(function (QueryExecuted $query) use (&$dbQueryCountForPost): void { if (Str::contains($query->sql, 'select * from `posts`')) { - $dbQueryCountForPost++; + ++$dbQueryCountForPost; } }); @@ -332,7 +332,7 @@ public function testAttachTagsToCache(): void $query = /** @lang GraphQL */ ' { - user(id: '.$user->getKey().') { + user(id: ' . $user->getKey() . ') { id name posts(first: 3) { @@ -347,7 +347,7 @@ public function testAttachTagsToCache(): void $dbQueryCountForPost = 0; DB::listen(function (QueryExecuted $query) use (&$dbQueryCountForPost): void { if (Str::contains($query->sql, 'select * from `posts`')) { - $dbQueryCountForPost++; + ++$dbQueryCountForPost; } }); diff --git a/tests/Integration/Schema/Directives/CountDirectiveDBTest.php b/tests/Integration/Schema/Directives/CountDirectiveDBTest.php index bcbc9b4746..c27fd9da54 100644 --- a/tests/Integration/Schema/Directives/CountDirectiveDBTest.php +++ b/tests/Integration/Schema/Directives/CountDirectiveDBTest.php @@ -96,7 +96,7 @@ public function testCountRelationAndEagerLoadsTheCount(): void $queries = 0; DB::listen(function () use (&$queries): void { - $queries++; + ++$queries; }); $this->graphQL(/** @lang GraphQL */ ' diff --git a/tests/Integration/Schema/Directives/EqDirectiveTest.php b/tests/Integration/Schema/Directives/EqDirectiveTest.php index 7418958e66..8a422d8890 100644 --- a/tests/Integration/Schema/Directives/EqDirectiveTest.php +++ b/tests/Integration/Schema/Directives/EqDirectiveTest.php @@ -111,7 +111,7 @@ public function testAttachEqFilterFromField(): void { $users = factory(User::class, 2)->create(); - $this->schema = /** @lang GraphQL */" + $this->schema = /** @lang GraphQL */ " type User { id: ID! } @@ -136,7 +136,7 @@ public function testEqOnFieldRequiresValue(): void { $this->expectException(DefinitionException::class); - $this->buildSchema(/** @lang GraphQL */' + $this->buildSchema(/** @lang GraphQL */ ' type User { id: ID! } @@ -151,7 +151,7 @@ public function testEqOnFieldRequiresKey(): void { $this->expectException(DefinitionException::class); - $this->buildSchema(/** @lang GraphQL */' + $this->buildSchema(/** @lang GraphQL */ ' type User { id: ID! } diff --git a/tests/Integration/Schema/Directives/EventDirectiveTest.php b/tests/Integration/Schema/Directives/EventDirectiveTest.php index 6389de6520..2e4b9776b3 100644 --- a/tests/Integration/Schema/Directives/EventDirectiveTest.php +++ b/tests/Integration/Schema/Directives/EventDirectiveTest.php @@ -43,8 +43,8 @@ public function testDispatchesAnEvent(): void ]); Event::assertDispatched(CompanyWasCreatedEvent::class, function ($event): bool { - return $event->company->id === 1 - && $event->company->name === 'foo'; + return 1 === $event->company->id + && 'foo' === $event->company->name; }); } } diff --git a/tests/Integration/Schema/Directives/HasManyDirectiveTest.php b/tests/Integration/Schema/Directives/HasManyDirectiveTest.php index ace87099e0..ad9a3dcee2 100644 --- a/tests/Integration/Schema/Directives/HasManyDirectiveTest.php +++ b/tests/Integration/Schema/Directives/HasManyDirectiveTest.php @@ -512,12 +512,12 @@ public function testUsesEdgeTypeForRelayConnections(): void $tasks = Arr::first( $user['fields'], function (array $field): bool { - return $field['name'] === 'tasks'; + return 'tasks' === $field['name']; } ); $this->assertSame( $expectedConnectionName, - $tasks['type']/* TODO add back in in v6 ['ofType'] */['name'] + $tasks['type']/* TODO add back in in v6 ['ofType'] */ ['name'] ); } diff --git a/tests/Integration/Schema/Directives/HasOneDirectiveTest.php b/tests/Integration/Schema/Directives/HasOneDirectiveTest.php index 5c2b4ebf5a..95c5a86027 100644 --- a/tests/Integration/Schema/Directives/HasOneDirectiveTest.php +++ b/tests/Integration/Schema/Directives/HasOneDirectiveTest.php @@ -15,7 +15,7 @@ public function testQueryHasOneRelationship(): void // Creates a task and assigns it to this post $post = factory(Post::class)->create(); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Post { id: Int } diff --git a/tests/Integration/Schema/Directives/MorphManyDirectiveTest.php b/tests/Integration/Schema/Directives/MorphManyDirectiveTest.php index 7dfd42df1e..1e18305f2c 100644 --- a/tests/Integration/Schema/Directives/MorphManyDirectiveTest.php +++ b/tests/Integration/Schema/Directives/MorphManyDirectiveTest.php @@ -60,7 +60,7 @@ public function setUp(): void factory(Image::class)->create() ); - if ($image === false) { + if (false === $image) { throw new Exception('Failed to save Image'); } @@ -71,8 +71,8 @@ public function setUp(): void 'user_id' => $this->user->id, ]); $this->postImages = Collection::times( - $this->faker()->numberBetween(1, 10) - ) + $this->faker()->numberBetween(1, 10) + ) ->map(function () { $image = $this->post ->images() @@ -80,7 +80,7 @@ public function setUp(): void factory(Image::class)->create() ); - if ($image === false) { + if (false === $image) { throw new Exception('Failed to save Image'); } diff --git a/tests/Integration/Schema/Directives/MorphToManyDirectiveTest.php b/tests/Integration/Schema/Directives/MorphToManyDirectiveTest.php index 200173ae63..9e9309d2ed 100644 --- a/tests/Integration/Schema/Directives/MorphToManyDirectiveTest.php +++ b/tests/Integration/Schema/Directives/MorphToManyDirectiveTest.php @@ -167,7 +167,7 @@ public function testResolveMorphToManyUsingInterfaces(): void }); $this->schema = /** @lang GraphQL */ ' - interface Tag @interface(resolveType: "'.$this->qualifyTestResolver('resolveType').'") { + interface Tag @interface(resolveType: "' . $this->qualifyTestResolver('resolveType') . '") { id: ID! } diff --git a/tests/Integration/Schema/Directives/ThrottleDirectiveTest.php b/tests/Integration/Schema/Directives/ThrottleDirectiveTest.php index 73d51d1473..980a6ca5fc 100644 --- a/tests/Integration/Schema/Directives/ThrottleDirectiveTest.php +++ b/tests/Integration/Schema/Directives/ThrottleDirectiveTest.php @@ -102,7 +102,7 @@ static function () { public function testInlineLimiter(): void { - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Query { foo: Int @throttle(maxAttempts: 1) } diff --git a/tests/Integration/Schema/Directives/WithCountDirectiveTest.php b/tests/Integration/Schema/Directives/WithCountDirectiveTest.php index 36278a44e2..cd62566cdf 100644 --- a/tests/Integration/Schema/Directives/WithCountDirectiveTest.php +++ b/tests/Integration/Schema/Directives/WithCountDirectiveTest.php @@ -33,7 +33,7 @@ public function testEagerLoadsRelationCount(): void $queries = 0; DB::listen(function () use (&$queries): void { - $queries++; + ++$queries; }); $this->graphQL(/** @lang GraphQL */ ' diff --git a/tests/Integration/Schema/Directives/WithDirectiveTest.php b/tests/Integration/Schema/Directives/WithDirectiveTest.php index 18795db801..bec175b054 100644 --- a/tests/Integration/Schema/Directives/WithDirectiveTest.php +++ b/tests/Integration/Schema/Directives/WithDirectiveTest.php @@ -210,7 +210,7 @@ public function testEagerLoadsPolymorphicRelations(): void 'id' => "{$post1->id}", 'images' => $post1->images()->get() ->map(function (Image $image) { - return ['id' => "{$image->id}"]; + return ['id' => "{$image->id}"]; }), ], ], @@ -221,7 +221,7 @@ public function testEagerLoadsPolymorphicRelations(): void 'id' => "{$post2->id}", 'images' => $post2->images()->get() ->map(function (Image $image) { - return ['id' => "{$image->id}"]; + return ['id' => "{$image->id}"]; }), ], ], @@ -232,7 +232,7 @@ public function testEagerLoadsPolymorphicRelations(): void 'id' => "{$task->id}", 'images' => $task->images()->get() ->map(static function (Image $image): array { - return ['id' => "{$image->id}"]; + return ['id' => "{$image->id}"]; }), ], ], diff --git a/tests/Integration/Scout/SearchDirectiveTest.php b/tests/Integration/Scout/SearchDirectiveTest.php index a5f44c175c..0169477e3d 100644 --- a/tests/Integration/Scout/SearchDirectiveTest.php +++ b/tests/Integration/Scout/SearchDirectiveTest.php @@ -159,7 +159,7 @@ public function testSearchWithBuilder(): void type Query { posts( - input: PostsInput! @builder(method: "'.$this->qualifyTestResolver('customBuilderMethod').'") + input: PostsInput! @builder(method: "' . $this->qualifyTestResolver('customBuilderMethod') . '") search: String! @search ): [Post!]! @all } diff --git a/tests/Integration/SoftDeletes/SoftDeletesAndTrashedDirectiveTest.php b/tests/Integration/SoftDeletes/SoftDeletesAndTrashedDirectiveTest.php index 4cd9b010d1..aee6cb1224 100644 --- a/tests/Integration/SoftDeletes/SoftDeletesAndTrashedDirectiveTest.php +++ b/tests/Integration/SoftDeletes/SoftDeletesAndTrashedDirectiveTest.php @@ -35,7 +35,7 @@ public function testWithAllDirective(): void 'data' => [ 'tasks' => [ [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ], @@ -95,7 +95,7 @@ public function testNullDoesNothing(): void 'data' => [ 'tasks' => [ [ - 'id' => $leftoverTask->id, + 'id' => $leftoverTask->id, ], ], ], @@ -127,7 +127,7 @@ public function testWithFindDirective(): void ')->assertJson([ 'data' => [ 'task' => [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ]); @@ -141,7 +141,7 @@ public function testWithFindDirective(): void ')->assertJson([ 'data' => [ 'task' => [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ]); @@ -178,7 +178,7 @@ public function testWithPaginateDirective(): void $taskToRemove = $tasks[2]; $taskToRemove->delete(); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Task { id: ID! } @@ -201,7 +201,7 @@ public function testWithPaginateDirective(): void 'tasks' => [ 'data' => [ [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ], @@ -285,7 +285,7 @@ public function testNested(): void [ 'tasks' => [ [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ], @@ -310,7 +310,7 @@ public function testNested(): void [ 'tasks' => [ [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ], @@ -332,7 +332,7 @@ public function testNested(): void 'user' => [ 'tasks' => [ [ - 'id' => $taskToRemove->id, + 'id' => $taskToRemove->id, ], ], ], diff --git a/tests/Integration/Subscriptions/EchoBroadcaster/AuthorizeRequestsTest.php b/tests/Integration/Subscriptions/EchoBroadcaster/AuthorizeRequestsTest.php index d87c1e2175..173cdafabd 100644 --- a/tests/Integration/Subscriptions/EchoBroadcaster/AuthorizeRequestsTest.php +++ b/tests/Integration/Subscriptions/EchoBroadcaster/AuthorizeRequestsTest.php @@ -21,7 +21,7 @@ class AuthorizeRequestsTest extends TestCase type Subscription { taskUpdated(id: ID!): Task } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testEchoClientAuthorizesSuccessfully(): void { @@ -47,7 +47,7 @@ public function testEchoClientAuthorizesPresenceChannelForBackwardCompatibility( $channel = $response->json('extensions.lighthouse_subscriptions.channel'); $this ->postJson('graphql/subscriptions/auth', [ - 'channel_name' => 'presence-'.$channel, + 'channel_name' => 'presence-' . $channel, ]) ->assertSuccessful() ->assertJsonStructure([ @@ -64,7 +64,7 @@ public function testEchoClientAuthorizationFailsOtherThanPresenceChannel(): void $channel = $response->json('extensions.lighthouse_subscriptions.channel'); $this ->postJson('graphql/subscriptions/auth', [ - 'channel_name' => 'anything-before-'.$channel, + 'channel_name' => 'anything-before-' . $channel, ]) ->assertForbidden(); } @@ -76,7 +76,7 @@ public function testEchoClientAuthorizeFails(): void $channel = $response->json('extensions.lighthouse_subscriptions.channel'); $this ->postJson('graphql/subscriptions/auth', [ - 'channel_name' => $channel.'plain-wrong', + 'channel_name' => $channel . 'plain-wrong', ]) ->assertForbidden(); } diff --git a/tests/Integration/Subscriptions/SerializerTest.php b/tests/Integration/Subscriptions/SerializerTest.php index 736b30529c..9dfdeee9cf 100644 --- a/tests/Integration/Subscriptions/SerializerTest.php +++ b/tests/Integration/Subscriptions/SerializerTest.php @@ -18,7 +18,7 @@ public function testWillSerializeUserModelAndRetrieveItFromTheDatabaseWhenUnseri $user = factory(User::class)->create(); $serializer = new Serializer( - $contextFactory = new ContextFactory + $contextFactory = new ContextFactory() ); $request = new Request(); diff --git a/tests/Integration/Subscriptions/Storage/RedisStorageManagerTest.php b/tests/Integration/Subscriptions/Storage/RedisStorageManagerTest.php index f4ee53e6bf..9405d48897 100644 --- a/tests/Integration/Subscriptions/Storage/RedisStorageManagerTest.php +++ b/tests/Integration/Subscriptions/Storage/RedisStorageManagerTest.php @@ -14,7 +14,7 @@ class RedisStorageManagerTest extends TestCase use TestsRedis; use TestsSubscriptions; - protected $schema = /** @lang GraphQL */' + protected $schema = /** @lang GraphQL */ ' type Task { id: ID! name: String! @@ -24,7 +24,7 @@ class RedisStorageManagerTest extends TestCase taskUpdated(id: ID!): Task taskCreated: Task } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; public function testSubscriptionStoredWithPrefix(): void { @@ -35,7 +35,7 @@ public function testSubscriptionStoredWithPrefix(): void $this->assertStringStartsWith('private-lighthouse-', $channel); // internally when using the redis driver to access the keys there seems to be no prefix - $this->assertRedisHas('graphql.subscriber.'.$channel); + $this->assertRedisHas('graphql.subscriber.' . $channel); $this->assertRedisHas('graphql.topic.TASK_UPDATED'); // but in reality redis stores with a prefix @@ -54,11 +54,11 @@ public function testDeleteSubscriber(): void $channel = $response->json('extensions.lighthouse_subscriptions.channel'); // when it's the only subscriber to a topic, the topic gets deleted with the subscriber - $this->assertRedisHas('graphql.subscriber.'.$channel); + $this->assertRedisHas('graphql.subscriber.' . $channel); $this->assertRedisHas('graphql.topic.TASK_UPDATED'); $storage->deleteSubscriber($channel); - $this->assertRedisMissing('graphql.subscriber.'.$channel); + $this->assertRedisMissing('graphql.subscriber.' . $channel); $this->assertRedisMissing('graphql.topic.TASK_UPDATED'); // when there are multiple subscribers, the topic stays as long as there are subscribers diff --git a/tests/Integration/Subscriptions/SubscriptionTest.php b/tests/Integration/Subscriptions/SubscriptionTest.php index e5ee9675e8..c05e97ee7a 100644 --- a/tests/Integration/Subscriptions/SubscriptionTest.php +++ b/tests/Integration/Subscriptions/SubscriptionTest.php @@ -190,6 +190,7 @@ public function testWithExcludeEmpty(): void /** * @param array $args + * * @return array */ public function resolve($root, array $args): array diff --git a/tests/Integration/Tests/Integration/Auth/CanDirectiveDBTest.php b/tests/Integration/Tests/Integration/Auth/CanDirectiveDBTest.php index d8834805cd..aaa4091dff 100644 --- a/tests/Integration/Tests/Integration/Auth/CanDirectiveDBTest.php +++ b/tests/Integration/Tests/Integration/Auth/CanDirectiveDBTest.php @@ -225,7 +225,7 @@ public function testHandleMultipleModels(): void type Post { title: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $this->graphQL(/** @lang GraphQL */ ' mutation ($ids: [ID!]!) { @@ -388,7 +388,7 @@ public function testHandleMultipleModelsWithQuery(): void type Post { title: String! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $this->graphQL(/** @lang GraphQL */ ' mutation ($ids: [ID!]!) { diff --git a/tests/Integration/Validation/RulesDirectiveTest.php b/tests/Integration/Validation/RulesDirectiveTest.php index 26369b3c18..a9fc473ee9 100644 --- a/tests/Integration/Validation/RulesDirectiveTest.php +++ b/tests/Integration/Validation/RulesDirectiveTest.php @@ -266,7 +266,7 @@ public function testValidateApplyArgument(string $applyArgument): void $this->expectException(DefinitionException::class); $this->buildSchema(/** @lang GraphQL */ ' type Query { - foo(bar: ID @rules(apply: '.$applyArgument.')): ID + foo(bar: ID @rules(apply: ' . $applyArgument . ')): ID } '); } diff --git a/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php b/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php index 4451842b81..7abe5cda7c 100644 --- a/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php +++ b/tests/Integration/WhereConditions/WhereConditionsDirectiveTest.php @@ -354,7 +354,7 @@ public function testHasMixed(): void $commentTwo->comment = 'test'; $commentTwo->save(); - for ($i = 0; $i < 5; $i++) { + for ($i = 0; $i < 5; ++$i) { $commentBatch = new Comment(); $commentBatch->post_id = 9; $commentBatch->user_id = 2; @@ -470,7 +470,7 @@ public function testHasAmount(): void $user->posts()->saveMany(factory(Post::class, 2)->create()); }); - for ($i = 0; $i < 5; $i++) { + for ($i = 0; $i < 5; ++$i) { $commentBatchOne = new Comment(); $commentBatchOne->user_id = 1; $commentBatchOne->post_id = 3; @@ -478,7 +478,7 @@ public function testHasAmount(): void $commentBatchOne->save(); } - for ($i = 0; $i < 2; $i++) { + for ($i = 0; $i < 2; ++$i) { $commentBatchTwo = new Comment(); $commentBatchTwo->user_id = 1; $commentBatchTwo->post_id = 7; @@ -516,7 +516,7 @@ public function testHasOperator(): void $user->posts()->saveMany(factory(Post::class, 2)->create()); }); - for ($i = 0; $i < 5; $i++) { + for ($i = 0; $i < 5; ++$i) { $commentBatchOne = new Comment(); $commentBatchOne->user_id = 1; $commentBatchOne->post_id = 3; @@ -524,7 +524,7 @@ public function testHasOperator(): void $commentBatchOne->save(); } - for ($i = 0; $i < 6; $i++) { + for ($i = 0; $i < 6; ++$i) { $commentBatchTwo = new Comment(); $commentBatchTwo->user_id = 1; $commentBatchTwo->post_id = 7; @@ -914,7 +914,7 @@ public function testIgnoreNullCondition(): void public function testWhereConditionOnJSONColumn(): void { - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Location { id: Int! } diff --git a/tests/Laravel7ExceptionHandler.php b/tests/Laravel7ExceptionHandler.php index d85f73e1ff..8bcd1928ce 100644 --- a/tests/Laravel7ExceptionHandler.php +++ b/tests/Laravel7ExceptionHandler.php @@ -9,7 +9,6 @@ class Laravel7ExceptionHandler implements ExceptionHandler { public function report(Throwable $e) { - // } public function render($request, Throwable $e) diff --git a/tests/PreLaravel7ExceptionHandler.php b/tests/PreLaravel7ExceptionHandler.php index e55ad29653..44b60dffe4 100644 --- a/tests/PreLaravel7ExceptionHandler.php +++ b/tests/PreLaravel7ExceptionHandler.php @@ -9,7 +9,6 @@ class PreLaravel7ExceptionHandler implements ExceptionHandler { public function report(Exception $e) { - // } public function render($request, Exception $e) diff --git a/tests/SerializingArrayStore.php b/tests/SerializingArrayStore.php index 073748d7a0..03a606d786 100644 --- a/tests/SerializingArrayStore.php +++ b/tests/SerializingArrayStore.php @@ -21,6 +21,7 @@ class SerializingArrayStore extends ArrayStore * Retrieve an item from the cache by key. * * @param string $key + * * @return mixed The value or null */ public function get($key) @@ -33,7 +34,7 @@ public function get($key) $expiresAt = $item['expiresAt'] ?? 0; - if ($expiresAt !== 0 && $this->currentTime() > $expiresAt) { + if (0 !== $expiresAt && $this->currentTime() > $expiresAt) { $this->forget($key); return null; diff --git a/tests/TestCase.php b/tests/TestCase.php index cdb17b34e7..15c7b1d794 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -60,6 +60,7 @@ public function setUp(): void * Get package providers. * * @param \Illuminate\Foundation\Application $app + * * @return array> */ protected function getPackageProviders($app): array @@ -128,7 +129,8 @@ protected function getEnvironmentSetUp($app): void ]); $config->set('app.debug', true); - $config->set('lighthouse.debug', + $config->set( + 'lighthouse.debug', DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE // | Debug::RETHROW_INTERNAL_EXCEPTIONS @@ -192,7 +194,7 @@ protected function resolveApplicationExceptionHandler($app): void protected function buildSchemaWithPlaceholderQuery(string $schema = ''): Schema { return $this->buildSchema( - $schema.self::PLACEHOLDER_QUERY + $schema . self::PLACEHOLDER_QUERY ); } @@ -214,7 +216,7 @@ protected function buildSchema(string $schema): Schema */ protected function qualifyTestResolver(string $method = 'resolve'): string { - return addslashes(static::class).'@'.$method; + return addslashes(static::class) . '@' . $method; } /** diff --git a/tests/TestsRedis.php b/tests/TestsRedis.php index 83ca02d737..d34581b3d8 100644 --- a/tests/TestsRedis.php +++ b/tests/TestsRedis.php @@ -41,7 +41,7 @@ protected function getEnvironmentSetUp($app): void 'broadcasters' => [ 'echo' => [ 'driver' => 'echo', - 'routes' => SubscriptionRouter::class.'@echoRoutes', + 'routes' => SubscriptionRouter::class . '@echoRoutes', ], ], ]); diff --git a/tests/TestsSchemaCache.php b/tests/TestsSchemaCache.php index c579f606d7..0b8c24acc6 100644 --- a/tests/TestsSchemaCache.php +++ b/tests/TestsSchemaCache.php @@ -17,7 +17,7 @@ protected function setUpSchemaCache(): void protected function schemaCachePath(): string { - return __DIR__.'/storage/lighthouse-schema.php'; + return __DIR__ . '/storage/lighthouse-schema.php'; } protected function tearDownSchemaCache(): void diff --git a/tests/TestsSerialization.php b/tests/TestsSerialization.php index a7080b1639..b4f90f05aa 100644 --- a/tests/TestsSerialization.php +++ b/tests/TestsSerialization.php @@ -15,8 +15,7 @@ trait TestsSerialization { protected function fakeContextSerializer(Container $app): void { - $contextSerializer = new class implements ContextSerializer - { + $contextSerializer = new class() implements ContextSerializer { public function serialize(GraphQLContext $context) { return 'foo'; @@ -24,8 +23,7 @@ public function serialize(GraphQLContext $context) public function unserialize(string $context) { - return new class implements GraphQLContext - { + return new class() implements GraphQLContext { public function user() { return new User(); diff --git a/tests/Unit/Events/BuildSchemaStringTest.php b/tests/Unit/Events/BuildSchemaStringTest.php index 6d0682b240..3776d3fcf3 100644 --- a/tests/Unit/Events/BuildSchemaStringTest.php +++ b/tests/Unit/Events/BuildSchemaStringTest.php @@ -37,13 +37,13 @@ function (): string { } ); - $this->schema = /** @lang GraphQL */" + $this->schema = /** @lang GraphQL */ " type Query { foo: String @field(resolver: \"{$this->qualifyTestResolver('resolveFoo')}\") } "; - $queryForBaseSchema = /** @lang GraphQL */' + $queryForBaseSchema = /** @lang GraphQL */ ' { foo } @@ -54,7 +54,7 @@ function (): string { ], ]); - $queryForAdditionalSchema = /** @lang GraphQL */' + $queryForAdditionalSchema = /** @lang GraphQL */ ' { sayHello } diff --git a/tests/Unit/Execution/Arguments/ArgumentSetFactoryTest.php b/tests/Unit/Execution/Arguments/ArgumentSetFactoryTest.php index 8318847f48..49451ae896 100644 --- a/tests/Unit/Execution/Arguments/ArgumentSetFactoryTest.php +++ b/tests/Unit/Execution/Arguments/ArgumentSetFactoryTest.php @@ -75,9 +75,9 @@ public function testItsListsAllTheWayDown(): void } '; - $barValue = + $barValue // Level 1 - [ + = [ // Level 2 [ // Level 3 diff --git a/tests/Unit/Federation/SchemaValidatorTest.php b/tests/Unit/Federation/SchemaValidatorTest.php index 8609348566..cacc68a7cb 100644 --- a/tests/Unit/Federation/SchemaValidatorTest.php +++ b/tests/Unit/Federation/SchemaValidatorTest.php @@ -25,7 +25,7 @@ public function testHooksIntoValidateSchemaCommand(): void type Foo @key(fields: "not_defined_on_the_object_type") { id: ID! } - '.self::PLACEHOLDER_QUERY; + ' . self::PLACEHOLDER_QUERY; $tester = $this->commandTester(new ValidateSchemaCommand()); $this->expectException(FederationException::class); diff --git a/tests/Unit/GlobalId/GlobalIdDirectiveTest.php b/tests/Unit/GlobalId/GlobalIdDirectiveTest.php index 9e6174c260..b0f055f020 100644 --- a/tests/Unit/GlobalId/GlobalIdDirectiveTest.php +++ b/tests/Unit/GlobalId/GlobalIdDirectiveTest.php @@ -145,7 +145,7 @@ static function ($root, array $args): array { } ); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Query { foo( type: ID! @globalId(decode: TYPE) diff --git a/tests/Unit/GlobalId/GlobalIdTest.php b/tests/Unit/GlobalId/GlobalIdTest.php index 2b7a49f580..f5f91d8ecc 100644 --- a/tests/Unit/GlobalId/GlobalIdTest.php +++ b/tests/Unit/GlobalId/GlobalIdTest.php @@ -17,7 +17,7 @@ public function setUp(): void { parent::setUp(); - $this->globalIdResolver = new GlobalId; + $this->globalIdResolver = new GlobalId(); } public function testHandleGlobalIds(): void diff --git a/tests/Unit/Pagination/PaginateDirectiveTest.php b/tests/Unit/Pagination/PaginateDirectiveTest.php index befeb2242c..7db475d21c 100644 --- a/tests/Unit/Pagination/PaginateDirectiveTest.php +++ b/tests/Unit/Pagination/PaginateDirectiveTest.php @@ -454,7 +454,7 @@ public function testIsLimitedByMaxCountFromDirective(): void { config(['lighthouse.pagination.max_count' => 5]); - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type User { id: ID! name: String! diff --git a/tests/Unit/Schema/AST/ASTBuilderTest.php b/tests/Unit/Schema/AST/ASTBuilderTest.php index 2386b35262..76f4ec69af 100644 --- a/tests/Unit/Schema/AST/ASTBuilderTest.php +++ b/tests/Unit/Schema/AST/ASTBuilderTest.php @@ -184,7 +184,7 @@ public function testDoesNotAllowExtendingUndefinedTypes(): void '; $this->expectException(DefinitionException::class); - $this->expectExceptionMessage('Could not find a base definition Foo of kind '.NodeKind::OBJECT_TYPE_EXTENSION.' to extend.'); + $this->expectExceptionMessage('Could not find a base definition Foo of kind ' . NodeKind::OBJECT_TYPE_EXTENSION . ' to extend.'); $this->astBuilder->documentAST(); } @@ -271,7 +271,7 @@ public function testDoesNotAllowMergingNonMatchingTypes(): void '; $this->expectException(DefinitionException::class); - $this->expectExceptionMessage('The type extension Foo of kind '.NodeKind::INTERFACE_TYPE_EXTENSION.' can not extend a definition of kind '.NodeKind::OBJECT_TYPE_DEFINITION.'.'); + $this->expectExceptionMessage('The type extension Foo of kind ' . NodeKind::INTERFACE_TYPE_EXTENSION . ' can not extend a definition of kind ' . NodeKind::OBJECT_TYPE_DEFINITION . '.'); $this->astBuilder->documentAST(); } diff --git a/tests/Unit/Schema/AST/ASTHelperTest.php b/tests/Unit/Schema/AST/ASTHelperTest.php index 678b6f8a1f..a237d9fe13 100644 --- a/tests/Unit/Schema/AST/ASTHelperTest.php +++ b/tests/Unit/Schema/AST/ASTHelperTest.php @@ -183,7 +183,7 @@ public function testExtractDirectiveDefinitionAllowsAuxiliaryTypes(): void directive @foo on OBJECT scalar Bar GRAPHQL -) + ) ); } diff --git a/tests/Unit/Schema/DirectiveLocatorTest.php b/tests/Unit/Schema/DirectiveLocatorTest.php index 9e885865ae..6c034f9c91 100644 --- a/tests/Unit/Schema/DirectiveLocatorTest.php +++ b/tests/Unit/Schema/DirectiveLocatorTest.php @@ -62,8 +62,7 @@ public function testSkipsHydrationForNonBaseDirectives(): void foo: String @foo '); - $directive = new class implements FieldMiddleware - { + $directive = new class() implements FieldMiddleware { public static function definition(): string { return /** @lang GraphQL */ 'foo'; diff --git a/tests/Unit/Schema/Directives/BaseDirectiveTest.php b/tests/Unit/Schema/Directives/BaseDirectiveTest.php index abe8c25934..2ffee15113 100644 --- a/tests/Unit/Schema/Directives/BaseDirectiveTest.php +++ b/tests/Unit/Schema/Directives/BaseDirectiveTest.php @@ -181,8 +181,7 @@ protected function constructFieldDirective(string $definition): BaseDirective { $fieldDefinition = Parser::fieldDefinition($definition); - $directive = new class extends BaseDirective - { + $directive = new class() extends BaseDirective { public static function definition(): string { return /** @lang GraphQL */ 'directive @baseTest on FIELD_DEFINITION'; @@ -192,7 +191,8 @@ public static function definition(): string * Allow to call protected methods from the test. * * @param array $args - * @return mixed Whatever the method returns. + * + * @return mixed whatever the method returns */ public function __call(string $method, array $args) { diff --git a/tests/Unit/Schema/Directives/ComplexityDirectiveTest.php b/tests/Unit/Schema/Directives/ComplexityDirectiveTest.php index 9b535d87e7..779f0b3585 100644 --- a/tests/Unit/Schema/Directives/ComplexityDirectiveTest.php +++ b/tests/Unit/Schema/Directives/ComplexityDirectiveTest.php @@ -9,7 +9,7 @@ class ComplexityDirectiveTest extends TestCase { - const CUSTOM_COMPLEXITY = 123; + public const CUSTOM_COMPLEXITY = 123; public function testDefaultComplexity(): void { diff --git a/tests/Unit/Schema/Directives/DeprecatedDirectiveTest.php b/tests/Unit/Schema/Directives/DeprecatedDirectiveTest.php index ae45eec0a0..f89a420db3 100644 --- a/tests/Unit/Schema/Directives/DeprecatedDirectiveTest.php +++ b/tests/Unit/Schema/Directives/DeprecatedDirectiveTest.php @@ -57,7 +57,7 @@ enumValues(includeDeprecated: $includeDeprecated) { $withoutDeprecatedIntrospection->assertJsonCount(1, 'data.__schema.queryType.fields'); $types = $withoutDeprecatedIntrospection->json('data.__schema.types'); $foo = Arr::first($types, static function (array $type): bool { - return $type['name'] === 'Foo'; + return 'Foo' === $type['name']; }); $this->assertCount(1, $foo['enumValues']); @@ -88,7 +88,7 @@ function (array $field): bool { $types = $includeDeprecatedIntrospection->json('data.__schema.types'); $foo = Arr::first($types, static function (array $type): bool { - return $type['name'] === 'Foo'; + return 'Foo' === $type['name']; }); $this->assertCount(2, $foo['enumValues']); } diff --git a/tests/Unit/Schema/Directives/ThrottleDirectiveTest.php b/tests/Unit/Schema/Directives/ThrottleDirectiveTest.php index a56f3b38e4..435f23e437 100644 --- a/tests/Unit/Schema/Directives/ThrottleDirectiveTest.php +++ b/tests/Unit/Schema/Directives/ThrottleDirectiveTest.php @@ -16,7 +16,7 @@ public function testNamedLimiter(): void $this->markTestSkipped('Version less than 8.0 does not support named requests.'); } - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Query { foo: Int @throttle(name: "test") } @@ -75,7 +75,7 @@ public function testUnlimitedNamedLimiter(): void $this->markTestSkipped('Version less than 8.0 does not support named requests.'); } - $this->schema = /** @lang GraphQL */' + $this->schema = /** @lang GraphQL */ ' type Query { foo: Int @throttle(name: "test") } diff --git a/tests/Unit/Schema/Execution/ContextFactoryTest.php b/tests/Unit/Schema/Execution/ContextFactoryTest.php index 637ea04aa3..da9d05b6c9 100644 --- a/tests/Unit/Schema/Execution/ContextFactoryTest.php +++ b/tests/Unit/Schema/Execution/ContextFactoryTest.php @@ -15,8 +15,7 @@ protected function getEnvironmentSetUp($app): void parent::getEnvironmentSetUp($app); $app->singleton(CreatesContext::class, function (): CreatesContext { - return new class implements CreatesContext - { + return new class() implements CreatesContext { public function generate(Request $request): GraphQLContext { return new FooContext($request); diff --git a/tests/Unit/Schema/Execution/Fixtures/FooContext.php b/tests/Unit/Schema/Execution/Fixtures/FooContext.php index d6bf221cef..8eebc40322 100644 --- a/tests/Unit/Schema/Execution/Fixtures/FooContext.php +++ b/tests/Unit/Schema/Execution/Fixtures/FooContext.php @@ -8,7 +8,7 @@ class FooContext implements GraphQLContext { - const FROM_FOO_CONTEXT = 'custom.context'; + public const FROM_FOO_CONTEXT = 'custom.context'; /** * @var \Illuminate\Http\Request diff --git a/tests/Unit/Schema/ResolverProviderTest.php b/tests/Unit/Schema/ResolverProviderTest.php index 89c65db573..5ac92e68e7 100644 --- a/tests/Unit/Schema/ResolverProviderTest.php +++ b/tests/Unit/Schema/ResolverProviderTest.php @@ -22,7 +22,7 @@ public function setUp(): void { parent::setUp(); - $this->resolverProvider = new ResolverProvider; + $this->resolverProvider = new ResolverProvider(); } public function testGetsTheWebonyxDefaultResolverForNonRootFields(): void diff --git a/tests/Unit/Schema/Source/SchemaStitcherTest.php b/tests/Unit/Schema/Source/SchemaStitcherTest.php index d575a043ac..c9882e17c2 100644 --- a/tests/Unit/Schema/Source/SchemaStitcherTest.php +++ b/tests/Unit/Schema/Source/SchemaStitcherTest.php @@ -13,7 +13,7 @@ class SchemaStitcherTest extends TestCase /** * @var string */ - public const SCHEMA_PATH = __DIR__.'/schema/'; + public const SCHEMA_PATH = __DIR__ . '/schema/'; /** * @var string @@ -47,7 +47,7 @@ protected function tearDown(): void protected function assertSchemaResultIsSame(string $expected): void { - $schema = (new SchemaStitcher(self::SCHEMA_PATH.self::ROOT_SCHEMA_FILENAME))->getSchemaString(); + $schema = (new SchemaStitcher(self::SCHEMA_PATH . self::ROOT_SCHEMA_FILENAME))->getSchemaString(); $this->assertSame($expected, $schema); } @@ -89,20 +89,24 @@ public function testLeavesImportlessFileAsBefore(): void public function testReplacesImportWithFileContent(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import bar EOT ); - $this->filesystem->put('bar', <<<'EOT' + $this->filesystem->put( + 'bar', + <<<'EOT' bar EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar @@ -112,26 +116,32 @@ public function testReplacesImportWithFileContent(): void public function testImportsRecursively(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import bar EOT ); - $this->filesystem->put('bar', <<<'EOT' + $this->filesystem->put( + 'bar', + <<<'EOT' bar #import baz EOT ); - $this->filesystem->put('baz', <<<'EOT' + $this->filesystem->put( + 'baz', + <<<'EOT' baz EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar baz @@ -142,7 +152,8 @@ public function testImportsRecursively(): void public function testImportsFromSubdirectory(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import subdir/bar @@ -150,13 +161,16 @@ public function testImportsFromSubdirectory(): void ); $this->filesystem->createDir('subdir'); - $this->filesystem->put('subdir/bar', <<<'EOT' + $this->filesystem->put( + 'subdir/bar', + <<<'EOT' bar EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar @@ -166,20 +180,24 @@ public function testImportsFromSubdirectory(): void public function testKeepsIndententation(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import bar EOT ); - $this->filesystem->put('bar', <<<'EOT' + $this->filesystem->put( + 'bar', + <<<'EOT' bar EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar @@ -189,7 +207,8 @@ public function testKeepsIndententation(): void public function testImportsViaGlob(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import subdir/*.graphql @@ -197,18 +216,23 @@ public function testImportsViaGlob(): void ); $this->filesystem->createDir('subdir'); - $this->filesystem->put('subdir/bar.graphql', <<<'EOT' + $this->filesystem->put( + 'subdir/bar.graphql', + <<<'EOT' bar EOT ); - $this->filesystem->put('subdir/other.graphql', <<<'EOT' + $this->filesystem->put( + 'subdir/other.graphql', + <<<'EOT' other EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar other @@ -219,24 +243,30 @@ public function testImportsViaGlob(): void public function testAddsNewlineToTheEndOfImportedFile(): void { - $this->putRootSchema(<<<'EOT' + $this->putRootSchema( + <<<'EOT' foo #import bar #import foobar EOT ); - $this->filesystem->put('bar', <<<'EOT' + $this->filesystem->put( + 'bar', + <<<'EOT' bar EOT ); - $this->filesystem->put('foobar', <<<'EOT' + $this->filesystem->put( + 'foobar', + <<<'EOT' foobar EOT ); - $this->assertSchemaResultIsSame(<<<'EOT' + $this->assertSchemaResultIsSame( + <<<'EOT' foo bar foobar diff --git a/tests/Unit/Schema/Types/Scalars/UploadTest.php b/tests/Unit/Schema/Types/Scalars/UploadTest.php index 3bd6e8fd8c..df333be301 100644 --- a/tests/Unit/Schema/Types/Scalars/UploadTest.php +++ b/tests/Unit/Schema/Types/Scalars/UploadTest.php @@ -14,14 +14,14 @@ public function testThrowsIfSerializing(): void { $this->expectException(InvariantViolation::class); - (new Upload)->serialize(''); + (new Upload())->serialize(''); } public function testThrowsIfParsingLiteral(): void { $this->expectException(Error::class); - $upload = new Upload; + $upload = new Upload(); // @phpstan-ignore-next-line Wrong use is on purpose $upload->parseLiteral(''); } @@ -30,14 +30,14 @@ public function testThrowsIfParsingValueNotFile(): void { $this->expectException(Error::class); - (new Upload)->parseValue('not a file'); + (new Upload())->parseValue('not a file'); } public function testParsesValidFiles(): void { $value = UploadedFile::fake() ->create('my-file.jpg', 500); - $parsedValue = (new Upload)->parseValue($value); + $parsedValue = (new Upload())->parseValue($value); $this->assertEquals($value, $parsedValue); } diff --git a/tests/Unit/Subscriptions/BroadcastManagerTest.php b/tests/Unit/Subscriptions/BroadcastManagerTest.php index e044ff956a..e56eb65707 100644 --- a/tests/Unit/Subscriptions/BroadcastManagerTest.php +++ b/tests/Unit/Subscriptions/BroadcastManagerTest.php @@ -42,8 +42,7 @@ public function testExtendBroadcastManager(): void { $broadcasterConfig = []; - $broadcaster = new class implements Broadcaster - { + $broadcaster = new class() implements Broadcaster { public function authorized(Request $request) { return new Response(); @@ -80,9 +79,7 @@ public function broadcast(Subscriber $subscriber, $data) public function testThrowsIfDriverDoesNotImplementInterface(): void { $this->broadcastManager->extend('foo', function () { - return new class - { - // + return new class() { }; }); diff --git a/tests/Unit/Subscriptions/Broadcasters/EchoBroadcasterTest.php b/tests/Unit/Subscriptions/Broadcasters/EchoBroadcasterTest.php index 6d5c04afe6..b9c3ce0d02 100644 --- a/tests/Unit/Subscriptions/Broadcasters/EchoBroadcasterTest.php +++ b/tests/Unit/Subscriptions/Broadcasters/EchoBroadcasterTest.php @@ -22,9 +22,9 @@ public function testBroadcast(): void $broadcastManager->expects($this->once()) ->method('event') ->with(new Callback(function (EchoSubscriptionEvent $event) { - return $event->broadcastAs() === Broadcaster::EVENT_NAME - && $event->broadcastOn()->name === 'test-123' - && $event->data === 'foo'; + return Broadcaster::EVENT_NAME === $event->broadcastAs() + && 'test-123' === $event->broadcastOn()->name + && 'foo' === $event->data; })); $redisBroadcaster = new EchoBroadcaster($broadcastManager); @@ -40,7 +40,7 @@ public function testBroadcastChannelNameIsNotModified(): void $broadcastManager->expects($this->once()) ->method('event') ->with(new Callback(function (EchoSubscriptionEvent $event) { - return $event->broadcastOn()->name === 'private-test-123'; + return 'private-test-123' === $event->broadcastOn()->name; })); $redisBroadcaster = new EchoBroadcaster($broadcastManager); diff --git a/tests/Unit/Subscriptions/Iterators/IteratorTest.php b/tests/Unit/Subscriptions/Iterators/IteratorTest.php index 66f2689665..688578d2f2 100644 --- a/tests/Unit/Subscriptions/Iterators/IteratorTest.php +++ b/tests/Unit/Subscriptions/Iterators/IteratorTest.php @@ -73,6 +73,6 @@ public function generateSubscriber(): Subscriber ]), ]); - return new Subscriber([], new Context(new Request), $resolveInfo); + return new Subscriber([], new Context(new Request()), $resolveInfo); } } diff --git a/tests/Unit/Subscriptions/Iterators/SyncIteratorTest.php b/tests/Unit/Subscriptions/Iterators/SyncIteratorTest.php index 7f1c47b2f8..c970baa01d 100644 --- a/tests/Unit/Subscriptions/Iterators/SyncIteratorTest.php +++ b/tests/Unit/Subscriptions/Iterators/SyncIteratorTest.php @@ -8,7 +8,7 @@ class SyncIteratorTest extends IteratorTest { public function testIsWellBehavedIterator(): void { - $iterator = new SyncIterator; + $iterator = new SyncIterator(); $this->assertIteratesOverItemsWithCallback($iterator); $this->assertPassesExceptionToHandler($iterator); diff --git a/tests/Unit/Subscriptions/Storage/RedisStorageManagerTest.php b/tests/Unit/Subscriptions/Storage/RedisStorageManagerTest.php index c68562bbe9..3f910a77e9 100644 --- a/tests/Unit/Subscriptions/Storage/RedisStorageManagerTest.php +++ b/tests/Unit/Subscriptions/Storage/RedisStorageManagerTest.php @@ -26,7 +26,7 @@ public function testSubscriberByChannel(): void $subscriber = new DummySubscriber($channel, 'test-topic'); $redisConnection->expects($this->once()) ->method('command') - ->with('get', ['graphql.subscriber.'.$channel]) + ->with('get', ['graphql.subscriber.' . $channel]) ->willReturn(serialize($subscriber)); $manager = new RedisStorageManager($config, $redisFactory); @@ -42,14 +42,14 @@ public function testDeleteSubscriber(): void $redisFactory = $this->getRedisFactory($redisConnection); $channel = 'test-channel'; - $prefixedChannel = 'graphql.subscriber.'.$channel; + $prefixedChannel = 'graphql.subscriber.' . $channel; $subscriber = new DummySubscriber($channel, 'test-topic'); $redisConnection->expects($this->exactly(3)) ->method('command') ->withConsecutive( ['get', [$prefixedChannel]], ['del', [$prefixedChannel]], - ['srem', ['graphql.topic.'.$subscriber->topic, $channel]] + ['srem', ['graphql.topic.' . $subscriber->topic, $channel]] ) ->willReturnOnConsecutiveCalls( serialize($subscriber) @@ -146,7 +146,7 @@ public function testSubscribersByTopic(): void $redisConnection->expects($this->exactly(2)) ->method('command') ->withConsecutive( - ['smembers', ['graphql.topic.'.$topic]], + ['smembers', ['graphql.topic.' . $topic]], ['mget', [[ 'graphql.subscriber.foo1', 'graphql.subscriber.foo2', @@ -166,6 +166,7 @@ public function testSubscribersByTopic(): void /** * @param \PHPUnit\Framework\MockObject\MockObject&\Illuminate\Redis\Connections\Connection $redisConnection + * * @return \PHPUnit\Framework\MockObject\MockObject&\Illuminate\Contracts\Redis\Factory */ protected function getRedisFactory(MockObject $redisConnection): MockObject diff --git a/tests/Unit/Subscriptions/SubscriptionTest.php b/tests/Unit/Subscriptions/SubscriptionTest.php index 99d1d2efd3..202fea1499 100644 --- a/tests/Unit/Subscriptions/SubscriptionTest.php +++ b/tests/Unit/Subscriptions/SubscriptionTest.php @@ -57,8 +57,7 @@ public function testBroadcastProgrammaticallyRegisteredSubscription(): void { $subscriptionRegistry = app(SubscriptionRegistry::class); - $subscription = new class extends GraphQLSubscription - { + $subscription = new class() extends GraphQLSubscription { public function authorize(Subscriber $subscriber, Request $request): bool { return true; diff --git a/tests/Unit/Support/Http/Middleware/AttemptAuthenticationTest.php b/tests/Unit/Support/Http/Middleware/AttemptAuthenticationTest.php index 729c736035..8e66583170 100644 --- a/tests/Unit/Support/Http/Middleware/AttemptAuthenticationTest.php +++ b/tests/Unit/Support/Http/Middleware/AttemptAuthenticationTest.php @@ -44,7 +44,7 @@ public function testAttemptsAuthenticationGuest(): void null, [], new Callback(function (Context $context) { - return $this->user === null; + return null === $this->user; }) ); diff --git a/tests/Unit/Testing/MakesGraphQLRequestsTest.php b/tests/Unit/Testing/MakesGraphQLRequestsTest.php index 492994f267..e05bb73c61 100644 --- a/tests/Unit/Testing/MakesGraphQLRequestsTest.php +++ b/tests/Unit/Testing/MakesGraphQLRequestsTest.php @@ -73,7 +73,8 @@ public function testGraphQLWithHeaders(): void $value = 'bar'; $this->graphQL( -/** @lang GraphQL */ ' + /** @lang GraphQL */ + ' { foo } diff --git a/tests/Unit/Tests/Unit/Auth/CanDirectiveTest.php b/tests/Unit/Tests/Unit/Auth/CanDirectiveTest.php index dca2e44f90..e71868e540 100644 --- a/tests/Unit/Tests/Unit/Auth/CanDirectiveTest.php +++ b/tests/Unit/Tests/Unit/Auth/CanDirectiveTest.php @@ -14,7 +14,7 @@ class CanDirectiveTest extends TestCase { public function testThrowsIfNotAuthorized(): void { - $this->be(new User); + $this->be(new User()); $this->schema = /** @lang GraphQL */ ' type Query { @@ -44,7 +44,7 @@ public function testThrowsWithCustomMessageIfNotAuthorized(): void $this->markTestSkipped('Version less than 6.0 do not support gate responses.'); } - $this->be(new User); + $this->be(new User()); $this->schema = /** @lang GraphQL */ ' type Query { @@ -77,7 +77,7 @@ public function testThrowsFirstWithCustomMessageIfNotAuthorized(): void $this->markTestSkipped('Version less than 6.0 do not support gate responses.'); } - $this->be(new User); + $this->be(new User()); $this->schema = /** @lang GraphQL */ ' type Query { @@ -105,7 +105,7 @@ public function testThrowsFirstWithCustomMessageIfNotAuthorized(): void public function testPassesAuthIfAuthorized(): void { - $user = new User; + $user = new User(); $user->name = UserPolicy::ADMIN; $this->be($user); @@ -179,7 +179,7 @@ public function testAcceptsGuestUser(): void public function testPassesMultiplePolicies(): void { - $user = new User; + $user = new User(); $user->name = UserPolicy::ADMIN; $this->be($user); @@ -239,7 +239,7 @@ public function testProcessesTheArgsArgument(): void public function testInjectArgsPassesClientArgumentToPolicy(): void { - $this->be(new User); + $this->be(new User()); $this->mockResolver(function (): User { return $this->resolveUser(); @@ -274,7 +274,7 @@ public function testInjectArgsPassesClientArgumentToPolicy(): void public function testInjectedArgsAndStaticArgs(): void { - $this->be(new User); + $this->be(new User()); $this->mockResolver(function (): User { return $this->resolveUser(); @@ -332,7 +332,7 @@ public function testFindAndQueryAreMutuallyExclusive(): void public function resolveUser(): User { - $user = new User; + $user = new User(); $user->name = 'foo'; return $user; diff --git a/tests/Utils/Directives/CustomFieldMiddlewareDirective.php b/tests/Utils/Directives/CustomFieldMiddlewareDirective.php index ca453a7ca7..5f4b256ad9 100644 --- a/tests/Utils/Directives/CustomFieldMiddlewareDirective.php +++ b/tests/Utils/Directives/CustomFieldMiddlewareDirective.php @@ -22,6 +22,7 @@ public function handleField(FieldValue $fieldValue, Closure $next) $fieldValue->setResolver( /** * @param array $args + * * @return array */ static function ($root, array $args): array { diff --git a/tests/Utils/Entities/Foo.php b/tests/Utils/Entities/Foo.php index 3852619c95..0121a82e5b 100644 --- a/tests/Utils/Entities/Foo.php +++ b/tests/Utils/Entities/Foo.php @@ -6,6 +6,7 @@ class Foo { /** * @param array $representation + * * @return array */ public function __invoke(array $representation): array diff --git a/tests/Utils/InterfacesSecondary/Bar.php b/tests/Utils/InterfacesSecondary/Bar.php index 43f17510d3..2c316c451b 100644 --- a/tests/Utils/InterfacesSecondary/Bar.php +++ b/tests/Utils/InterfacesSecondary/Bar.php @@ -6,6 +6,5 @@ class Bar { public function __invoke(): void { - // } } diff --git a/tests/Utils/LaravelEnums/LocalizedUserType.php b/tests/Utils/LaravelEnums/LocalizedUserType.php index e03ed6d8ff..dd94c37596 100644 --- a/tests/Utils/LaravelEnums/LocalizedUserType.php +++ b/tests/Utils/LaravelEnums/LocalizedUserType.php @@ -12,7 +12,7 @@ final class LocalizedUserType extends Enum implements LocalizedEnum public static function getDescription($value): string { - if ($value === self::Moderator) { + if (self::Moderator === $value) { return 'Localize Moderator'; } diff --git a/tests/Utils/Models/Closure.php b/tests/Utils/Models/Closure.php index 9dfeb1e1d3..599fcdd0ff 100644 --- a/tests/Utils/Models/Closure.php +++ b/tests/Utils/Models/Closure.php @@ -10,5 +10,4 @@ */ class Closure extends Model { - // } diff --git a/tests/Utils/ModelsSecondary/Category.php b/tests/Utils/ModelsSecondary/Category.php index d6572ccaa2..a6722a2678 100644 --- a/tests/Utils/ModelsSecondary/Category.php +++ b/tests/Utils/ModelsSecondary/Category.php @@ -10,5 +10,4 @@ */ class Category extends Model { - // } diff --git a/tests/Utils/ModelsSecondary/OnlyHere.php b/tests/Utils/ModelsSecondary/OnlyHere.php index 384e0c8f11..87ac3709c8 100644 --- a/tests/Utils/ModelsSecondary/OnlyHere.php +++ b/tests/Utils/ModelsSecondary/OnlyHere.php @@ -9,5 +9,4 @@ */ class OnlyHere extends Model { - // } diff --git a/tests/Utils/Policies/TaskPolicy.php b/tests/Utils/Policies/TaskPolicy.php index 8ef27b5264..bf0a64c757 100644 --- a/tests/Utils/Policies/TaskPolicy.php +++ b/tests/Utils/Policies/TaskPolicy.php @@ -11,13 +11,13 @@ class TaskPolicy public function adminOnly(User $user): bool { - return $user->name === self::ADMIN; + return self::ADMIN === $user->name; } public function delete(User $user, Task $task): bool { $taskUser = $task->user; - if ($taskUser === null) { + if (null === $taskUser) { return false; } diff --git a/tests/Utils/Policies/UserPolicy.php b/tests/Utils/Policies/UserPolicy.php index 4c54522a89..c11445aaf2 100644 --- a/tests/Utils/Policies/UserPolicy.php +++ b/tests/Utils/Policies/UserPolicy.php @@ -14,12 +14,12 @@ class UserPolicy public function adminOnly(User $user): bool { - return $user->name === self::ADMIN; + return self::ADMIN === $user->name; } public function superAdminOnly(User $user): Response { - if ($user->name === self::SUPER_ADMIN) { + if (self::SUPER_ADMIN === $user->name) { return Response::allow(); } @@ -33,7 +33,7 @@ public function alwaysTrue(): bool public function guestOnly(User $viewer = null): bool { - return $viewer === null; + return null === $viewer; } public function view(User $viewer, User $queriedUser): bool diff --git a/tests/Utils/Scalars/Email.php b/tests/Utils/Scalars/Email.php index 975625d642..825c9c515f 100644 --- a/tests/Utils/Scalars/Email.php +++ b/tests/Utils/Scalars/Email.php @@ -27,7 +27,7 @@ public function serialize($value) public function parseValue($value): string { if (! filter_var($value, FILTER_VALIDATE_EMAIL)) { - throw new Error('Cannot represent following value as email: '.Utils::printSafeJson($value)); + throw new Error('Cannot represent following value as email: ' . Utils::printSafeJson($value)); } return $value; @@ -41,7 +41,7 @@ public function parseValue($value): string public function parseLiteral($valueNode, ?array $variables = null): string { if (! $valueNode instanceof StringValueNode) { - throw new Error('Query error: Can only parse strings got: '.$valueNode->kind, $valueNode); + throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode); } if (! filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { diff --git a/tests/Utils/Unions/CustomStuff.php b/tests/Utils/Unions/CustomStuff.php index 118f4ae001..cc84a3dbae 100644 --- a/tests/Utils/Unions/CustomStuff.php +++ b/tests/Utils/Unions/CustomStuff.php @@ -26,7 +26,7 @@ public function resolveType($rootValue): Type { return $this->typeRegistry->get( // Add prefix - 'Custom'.class_basename($rootValue) + 'Custom' . class_basename($rootValue) ); } } diff --git a/tests/Utils/Validators/EmailCustomAttributeValidator.php b/tests/Utils/Validators/EmailCustomAttributeValidator.php index 95997bf5e5..22267bb274 100644 --- a/tests/Utils/Validators/EmailCustomAttributeValidator.php +++ b/tests/Utils/Validators/EmailCustomAttributeValidator.php @@ -6,7 +6,7 @@ class EmailCustomAttributeValidator extends Validator { - const MESSAGE = 'The email address must be a valid email address.'; + public const MESSAGE = 'The email address must be a valid email address.'; public function rules(): array { diff --git a/tests/Utils/Validators/EmailCustomMessageValidator.php b/tests/Utils/Validators/EmailCustomMessageValidator.php index b66c63c4da..677f482ba3 100644 --- a/tests/Utils/Validators/EmailCustomMessageValidator.php +++ b/tests/Utils/Validators/EmailCustomMessageValidator.php @@ -6,7 +6,7 @@ class EmailCustomMessageValidator extends Validator { - const MESSAGE = 'this is a custom error message'; + public const MESSAGE = 'this is a custom error message'; public function rules(): array { diff --git a/tests/Utils/Validators/FooClosureValidator.php b/tests/Utils/Validators/FooClosureValidator.php index e22924d6e9..21051c0c82 100644 --- a/tests/Utils/Validators/FooClosureValidator.php +++ b/tests/Utils/Validators/FooClosureValidator.php @@ -9,7 +9,7 @@ class FooClosureValidator extends Validator { public static function notFoo(string $attribute): string { - return 'The '.$attribute.' field must have a value of "foo".'; + return 'The ' . $attribute . ' field must have a value of "foo".'; } public function rules(): array @@ -17,7 +17,7 @@ public function rules(): array return [ 'foo' => [ static function (string $attribute, $value, Closure $fail): void { - if ($value !== 'foo') { + if ('foo' !== $value) { $fail(self::notFoo($attribute)); } }, diff --git a/tests/database/factories/RoleFactory.php b/tests/database/factories/RoleFactory.php index 778d2e85a1..3069a48fa0 100644 --- a/tests/database/factories/RoleFactory.php +++ b/tests/database/factories/RoleFactory.php @@ -7,7 +7,7 @@ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(Role::class, function (Faker $faker): array { return [ - 'name' => 'role_'.$faker->unique()->randomNumber(), + 'name' => 'role_' . $faker->unique()->randomNumber(), 'acl_id' => function () { return factory(ACL::class)->create()->getKey(); }, From bebd344ec4b098b6d8b137088f6028c4ae95d735 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Mon, 6 Dec 2021 09:51:53 +0100 Subject: [PATCH 9/9] Allow mll-lab/graphql-php-scalars:^5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 150c3ca0e5..af8951e36e 100644 --- a/composer.json +++ b/composer.json @@ -49,7 +49,7 @@ "laravel/legacy-factories": "^1", "laravel/lumen-framework": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", "laravel/scout": "^7 || ^8", - "mll-lab/graphql-php-scalars": "^4", + "mll-lab/graphql-php-scalars": "^4 || ^5", "mll-lab/php-cs-fixer-config": "^4.4.1", "mockery/mockery": "^1", "nunomaduro/larastan": "^0.6 || ^0.7 || ^1",