From af31ca7ad8d3a958be41350fe891003b2df96065 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 11:05:01 +0200 Subject: [PATCH 01/10] Bump Doctrine CS to v5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c536480..bc8f8b2 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "ext-mbstring": "*" }, "require-dev": { - "doctrine/coding-standard": "^4.0", + "doctrine/coding-standard": "^5.0", "phpbench/phpbench": "^0.14.0", "phpstan/phpstan": "^0.10.3", "phpstan/phpstan-phpunit": "^0.10.0", From 07c070d79550d5492265456e6d8791ceec7b8a0a Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 11:07:23 +0200 Subject: [PATCH 02/10] Fix CS in tests --- tests/Error/ErrorTest.php | 3 +- tests/Executor/AbstractPromiseTest.php | 56 +- tests/Executor/AbstractTest.php | 34 +- tests/Executor/DeferredFieldsTest.php | 10 +- tests/Executor/DirectivesTest.php | 1 + tests/Executor/ExecutorLazySchemaTest.php | 26 +- tests/Executor/ExecutorSchemaTest.php | 10 +- tests/Executor/ExecutorTest.php | 121 ++-- tests/Executor/LazyInterfaceTest.php | 5 +- tests/Executor/ListsTest.php | 116 ++-- tests/Executor/MutationsTest.php | 12 +- tests/Executor/NonNullTest.php | 23 +- .../Promise/ReactPromiseAdapterTest.php | 24 +- .../Promise/SyncPromiseAdapterTest.php | 33 +- tests/Executor/Promise/SyncPromiseTest.php | 76 +-- tests/Executor/ResolveTest.php | 4 +- tests/Executor/SyncTest.php | 10 +- tests/Executor/TestClasses/Root.php | 3 +- tests/Executor/UnionInterfaceTest.php | 10 +- tests/Executor/ValuesTest.php | 1 + tests/Executor/VariablesTest.php | 2 +- tests/Language/LexerTest.php | 15 +- tests/Language/ParserTest.php | 10 +- tests/Language/PrinterTest.php | 6 +- tests/Language/SchemaParserTest.php | 40 +- tests/Language/VisitorTest.php | 538 +++++++++--------- tests/Server/QueryExecutionTest.php | 39 +- tests/Server/RequestParsingTest.php | 14 +- tests/Server/ServerConfigTest.php | 33 +- tests/Server/ServerTestCase.php | 20 +- tests/Server/StandardServerTest.php | 2 +- tests/Server/Unsafe.php | 9 +- tests/StarWarsData.php | 5 +- tests/StarWarsSchema.php | 30 +- tests/Type/DefinitionTest.php | 90 +-- tests/Type/EnumTypeTest.php | 19 +- tests/Type/IntrospectionTest.php | 2 +- tests/Type/ResolutionTest.php | 7 +- tests/Type/ResolveInfoTest.php | 8 +- tests/Type/ScalarSerializationTest.php | 5 +- tests/Type/SchemaTest.php | 4 +- tests/Type/TypeLoaderTest.php | 21 +- tests/Type/ValidationTest.php | 29 +- tests/Utils/AstFromValueTest.php | 14 +- tests/Utils/BuildSchemaTest.php | 19 +- tests/Utils/MixedStoreTest.php | 11 +- tests/Utils/QuotedOrListTest.php | 3 +- tests/Utils/SchemaPrinterTest.php | 2 +- tests/UtilsTest.php | 6 +- .../OverlappingFieldsCanBeMergedTest.php | 10 +- tests/Validator/QueryComplexityTest.php | 4 +- tests/Validator/QueryDepthTest.php | 17 +- tests/Validator/QuerySecuritySchema.php | 4 +- tests/Validator/QuerySecurityTestCase.php | 1 + tests/Validator/ValidatorTestCase.php | 27 +- tests/Validator/ValuesOfCorrectTypeTest.php | 1 + 56 files changed, 844 insertions(+), 801 deletions(-) diff --git a/tests/Error/ErrorTest.php b/tests/Error/ErrorTest.php index 3c53e2d..eb0a6c8 100644 --- a/tests/Error/ErrorTest.php +++ b/tests/Error/ErrorTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Error; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\Parser; use GraphQL\Language\Source; @@ -17,7 +18,7 @@ class ErrorTest extends TestCase */ public function testUsesTheStackOfAnOriginalError() : void { - $prev = new \Exception('Original'); + $prev = new Exception('Original'); $err = new Error('msg', null, null, null, null, $prev); self::assertSame($err->getPrevious(), $prev); diff --git a/tests/Executor/AbstractPromiseTest.php b/tests/Executor/AbstractPromiseTest.php index 01937e6..ed39d04 100644 --- a/tests/Executor/AbstractPromiseTest.php +++ b/tests/Executor/AbstractPromiseTest.php @@ -37,8 +37,8 @@ class AbstractPromiseTest extends TestCase $DogType = new ObjectType([ 'name' => 'Dog', 'interfaces' => [$PetType], - 'isTypeOf' => function ($obj) { - return new Deferred(function () use ($obj) { + 'isTypeOf' => static function ($obj) { + return new Deferred(static function () use ($obj) { return $obj instanceof Dog; }); }, @@ -51,8 +51,8 @@ class AbstractPromiseTest extends TestCase $CatType = new ObjectType([ 'name' => 'Cat', 'interfaces' => [$PetType], - 'isTypeOf' => function ($obj) { - return new Deferred(function () use ($obj) { + 'isTypeOf' => static function ($obj) { + return new Deferred(static function () use ($obj) { return $obj instanceof Cat; }); }, @@ -68,7 +68,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -121,8 +121,8 @@ class AbstractPromiseTest extends TestCase $DogType = new ObjectType([ 'name' => 'Dog', 'interfaces' => [$PetType], - 'isTypeOf' => function () { - return new Deferred(function () { + 'isTypeOf' => static function () { + return new Deferred(static function () { throw new UserError('We are testing this error'); }); }, @@ -135,8 +135,8 @@ class AbstractPromiseTest extends TestCase $CatType = new ObjectType([ 'name' => 'Cat', 'interfaces' => [$PetType], - 'isTypeOf' => function ($obj) { - return new Deferred(function () use ($obj) { + 'isTypeOf' => static function ($obj) { + return new Deferred(static function () use ($obj) { return $obj instanceof Cat; }); }, @@ -152,7 +152,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -206,8 +206,8 @@ class AbstractPromiseTest extends TestCase { $DogType = new ObjectType([ 'name' => 'Dog', - 'isTypeOf' => function ($obj) { - return new Deferred(function () use ($obj) { + 'isTypeOf' => static function ($obj) { + return new Deferred(static function () use ($obj) { return $obj instanceof Dog; }); }, @@ -219,8 +219,8 @@ class AbstractPromiseTest extends TestCase $CatType = new ObjectType([ 'name' => 'Cat', - 'isTypeOf' => function ($obj) { - return new Deferred(function () use ($obj) { + 'isTypeOf' => static function ($obj) { + return new Deferred(static function () use ($obj) { return $obj instanceof Cat; }); }, @@ -241,7 +241,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [new Dog('Odie', true), new Cat('Garfield', false)]; }, ], @@ -283,8 +283,8 @@ class AbstractPromiseTest extends TestCase { $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => function ($obj) use (&$DogType, &$CatType, &$HumanType) { - return new Deferred(function () use ($obj, $DogType, $CatType, $HumanType) { + 'resolveType' => static function ($obj) use (&$DogType, &$CatType, &$HumanType) { + return new Deferred(static function () use ($obj, $DogType, $CatType, $HumanType) { if ($obj instanceof Dog) { return $DogType; } @@ -334,8 +334,8 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { - return new Deferred(function () { + 'resolve' => static function () { + return new Deferred(static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -413,8 +413,8 @@ class AbstractPromiseTest extends TestCase $PetType = new UnionType([ 'name' => 'Pet', - 'resolveType' => function ($obj) use ($DogType, $CatType, $HumanType) { - return new Deferred(function () use ($obj, $DogType, $CatType, $HumanType) { + 'resolveType' => static function ($obj) use ($DogType, $CatType, $HumanType) { + return new Deferred(static function () use ($obj, $DogType, $CatType, $HumanType) { if ($obj instanceof Dog) { return $DogType; } @@ -437,7 +437,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -491,8 +491,8 @@ class AbstractPromiseTest extends TestCase { $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => function ($obj) { - return new Deferred(function () use ($obj) { + 'resolveType' => static function ($obj) { + return new Deferred(static function () use ($obj) { if ($obj instanceof Dog) { return 'Dog'; } @@ -532,7 +532,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -576,8 +576,8 @@ class AbstractPromiseTest extends TestCase { $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => function () { - return new Deferred(function () { + 'resolveType' => static function () { + return new Deferred(static function () { throw new UserError('We are testing this error'); }); }, @@ -610,7 +610,7 @@ class AbstractPromiseTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), diff --git a/tests/Executor/AbstractTest.php b/tests/Executor/AbstractTest.php index 0119344..a1423b9 100644 --- a/tests/Executor/AbstractTest.php +++ b/tests/Executor/AbstractTest.php @@ -40,7 +40,7 @@ class AbstractTest extends TestCase $dogType = new ObjectType([ 'name' => 'Dog', 'interfaces' => [$petType], - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Dog; }, 'fields' => [ @@ -52,7 +52,7 @@ class AbstractTest extends TestCase $catType = new ObjectType([ 'name' => 'Cat', 'interfaces' => [$petType], - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Cat; }, 'fields' => [ @@ -67,7 +67,7 @@ class AbstractTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($petType), - 'resolve' => function () { + 'resolve' => static function () { return [new Dog('Odie', true), new Cat('Garfield', false)]; }, ], @@ -106,7 +106,7 @@ class AbstractTest extends TestCase { $dogType = new ObjectType([ 'name' => 'Dog', - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Dog; }, 'fields' => [ @@ -117,7 +117,7 @@ class AbstractTest extends TestCase $catType = new ObjectType([ 'name' => 'Cat', - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Cat; }, 'fields' => [ @@ -137,7 +137,7 @@ class AbstractTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($petType), - 'resolve' => function () { + 'resolve' => static function () { return [new Dog('Odie', true), new Cat('Garfield', false)]; }, ], @@ -178,7 +178,7 @@ class AbstractTest extends TestCase $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => function ($obj) use (&$DogType, &$CatType, &$HumanType) { + 'resolveType' => static function ($obj) use (&$DogType, &$CatType, &$HumanType) { if ($obj instanceof Dog) { return $DogType; } @@ -227,7 +227,7 @@ class AbstractTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -302,7 +302,7 @@ class AbstractTest extends TestCase $PetType = new UnionType([ 'name' => 'Pet', - 'resolveType' => function ($obj) use ($DogType, $CatType, $HumanType) { + 'resolveType' => static function ($obj) use ($DogType, $CatType, $HumanType) { if ($obj instanceof Dog) { return $DogType; } @@ -322,7 +322,7 @@ class AbstractTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -380,7 +380,7 @@ class AbstractTest extends TestCase $fooInterface = new InterfaceType([ 'name' => 'FooInterface', 'fields' => ['bar' => ['type' => Type::string()]], - 'resolveType' => function () { + 'resolveType' => static function () { return []; }, ]); @@ -397,7 +397,7 @@ class AbstractTest extends TestCase 'fields' => [ 'foo' => [ 'type' => $fooInterface, - 'resolve' => function () { + 'resolve' => static function () { return 'dummy'; }, ], @@ -434,7 +434,7 @@ class AbstractTest extends TestCase { $PetType = new InterfaceType([ 'name' => 'Pet', - 'resolveType' => function ($obj) { + 'resolveType' => static function ($obj) { if ($obj instanceof Dog) { return 'Dog'; } @@ -473,7 +473,7 @@ class AbstractTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($PetType), - 'resolve' => function () { + 'resolve' => static function () { return [ new Dog('Odie', true), new Cat('Garfield', false), @@ -514,13 +514,13 @@ class AbstractTest extends TestCase public function testHintsOnConflictingTypeInstancesInResolveType() : void { - $createTest = function () use (&$iface) { + $createTest = static function () use (&$iface) { return new ObjectType([ 'name' => 'Test', 'fields' => [ 'a' => Type::string(), ], - 'interfaces' => function () use ($iface) { + 'interfaces' => static function () use ($iface) { return [$iface]; }, ]); @@ -531,7 +531,7 @@ class AbstractTest extends TestCase 'fields' => [ 'a' => Type::string(), ], - 'resolveType' => function () use (&$createTest) { + 'resolveType' => static function () use (&$createTest) { return $createTest(); }, ]); diff --git a/tests/Executor/DeferredFieldsTest.php b/tests/Executor/DeferredFieldsTest.php index c97da22..82df651 100644 --- a/tests/Executor/DeferredFieldsTest.php +++ b/tests/Executor/DeferredFieldsTest.php @@ -91,7 +91,7 @@ class DeferredFieldsTest extends TestCase return Utils::find( $this->userDataSource, - function ($entry) use ($user) { + static function ($entry) use ($user) { return $entry['id'] === $user['bestFriendId']; } ); @@ -123,7 +123,7 @@ class DeferredFieldsTest extends TestCase return Utils::find( $this->userDataSource, - function ($entry) use ($story) { + static function ($entry) use ($story) { return $entry['id'] === $story['authorId']; } ); @@ -152,7 +152,7 @@ class DeferredFieldsTest extends TestCase return Utils::filter( $this->storyDataSource, - function ($story) use ($category) { + static function ($story) use ($category) { return in_array($category['id'], $story['categoryIds']); } ); @@ -168,7 +168,7 @@ class DeferredFieldsTest extends TestCase return Utils::find( $this->storyDataSource, - function ($story) use ($category) { + static function ($story) use ($category) { return $story['id'] === $category['topStoryId']; } ); @@ -188,7 +188,7 @@ class DeferredFieldsTest extends TestCase return Utils::filter( $this->storyDataSource, - function ($story) { + static function ($story) { return $story['id'] % 2 === 1; } ); diff --git a/tests/Executor/DirectivesTest.php b/tests/Executor/DirectivesTest.php index 6550c97..84aa491 100644 --- a/tests/Executor/DirectivesTest.php +++ b/tests/Executor/DirectivesTest.php @@ -33,6 +33,7 @@ class DirectivesTest extends TestCase /** * @param Source|string $doc + * * @return mixed[] */ private function executeTestQuery($doc) : array diff --git a/tests/Executor/ExecutorLazySchemaTest.php b/tests/Executor/ExecutorLazySchemaTest.php index 63b4042..7779715 100644 --- a/tests/Executor/ExecutorLazySchemaTest.php +++ b/tests/Executor/ExecutorLazySchemaTest.php @@ -64,7 +64,7 @@ class ExecutorLazySchemaTest extends TestCase // isTypeOf used to resolve runtime type for Interface $petType = new InterfaceType([ 'name' => 'Pet', - 'fields' => function () { + 'fields' => static function () { return [ 'name' => ['type' => Type::string()], ]; @@ -75,10 +75,10 @@ class ExecutorLazySchemaTest extends TestCase $dogType = new ObjectType([ 'name' => 'Dog', 'interfaces' => [$petType], - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Dog; }, - 'fields' => function () { + 'fields' => static function () { return [ 'name' => ['type' => Type::string()], 'woofs' => ['type' => Type::boolean()], @@ -89,10 +89,10 @@ class ExecutorLazySchemaTest extends TestCase $catType = new ObjectType([ 'name' => 'Cat', 'interfaces' => [$petType], - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Cat; }, - 'fields' => function () { + 'fields' => static function () { return [ 'name' => ['type' => Type::string()], 'meows' => ['type' => Type::boolean()], @@ -106,14 +106,14 @@ class ExecutorLazySchemaTest extends TestCase 'fields' => [ 'pets' => [ 'type' => Type::listOf($petType), - 'resolve' => function () { + 'resolve' => static function () { return [new Dog('Odie', true), new Cat('Garfield', false)]; }, ], ], ]), 'types' => [$catType, $dogType], - 'typeLoader' => function ($name) use ($dogType, $petType, $catType) { + 'typeLoader' => static function ($name) use ($dogType, $petType, $catType) { switch ($name) { case 'Dog': return $dogType; @@ -165,13 +165,13 @@ class ExecutorLazySchemaTest extends TestCase public function testHintsOnConflictingTypeInstancesInDefinitions() : void { $calls = []; - $typeLoader = function ($name) use (&$calls) { + $typeLoader = static function ($name) use (&$calls) { $calls[] = $name; switch ($name) { case 'Test': return new ObjectType([ 'name' => 'Test', - 'fields' => function () { + 'fields' => static function () { return [ 'test' => Type::string(), ]; @@ -184,7 +184,7 @@ class ExecutorLazySchemaTest extends TestCase $query = new ObjectType([ 'name' => 'Query', - 'fields' => function () use ($typeLoader) { + 'fields' => static function () use ($typeLoader) { return [ 'test' => $typeLoader('Test'), ]; @@ -311,13 +311,13 @@ class ExecutorLazySchemaTest extends TestCase case 'SomeScalar': return $this->someScalarType ?: $this->someScalarType = new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function ($value) { + 'serialize' => static function ($value) { return $value; }, - 'parseValue' => function ($value) { + 'parseValue' => static function ($value) { return $value; }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]); case 'SomeUnion': diff --git a/tests/Executor/ExecutorSchemaTest.php b/tests/Executor/ExecutorSchemaTest.php index a79f542..4c3b9d6 100644 --- a/tests/Executor/ExecutorSchemaTest.php +++ b/tests/Executor/ExecutorSchemaTest.php @@ -32,14 +32,14 @@ class ExecutorSchemaTest extends TestCase $BlogAuthor = new ObjectType([ 'name' => 'Author', - 'fields' => function () use (&$BlogArticle, &$BlogImage) { + 'fields' => static function () use (&$BlogArticle, &$BlogImage) { return [ 'id' => ['type' => Type::string()], 'name' => ['type' => Type::string()], 'pic' => [ 'args' => ['width' => ['type' => Type::int()], 'height' => ['type' => Type::int()]], 'type' => $BlogImage, - 'resolve' => function ($obj, $args) { + 'resolve' => static function ($obj, $args) { return $obj['pic']($args['width'], $args['height']); }, ], @@ -201,7 +201,7 @@ class ExecutorSchemaTest extends TestCase private function article($id) { $johnSmith = null; - $article = function ($id) use (&$johnSmith) { + $article = static function ($id) use (&$johnSmith) { return [ 'id' => $id, 'isPublished' => 'true', @@ -213,7 +213,7 @@ class ExecutorSchemaTest extends TestCase ]; }; - $getPic = function ($uid, $width, $height) { + $getPic = static function ($uid, $width, $height) { return [ 'url' => sprintf('cdn://%s', $uid), 'width' => $width, @@ -224,7 +224,7 @@ class ExecutorSchemaTest extends TestCase $johnSmith = [ 'id' => 123, 'name' => 'John Smith', - 'pic' => function ($width, $height) use ($getPic) { + 'pic' => static function ($width, $height) use ($getPic) { return $getPic(123, $width, $height); }, 'recentArticle' => $article(1), diff --git a/tests/Executor/ExecutorTest.php b/tests/Executor/ExecutorTest.php index 3a00406..4a4bbb1 100644 --- a/tests/Executor/ExecutorTest.php +++ b/tests/Executor/ExecutorTest.php @@ -17,6 +17,7 @@ use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; use PHPUnit\Framework\TestCase; +use stdClass; use function array_keys; use function count; use function json_encode; @@ -38,52 +39,52 @@ class ExecutorTest extends TestCase $deepData = null; $data = null; - $promiseData = function () use (&$data) { - return new Deferred(function () use (&$data) { + $promiseData = static function () use (&$data) { + return new Deferred(static function () use (&$data) { return $data; }); }; $data = [ - 'a' => function () { + 'a' => static function () { return 'Apple'; }, - 'b' => function () { + 'b' => static function () { return 'Banana'; }, - 'c' => function () { + 'c' => static function () { return 'Cookie'; }, - 'd' => function () { + 'd' => static function () { return 'Donut'; }, - 'e' => function () { + 'e' => static function () { return 'Egg'; }, 'f' => 'Fish', - 'pic' => function ($size = 50) { + 'pic' => static function ($size = 50) { return 'Pic of size: ' . $size; }, - 'promise' => function () use ($promiseData) { + 'promise' => static function () use ($promiseData) { return $promiseData(); }, - 'deep' => function () use (&$deepData) { + 'deep' => static function () use (&$deepData) { return $deepData; }, ]; // Required for that & reference above $deepData = [ - 'a' => function () { + 'a' => static function () { return 'Already Been Done'; }, - 'b' => function () { + 'b' => static function () { return 'Boring'; }, - 'c' => function () { + 'c' => static function () { return ['Contrived', null, 'Confusing']; }, - 'deeper' => function () use (&$data) { + 'deeper' => static function () use (&$data) { return [$data, null, $data]; }, ]; @@ -145,7 +146,7 @@ class ExecutorTest extends TestCase $deepDataType = null; $dataType = new ObjectType([ 'name' => 'DataType', - 'fields' => function () use (&$dataType, &$deepDataType) { + 'fields' => static function () use (&$dataType, &$deepDataType) { return [ 'a' => ['type' => Type::string()], 'b' => ['type' => Type::string()], @@ -156,7 +157,7 @@ class ExecutorTest extends TestCase 'pic' => [ 'args' => ['size' => ['type' => Type::int()]], 'type' => Type::string(), - 'resolve' => function ($obj, $args) { + 'resolve' => static function ($obj, $args) { return $obj['pic']($args['size']); }, ], @@ -205,29 +206,29 @@ class ExecutorTest extends TestCase $Type = new ObjectType([ 'name' => 'Type', - 'fields' => function () use (&$Type) { + 'fields' => static function () use (&$Type) { return [ 'a' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return 'Apple'; }, ], 'b' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return 'Banana'; }, ], 'c' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return 'Cherry'; }, ], 'deep' => [ 'type' => $Type, - 'resolve' => function () { + 'resolve' => static function () { return []; }, ], @@ -270,7 +271,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'test' => [ 'type' => Type::string(), - 'resolve' => function ($val, $args, $ctx, $_info) use (&$info) { + 'resolve' => static function ($val, $args, $ctx, $_info) use (&$info) { $info = $_info; }, ], @@ -329,7 +330,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'a' => [ 'type' => Type::string(), - 'resolve' => function ($context) use (&$gotHere) { + 'resolve' => static function ($context) use (&$gotHere) { self::assertEquals('thing', $context['contextThing']); $gotHere = true; }, @@ -366,7 +367,7 @@ class ExecutorTest extends TestCase 'stringArg' => ['type' => Type::string()], ], 'type' => Type::string(), - 'resolve' => function ($_, $args) use (&$gotHere) { + 'resolve' => static function ($_, $args) use (&$gotHere) { self::assertEquals(123, $args['numArg']); self::assertEquals('foo', $args['stringArg']); $gotHere = true; @@ -400,21 +401,21 @@ class ExecutorTest extends TestCase }'; $data = [ - 'sync' => function () { + 'sync' => static function () { return 'sync'; }, - 'syncError' => function () { + 'syncError' => static function () { throw new UserError('Error getting syncError'); }, - 'syncRawError' => function () { + 'syncRawError' => static function () { throw new UserError('Error getting syncRawError'); }, // inherited from JS reference implementation, but make no sense in this PHP impl // leaving it just to simplify migrations from newer js versions - 'syncReturnError' => function () { + 'syncReturnError' => static function () { return new UserError('Error getting syncReturnError'); }, - 'syncReturnErrorList' => function () { + 'syncReturnErrorList' => static function () { return [ 'sync0', new UserError('Error getting syncReturnErrorList1'), @@ -422,40 +423,40 @@ class ExecutorTest extends TestCase new UserError('Error getting syncReturnErrorList3'), ]; }, - 'async' => function () { - return new Deferred(function () { + 'async' => static function () { + return new Deferred(static function () { return 'async'; }); }, - 'asyncReject' => function () { - return new Deferred(function () { + 'asyncReject' => static function () { + return new Deferred(static function () { throw new UserError('Error getting asyncReject'); }); }, - 'asyncRawReject' => function () { - return new Deferred(function () { + 'asyncRawReject' => static function () { + return new Deferred(static function () { throw new UserError('Error getting asyncRawReject'); }); }, - 'asyncEmptyReject' => function () { - return new Deferred(function () { + 'asyncEmptyReject' => static function () { + return new Deferred(static function () { throw new UserError(); }); }, - 'asyncError' => function () { - return new Deferred(function () { + 'asyncError' => static function () { + return new Deferred(static function () { throw new UserError('Error getting asyncError'); }); }, // inherited from JS reference implementation, but make no sense in this PHP impl // leaving it just to simplify migrations from newer js versions - 'asyncRawError' => function () { - return new Deferred(function () { + 'asyncRawError' => static function () { + return new Deferred(static function () { throw new UserError('Error getting asyncRawError'); }); }, - 'asyncReturnError' => function () { - return new Deferred(function () { + 'asyncReturnError' => static function () { + return new Deferred(static function () { throw new UserError('Error getting asyncReturnError'); }); }, @@ -805,23 +806,23 @@ class ExecutorTest extends TestCase e }'; $data = [ - 'a' => function () { + 'a' => static function () { return 'a'; }, - 'b' => function () { - return new Deferred(function () { + 'b' => static function () { + return new Deferred(static function () { return 'b'; }); }, - 'c' => function () { + 'c' => static function () { return 'c'; }, - 'd' => function () { - return new Deferred(function () { + 'd' => static function () { + return new Deferred(static function () { return 'd'; }); }, - 'e' => function () { + 'e' => static function () { return 'e'; }, ]; @@ -923,7 +924,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'field' => [ 'type' => Type::string(), - 'resolve' => function ($data, $args) { + 'resolve' => static function ($data, $args) { return $args ? json_encode($args) : ''; }, 'args' => [ @@ -954,7 +955,7 @@ class ExecutorTest extends TestCase { $SpecialType = new ObjectType([ 'name' => 'SpecialType', - 'isTypeOf' => function ($obj) { + 'isTypeOf' => static function ($obj) { return $obj instanceof Special; }, 'fields' => [ @@ -968,7 +969,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'specials' => [ 'type' => Type::listOf($SpecialType), - 'resolve' => function ($rootValue) { + 'resolve' => static function ($rootValue) { return $rootValue['specials']; }, ], @@ -1049,7 +1050,7 @@ class ExecutorTest extends TestCase ]); // For the purposes of test, just return the name of the field! - $customResolver = function ($source, $args, $context, ResolveInfo $info) { + $customResolver = static function ($source, $args, $context, ResolveInfo $info) { return $info->fieldName; }; @@ -1078,7 +1079,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'field' => [ 'type' => Type::string(), - 'resolve' => function ($data, $args) { + 'resolve' => static function ($data, $args) { return $args ? json_encode($args) : ''; }, 'args' => [ @@ -1125,7 +1126,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'id' => Type::id(), ], - 'interfaces' => function () use (&$iface) { + 'interfaces' => static function () use (&$iface) { return [$iface]; }, ]); @@ -1135,7 +1136,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'id' => Type::id(), ], - 'interfaces' => function () use (&$iface) { + 'interfaces' => static function () use (&$iface) { return [$iface]; }, ]); @@ -1145,7 +1146,7 @@ class ExecutorTest extends TestCase 'fields' => [ 'id' => Type::id(), ], - 'resolveType' => function ($v) use ($a, $b) { + 'resolveType' => static function ($v) use ($a, $b) { return $v['type'] === 'A' ? $a : $b; }, ]); @@ -1187,8 +1188,8 @@ class ExecutorTest extends TestCase 'ab' => [ ['id' => '1'], ['id' => '2'], - new \stdClass(), - new \stdClass(), + new stdClass(), + new stdClass(), ], ], ], diff --git a/tests/Executor/LazyInterfaceTest.php b/tests/Executor/LazyInterfaceTest.php index 197a111..c03d40c 100644 --- a/tests/Executor/LazyInterfaceTest.php +++ b/tests/Executor/LazyInterfaceTest.php @@ -64,7 +64,7 @@ class LazyInterfaceTest extends TestCase return [ 'lazyInterface' => [ 'type' => $this->getLazyInterfaceType(), - 'resolve' => function () { + 'resolve' => static function () { return []; }, ], @@ -99,6 +99,7 @@ class LazyInterfaceTest extends TestCase /** * Returns the test ObjectType + * * @return ObjectType */ protected function getTestObjectType() @@ -109,7 +110,7 @@ class LazyInterfaceTest extends TestCase 'fields' => [ 'name' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return 'testname'; }, ], diff --git a/tests/Executor/ListsTest.php b/tests/Executor/ListsTest.php index cb63514..1ebe596 100644 --- a/tests/Executor/ListsTest.php +++ b/tests/Executor/ListsTest.php @@ -53,12 +53,12 @@ class ListsTest extends TestCase $dataType = new ObjectType([ 'name' => 'DataType', - 'fields' => function () use (&$testType, &$dataType, $data) { + 'fields' => static function () use (&$testType, &$dataType, $data) { return [ 'test' => ['type' => $testType], 'nest' => [ 'type' => $dataType, - 'resolve' => function () use ($data) { + 'resolve' => static function () use ($data) { return $data; }, ], @@ -81,7 +81,7 @@ class ListsTest extends TestCase { // Contains values $this->checkHandlesNullableLists( - new Deferred(function () { + new Deferred(static function () { return [1, 2]; }), ['data' => ['nest' => ['test' => [1, 2]]]] @@ -89,7 +89,7 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNullableLists( - new Deferred(function () { + new Deferred(static function () { return [1, null, 2]; }), ['data' => ['nest' => ['test' => [1, null, 2]]]] @@ -97,7 +97,7 @@ class ListsTest extends TestCase // Returns null $this->checkHandlesNullableLists( - new Deferred(function () { + new Deferred(static function () { return null; }), ['data' => ['nest' => ['test' => null]]] @@ -105,8 +105,8 @@ class ListsTest extends TestCase // Rejected $this->checkHandlesNullableLists( - function () { - return new Deferred(function () { + static function () { + return new Deferred(static function () { throw new UserError('bad'); }); }, @@ -131,10 +131,10 @@ class ListsTest extends TestCase // Contains values $this->checkHandlesNullableLists( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -144,13 +144,13 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNullableLists( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return null; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -159,7 +159,7 @@ class ListsTest extends TestCase // Returns null $this->checkHandlesNullableLists( - new Deferred(function () { + new Deferred(static function () { return null; }), ['data' => ['nest' => ['test' => null]]] @@ -167,15 +167,15 @@ class ListsTest extends TestCase // Contains reject $this->checkHandlesNullableLists( - function () { + static function () { return [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { throw new UserError('bad'); }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ]; @@ -239,7 +239,7 @@ class ListsTest extends TestCase { // Contains values $this->checkHandlesNonNullableLists( - new Deferred(function () { + new Deferred(static function () { return [1, 2]; }), ['data' => ['nest' => ['test' => [1, 2]]]] @@ -247,7 +247,7 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNonNullableLists( - new Deferred(function () { + new Deferred(static function () { return [1, null, 2]; }), ['data' => ['nest' => ['test' => [1, null, 2]]]] @@ -270,8 +270,8 @@ class ListsTest extends TestCase // Rejected $this->checkHandlesNonNullableLists( - function () { - return new Deferred(function () { + static function () { + return new Deferred(static function () { throw new UserError('bad'); }); }, @@ -296,10 +296,10 @@ class ListsTest extends TestCase // Contains values $this->checkHandlesNonNullableLists( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -309,13 +309,13 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNonNullableLists( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return null; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -324,15 +324,15 @@ class ListsTest extends TestCase // Contains reject $this->checkHandlesNonNullableLists( - function () { + static function () { return [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { throw new UserError('bad'); }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ]; @@ -396,7 +396,7 @@ class ListsTest extends TestCase { // Contains values $this->checkHandlesListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return [1, 2]; }), ['data' => ['nest' => ['test' => [1, 2]]]] @@ -404,7 +404,7 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return [1, null, 2]; }), [ @@ -421,7 +421,7 @@ class ListsTest extends TestCase // Returns null $this->checkHandlesListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return null; }), ['data' => ['nest' => ['test' => null]]] @@ -429,8 +429,8 @@ class ListsTest extends TestCase // Rejected $this->checkHandlesListOfNonNulls( - function () { - return new Deferred(function () { + static function () { + return new Deferred(static function () { throw new UserError('bad'); }); }, @@ -455,10 +455,10 @@ class ListsTest extends TestCase // Contains values $this->checkHandlesListOfNonNulls( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -468,13 +468,13 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesListOfNonNulls( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return null; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -483,15 +483,15 @@ class ListsTest extends TestCase // Contains reject $this->checkHandlesListOfNonNulls( - function () { + static function () { return [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { throw new UserError('bad'); }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ]; @@ -564,7 +564,7 @@ class ListsTest extends TestCase { // Contains values $this->checkHandlesNonNullListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return [1, 2]; }), ['data' => ['nest' => ['test' => [1, 2]]]] @@ -572,7 +572,7 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNonNullListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return [1, null, 2]; }), [ @@ -589,7 +589,7 @@ class ListsTest extends TestCase // Returns null $this->checkHandlesNonNullListOfNonNulls( - new Deferred(function () { + new Deferred(static function () { return null; }), [ @@ -606,8 +606,8 @@ class ListsTest extends TestCase // Rejected $this->checkHandlesNonNullListOfNonNulls( - function () { - return new Deferred(function () { + static function () { + return new Deferred(static function () { throw new UserError('bad'); }); }, @@ -632,10 +632,10 @@ class ListsTest extends TestCase // Contains values $this->checkHandlesNonNullListOfNonNulls( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), @@ -646,13 +646,13 @@ class ListsTest extends TestCase // Contains null $this->checkHandlesNonNullListOfNonNulls( [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { return null; }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ], @@ -670,15 +670,15 @@ class ListsTest extends TestCase // Contains reject $this->checkHandlesNonNullListOfNonNulls( - function () { + static function () { return [ - new Deferred(function () { + new Deferred(static function () { return 1; }), - new Deferred(function () { + new Deferred(static function () { throw new UserError('bad'); }), - new Deferred(function () { + new Deferred(static function () { return 2; }), ]; diff --git a/tests/Executor/MutationsTest.php b/tests/Executor/MutationsTest.php index fa161f6..6671b2d 100644 --- a/tests/Executor/MutationsTest.php +++ b/tests/Executor/MutationsTest.php @@ -59,7 +59,7 @@ class MutationsTest extends TestCase ], 'name' => 'NumberHolder', ]); - $schema = new Schema([ + return new Schema([ 'query' => new ObjectType([ 'fields' => [ 'numberHolder' => ['type' => $numberHolderType], @@ -71,28 +71,28 @@ class MutationsTest extends TestCase 'immediatelyChangeTheNumber' => [ 'type' => $numberHolderType, 'args' => ['newNumber' => ['type' => Type::int()]], - 'resolve' => function (Root $obj, $args) { + 'resolve' => static function (Root $obj, $args) { return $obj->immediatelyChangeTheNumber($args['newNumber']); }, ], 'promiseToChangeTheNumber' => [ 'type' => $numberHolderType, 'args' => ['newNumber' => ['type' => Type::int()]], - 'resolve' => function (Root $obj, $args) { + 'resolve' => static function (Root $obj, $args) { return $obj->promiseToChangeTheNumber($args['newNumber']); }, ], 'failToChangeTheNumber' => [ 'type' => $numberHolderType, 'args' => ['newNumber' => ['type' => Type::int()]], - 'resolve' => function (Root $obj, $args) { + 'resolve' => static function (Root $obj, $args) { $obj->failToChangeTheNumber(); }, ], 'promiseAndFailToChangeTheNumber' => [ 'type' => $numberHolderType, 'args' => ['newNumber' => ['type' => Type::int()]], - 'resolve' => function (Root $obj, $args) { + 'resolve' => static function (Root $obj, $args) { return $obj->promiseAndFailToChangeTheNumber(); }, ], @@ -100,8 +100,6 @@ class MutationsTest extends TestCase 'name' => 'Mutation', ]), ]); - - return $schema; } /** diff --git a/tests/Executor/NonNullTest.php b/tests/Executor/NonNullTest.php index e9f666e..8601cc5 100644 --- a/tests/Executor/NonNullTest.php +++ b/tests/Executor/NonNullTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Executor; +use Exception; use GraphQL\Deferred; use GraphQL\Error\FormattedError; use GraphQL\Error\UserError; @@ -17,16 +18,16 @@ use PHPUnit\Framework\TestCase; class NonNullTest extends TestCase { - /** @var \Exception */ + /** @var Exception */ public $syncError; - /** @var \Exception */ + /** @var Exception */ public $syncNonNullError; - /** @var \Exception */ + /** @var Exception */ public $promiseError; - /** @var \Exception */ + /** @var Exception */ public $promiseNonNullError; /** @var callable[] */ @@ -81,19 +82,19 @@ class NonNullTest extends TestCase ]; $this->nullingData = [ - 'sync' => function () { + 'sync' => static function () { return null; }, - 'syncNonNull' => function () { + 'syncNonNull' => static function () { return null; }, - 'promise' => function () { - return new Deferred(function () { + 'promise' => static function () { + return new Deferred(static function () { return null; }); }, - 'promiseNonNull' => function () { - return new Deferred(function () { + 'promiseNonNull' => static function () { + return new Deferred(static function () { return null; }); }, @@ -117,7 +118,7 @@ class NonNullTest extends TestCase $dataType = new ObjectType([ 'name' => 'DataType', - 'fields' => function () use (&$dataType) { + 'fields' => static function () use (&$dataType) { return [ 'sync' => ['type' => Type::string()], 'syncNonNull' => ['type' => Type::nonNull(Type::string())], diff --git a/tests/Executor/Promise/ReactPromiseAdapterTest.php b/tests/Executor/Promise/ReactPromiseAdapterTest.php index 3023ddd..a616613 100644 --- a/tests/Executor/Promise/ReactPromiseAdapterTest.php +++ b/tests/Executor/Promise/ReactPromiseAdapterTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Executor\Promise; +use Exception; use GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter; use PHPUnit\Framework\TestCase; use React\Promise\Deferred; @@ -11,6 +12,7 @@ use React\Promise\FulfilledPromise; use React\Promise\LazyPromise; use React\Promise\Promise as ReactPromise; use React\Promise\RejectedPromise; +use stdClass; use function class_exists; /** @@ -32,13 +34,13 @@ class ReactPromiseAdapterTest extends TestCase $reactAdapter = new ReactPromiseAdapter(); self::assertTrue( - $reactAdapter->isThenable(new ReactPromise(function () { + $reactAdapter->isThenable(new ReactPromise(static function () { })) ); self::assertTrue($reactAdapter->isThenable(new FulfilledPromise())); self::assertTrue($reactAdapter->isThenable(new RejectedPromise())); self::assertTrue( - $reactAdapter->isThenable(new LazyPromise(function () { + $reactAdapter->isThenable(new LazyPromise(static function () { })) ); self::assertFalse($reactAdapter->isThenable(false)); @@ -48,7 +50,7 @@ class ReactPromiseAdapterTest extends TestCase self::assertFalse($reactAdapter->isThenable('test')); self::assertFalse($reactAdapter->isThenable('')); self::assertFalse($reactAdapter->isThenable([])); - self::assertFalse($reactAdapter->isThenable(new \stdClass())); + self::assertFalse($reactAdapter->isThenable(new stdClass())); } public function testConvertsReactPromisesToGraphQlOnes() : void @@ -72,7 +74,7 @@ class ReactPromiseAdapterTest extends TestCase $resultPromise = $reactAdapter->then( $promise, - function ($value) use (&$result) { + static function ($value) use (&$result) { $result = $value; } ); @@ -85,7 +87,7 @@ class ReactPromiseAdapterTest extends TestCase public function testCreate() : void { $reactAdapter = new ReactPromiseAdapter(); - $resolvedPromise = $reactAdapter->create(function ($resolve) { + $resolvedPromise = $reactAdapter->create(static function ($resolve) { $resolve(1); }); @@ -94,7 +96,7 @@ class ReactPromiseAdapterTest extends TestCase $result = null; - $resolvedPromise->then(function ($value) use (&$result) { + $resolvedPromise->then(static function ($value) use (&$result) { $result = $value; }); @@ -111,7 +113,7 @@ class ReactPromiseAdapterTest extends TestCase $result = null; - $fulfilledPromise->then(function ($value) use (&$result) { + $fulfilledPromise->then(static function ($value) use (&$result) { $result = $value; }); @@ -121,7 +123,7 @@ class ReactPromiseAdapterTest extends TestCase public function testCreateRejected() : void { $reactAdapter = new ReactPromiseAdapter(); - $rejectedPromise = $reactAdapter->createRejected(new \Exception('I am a bad promise')); + $rejectedPromise = $reactAdapter->createRejected(new Exception('I am a bad promise')); self::assertInstanceOf('GraphQL\Executor\Promise\Promise', $rejectedPromise); self::assertInstanceOf('React\Promise\RejectedPromise', $rejectedPromise->adoptedPromise); @@ -130,7 +132,7 @@ class ReactPromiseAdapterTest extends TestCase $rejectedPromise->then( null, - function ($error) use (&$exception) { + static function ($error) use (&$exception) { $exception = $error; } ); @@ -151,7 +153,7 @@ class ReactPromiseAdapterTest extends TestCase $result = null; - $allPromise->then(function ($values) use (&$result) { + $allPromise->then(static function ($values) use (&$result) { $result = $values; }); @@ -165,7 +167,7 @@ class ReactPromiseAdapterTest extends TestCase $promises = [new FulfilledPromise(1), $deferred->promise(), new FulfilledPromise(3)]; $result = null; - $reactAdapter->all($promises)->then(function ($values) use (&$result) { + $reactAdapter->all($promises)->then(static function ($values) use (&$result) { $result = $values; }); diff --git a/tests/Executor/Promise/SyncPromiseAdapterTest.php b/tests/Executor/Promise/SyncPromiseAdapterTest.php index f1cf46f..b9d97b5 100644 --- a/tests/Executor/Promise/SyncPromiseAdapterTest.php +++ b/tests/Executor/Promise/SyncPromiseAdapterTest.php @@ -4,12 +4,15 @@ declare(strict_types=1); namespace GraphQL\Tests\Executor\Promise; +use Exception; use GraphQL\Deferred; use GraphQL\Error\InvariantViolation; use GraphQL\Executor\Promise\Adapter\SyncPromise; use GraphQL\Executor\Promise\Adapter\SyncPromiseAdapter; use GraphQL\Executor\Promise\Promise; use PHPUnit\Framework\TestCase; +use stdClass; +use Throwable; class SyncPromiseAdapterTest extends TestCase { @@ -25,7 +28,7 @@ class SyncPromiseAdapterTest extends TestCase { self::assertEquals( true, - $this->promises->isThenable(new Deferred(function () { + $this->promises->isThenable(new Deferred(static function () { })) ); self::assertEquals(false, $this->promises->isThenable(false)); @@ -35,12 +38,12 @@ class SyncPromiseAdapterTest extends TestCase self::assertEquals(false, $this->promises->isThenable('test')); self::assertEquals(false, $this->promises->isThenable('')); self::assertEquals(false, $this->promises->isThenable([])); - self::assertEquals(false, $this->promises->isThenable(new \stdClass())); + self::assertEquals(false, $this->promises->isThenable(new stdClass())); } public function testConvert() : void { - $dfd = new Deferred(function () { + $dfd = new Deferred(static function () { }); $result = $this->promises->convertThenable($dfd); @@ -54,7 +57,7 @@ class SyncPromiseAdapterTest extends TestCase public function testThen() : void { - $dfd = new Deferred(function () { + $dfd = new Deferred(static function () { }); $promise = $this->promises->convertThenable($dfd); @@ -66,13 +69,13 @@ class SyncPromiseAdapterTest extends TestCase public function testCreatePromise() : void { - $promise = $this->promises->create(function ($resolve, $reject) { + $promise = $this->promises->create(static function ($resolve, $reject) { }); self::assertInstanceOf('GraphQL\Executor\Promise\Promise', $promise); self::assertInstanceOf('GraphQL\Executor\Promise\Adapter\SyncPromise', $promise->adoptedPromise); - $promise = $this->promises->create(function ($resolve, $reject) { + $promise = $this->promises->create(static function ($resolve, $reject) { $resolve('A'); }); @@ -90,11 +93,11 @@ class SyncPromiseAdapterTest extends TestCase $onRejectedCalled = false; $promise->then( - function ($nextValue) use (&$actualNextValue, &$onFulfilledCalled) { + static function ($nextValue) use (&$actualNextValue, &$onFulfilledCalled) { $onFulfilledCalled = true; $actualNextValue = $nextValue; }, - function (\Throwable $reason) use (&$actualNextReason, &$onRejectedCalled) { + static function (Throwable $reason) use (&$actualNextReason, &$onRejectedCalled) { $onRejectedCalled = true; $actualNextReason = $reason->getMessage(); } @@ -123,7 +126,7 @@ class SyncPromiseAdapterTest extends TestCase public function testCreateRejectedPromise() : void { - $promise = $this->promises->createRejected(new \Exception('test reason')); + $promise = $this->promises->createRejected(new Exception('test reason')); self::assertValidPromise($promise, 'test reason', null, SyncPromise::REJECTED); } @@ -138,7 +141,7 @@ class SyncPromiseAdapterTest extends TestCase $promise1 = new SyncPromise(); $promise2 = new SyncPromise(); $promise3 = $promise2->then( - function ($value) { + static function ($value) { return $value . '-value3'; } ); @@ -170,12 +173,12 @@ class SyncPromiseAdapterTest extends TestCase { $called = []; - $deferred1 = new Deferred(function () use (&$called) { + $deferred1 = new Deferred(static function () use (&$called) { $called[] = 1; return 1; }); - $deferred2 = new Deferred(function () use (&$called) { + $deferred2 = new Deferred(static function () use (&$called) { $called[] = 2; return 2; @@ -185,7 +188,7 @@ class SyncPromiseAdapterTest extends TestCase $p2 = $this->promises->convertThenable($deferred2); $p3 = $p2->then(function () use (&$called) { - $dfd = new Deferred(function () use (&$called) { + $dfd = new Deferred(static function () use (&$called) { $called[] = 3; return 3; @@ -194,8 +197,8 @@ class SyncPromiseAdapterTest extends TestCase return $this->promises->convertThenable($dfd); }); - $p4 = $p3->then(function () use (&$called) { - return new Deferred(function () use (&$called) { + $p4 = $p3->then(static function () use (&$called) { + return new Deferred(static function () use (&$called) { $called[] = 4; return 4; diff --git a/tests/Executor/Promise/SyncPromiseTest.php b/tests/Executor/Promise/SyncPromiseTest.php index e2e12c2..302715c 100644 --- a/tests/Executor/Promise/SyncPromiseTest.php +++ b/tests/Executor/Promise/SyncPromiseTest.php @@ -4,29 +4,31 @@ declare(strict_types=1); namespace GraphQL\Tests\Executor\Promise; +use Exception; use GraphQL\Executor\Promise\Adapter\SyncPromise; use PHPUnit\Framework\Error\Error; use PHPUnit\Framework\TestCase; +use Throwable; use function uniqid; class SyncPromiseTest extends TestCase { public function getFulfilledPromiseResolveData() { - $onFulfilledReturnsNull = function () { + $onFulfilledReturnsNull = static function () { return null; }; - $onFulfilledReturnsSameValue = function ($value) { + $onFulfilledReturnsSameValue = static function ($value) { return $value; }; - $onFulfilledReturnsOtherValue = function ($value) { + $onFulfilledReturnsOtherValue = static function ($value) { return 'other-' . $value; }; - $onFulfilledThrows = function ($value) { - throw new \Exception('onFulfilled throws this!'); + $onFulfilledThrows = static function ($value) { + throw new Exception('onFulfilled throws this!'); }; return [ @@ -55,7 +57,7 @@ class SyncPromiseTest extends TestCase $promise->resolve($resolvedValue); self::assertEquals(SyncPromise::FULFILLED, $promise->state); - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Cannot change value of fulfilled promise'); $promise->resolve($resolvedValue . '-other-value'); } @@ -76,9 +78,9 @@ class SyncPromiseTest extends TestCase $promise->resolve($resolvedValue); self::assertEquals(SyncPromise::FULFILLED, $promise->state); - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Cannot reject fulfilled promise'); - $promise->reject(new \Exception('anything')); + $promise->reject(new Exception('anything')); } /** @@ -99,7 +101,7 @@ class SyncPromiseTest extends TestCase $nextPromise = $promise->then( null, - function () { + static function () { } ); self::assertSame($promise, $nextPromise); @@ -107,7 +109,7 @@ class SyncPromiseTest extends TestCase $onRejectedCalled = false; $nextPromise = $promise->then( $onFulfilled, - function () use (&$onRejectedCalled) { + static function () use (&$onRejectedCalled) { $onRejectedCalled = true; } ); @@ -151,7 +153,7 @@ class SyncPromiseTest extends TestCase $onFulfilledCalled = true; $actualNextValue = $nextValue; }, - static function (\Throwable $reason) use (&$actualNextReason, &$onRejectedCalled) { + static function (Throwable $reason) use (&$actualNextReason, &$onRejectedCalled) { $onRejectedCalled = true; $actualNextReason = $reason->getMessage(); } @@ -172,29 +174,29 @@ class SyncPromiseTest extends TestCase public function getRejectedPromiseData() { - $onRejectedReturnsNull = function () { + $onRejectedReturnsNull = static function () { return null; }; - $onRejectedReturnsSomeValue = function ($reason) { + $onRejectedReturnsSomeValue = static function ($reason) { return 'some-value'; }; - $onRejectedThrowsSameReason = function ($reason) { + $onRejectedThrowsSameReason = static function ($reason) { throw $reason; }; - $onRejectedThrowsOtherReason = function ($value) { - throw new \Exception('onRejected throws other!'); + $onRejectedThrowsOtherReason = static function ($value) { + throw new Exception('onRejected throws other!'); }; return [ // $rejectedReason, $onRejected, $expectedNextValue, $expectedNextReason, $expectedNextState - [new \Exception('test-reason'), null, null, 'test-reason', SyncPromise::REJECTED], - [new \Exception('test-reason-2'), $onRejectedReturnsNull, null, null, SyncPromise::FULFILLED], - [new \Exception('test-reason-3'), $onRejectedReturnsSomeValue, 'some-value', null, SyncPromise::FULFILLED], - [new \Exception('test-reason-4'), $onRejectedThrowsSameReason, null, 'test-reason-4', SyncPromise::REJECTED], - [new \Exception('test-reason-5'), $onRejectedThrowsOtherReason, null, 'onRejected throws other!', SyncPromise::REJECTED], + [new Exception('test-reason'), null, null, 'test-reason', SyncPromise::REJECTED], + [new Exception('test-reason-2'), $onRejectedReturnsNull, null, null, SyncPromise::FULFILLED], + [new Exception('test-reason-3'), $onRejectedReturnsSomeValue, 'some-value', null, SyncPromise::FULFILLED], + [new Exception('test-reason-4'), $onRejectedThrowsSameReason, null, 'test-reason-4', SyncPromise::REJECTED], + [new Exception('test-reason-5'), $onRejectedThrowsOtherReason, null, 'onRejected throws other!', SyncPromise::REJECTED], ]; } @@ -214,9 +216,9 @@ class SyncPromiseTest extends TestCase $promise->reject($rejectedReason); self::assertEquals(SyncPromise::REJECTED, $promise->state); - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Cannot change rejection reason'); - $promise->reject(new \Exception('other-reason')); + $promise->reject(new Exception('other-reason')); } /** @@ -235,7 +237,7 @@ class SyncPromiseTest extends TestCase $promise->reject($rejectedReason); self::assertEquals(SyncPromise::REJECTED, $promise->state); - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Cannot resolve rejected promise'); $promise->resolve('anything'); } @@ -257,21 +259,21 @@ class SyncPromiseTest extends TestCase self::assertEquals(SyncPromise::REJECTED, $promise->state); try { - $promise->reject(new \Exception('other-reason')); + $promise->reject(new Exception('other-reason')); $this->fail('Expected exception not thrown'); - } catch (\Throwable $e) { + } catch (Throwable $e) { self::assertEquals('Cannot change rejection reason', $e->getMessage()); } try { $promise->resolve('anything'); $this->fail('Expected exception not thrown'); - } catch (\Throwable $e) { + } catch (Throwable $e) { self::assertEquals('Cannot resolve rejected promise', $e->getMessage()); } $nextPromise = $promise->then( - function () { + static function () { }, null ); @@ -279,7 +281,7 @@ class SyncPromiseTest extends TestCase $onFulfilledCalled = false; $nextPromise = $promise->then( - function () use (&$onFulfilledCalled) { + static function () use (&$onFulfilledCalled) { $onFulfilledCalled = true; }, $onRejected @@ -315,7 +317,7 @@ class SyncPromiseTest extends TestCase try { $promise->resolve($promise); $this->fail('Expected exception not thrown'); - } catch (\Throwable $e) { + } catch (Throwable $e) { self::assertEquals('Cannot resolve promise with self', $e->getMessage()); self::assertEquals(SyncPromise::PENDING, $promise->state); } @@ -346,26 +348,26 @@ class SyncPromiseTest extends TestCase $this->fail('Expected exception not thrown'); } catch (Error $e) { throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { self::assertEquals(SyncPromise::PENDING, $promise->state); } - $promise->reject(new \Exception('Rejected Reason')); + $promise->reject(new Exception('Rejected Reason')); self::assertValidPromise($promise, 'Rejected Reason', null, SyncPromise::REJECTED); $promise = new SyncPromise(); $promise2 = $promise->then( null, - function () { + static function () { return 'value'; } ); - $promise->reject(new \Exception('Rejected Again')); + $promise->reject(new Exception('Rejected Again')); self::assertValidPromise($promise2, null, 'value', SyncPromise::FULFILLED); $promise = new SyncPromise(); $promise2 = $promise->then(); - $promise->reject(new \Exception('Rejected Once Again')); + $promise->reject(new Exception('Rejected Once Again')); self::assertValidPromise($promise2, 'Rejected Once Again', null, SyncPromise::REJECTED); } @@ -382,13 +384,13 @@ class SyncPromiseTest extends TestCase // Make sure that it queues derivative promises until resolution: $onFulfilledCount = 0; $onRejectedCount = 0; - $onFulfilled = function ($value) use (&$onFulfilledCount) { + $onFulfilled = static function ($value) use (&$onFulfilledCount) { $onFulfilledCount++; return $onFulfilledCount; }; - $onRejected = function ($reason) use (&$onRejectedCount) { + $onRejected = static function ($reason) use (&$onRejectedCount) { $onRejectedCount++; throw $reason; }; diff --git a/tests/Executor/ResolveTest.php b/tests/Executor/ResolveTest.php index dbc82c4..8fe4ab7 100644 --- a/tests/Executor/ResolveTest.php +++ b/tests/Executor/ResolveTest.php @@ -51,7 +51,7 @@ class ResolveTest extends TestCase $_secret = 'secretValue' . uniqid(); $source = [ - 'test' => function () use ($_secret) { + 'test' => static function () use ($_secret) { return $_secret; }, ]; @@ -90,7 +90,7 @@ class ResolveTest extends TestCase 'aStr' => ['type' => Type::string()], 'aInt' => ['type' => Type::int()], ], - 'resolve' => function ($source, $args) { + 'resolve' => static function ($source, $args) { return json_encode([$source, $args]); }, ]); diff --git a/tests/Executor/SyncTest.php b/tests/Executor/SyncTest.php index cb99832..e2255fa 100644 --- a/tests/Executor/SyncTest.php +++ b/tests/Executor/SyncTest.php @@ -36,14 +36,14 @@ class SyncTest extends TestCase 'fields' => [ 'syncField' => [ 'type' => Type::string(), - 'resolve' => function ($rootValue) { + 'resolve' => static function ($rootValue) { return $rootValue; }, ], 'asyncField' => [ 'type' => Type::string(), - 'resolve' => function ($rootValue) { - return new Deferred(function () use ($rootValue) { + 'resolve' => static function ($rootValue) { + return new Deferred(static function () use ($rootValue) { return $rootValue; }); }, @@ -55,7 +55,7 @@ class SyncTest extends TestCase 'fields' => [ 'syncMutationField' => [ 'type' => Type::string(), - 'resolve' => function ($rootValue) { + 'resolve' => static function ($rootValue) { return $rootValue; }, ], @@ -199,7 +199,7 @@ class SyncTest extends TestCase $expected = [ 'errors' => Utils::map( $validationErrors, - function ($e) { + static function ($e) { return FormattedError::createFromException($e); } ), diff --git a/tests/Executor/TestClasses/Root.php b/tests/Executor/TestClasses/Root.php index 812db16..6263bd9 100644 --- a/tests/Executor/TestClasses/Root.php +++ b/tests/Executor/TestClasses/Root.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Executor\TestClasses; +use Exception; use GraphQL\Deferred; class Root @@ -32,7 +33,7 @@ class Root public function failToChangeTheNumber() : void { - throw new \Exception('Cannot change the number'); + throw new Exception('Cannot change the number'); } public function promiseAndFailToChangeTheNumber() : Deferred diff --git a/tests/Executor/UnionInterfaceTest.php b/tests/Executor/UnionInterfaceTest.php index 03091c9..f8ce41a 100644 --- a/tests/Executor/UnionInterfaceTest.php +++ b/tests/Executor/UnionInterfaceTest.php @@ -51,7 +51,7 @@ class UnionInterfaceTest extends TestCase 'name' => ['type' => Type::string()], 'woofs' => ['type' => Type::boolean()], ], - 'isTypeOf' => function ($value) { + 'isTypeOf' => static function ($value) { return $value instanceof Dog; }, ]); @@ -63,7 +63,7 @@ class UnionInterfaceTest extends TestCase 'name' => ['type' => Type::string()], 'meows' => ['type' => Type::boolean()], ], - 'isTypeOf' => function ($value) { + 'isTypeOf' => static function ($value) { return $value instanceof Cat; }, ]); @@ -71,7 +71,7 @@ class UnionInterfaceTest extends TestCase $PetType = new UnionType([ 'name' => 'Pet', 'types' => [$DogType, $CatType], - 'resolveType' => function ($value) use ($DogType, $CatType) { + 'resolveType' => static function ($value) use ($DogType, $CatType) { if ($value instanceof Dog) { return $DogType; } @@ -89,7 +89,7 @@ class UnionInterfaceTest extends TestCase 'pets' => ['type' => Type::listOf($PetType)], 'friends' => ['type' => Type::listOf($NamedType)], ], - 'isTypeOf' => function ($value) { + 'isTypeOf' => static function ($value) { return $value instanceof Person; }, ]); @@ -376,7 +376,7 @@ class UnionInterfaceTest extends TestCase 'fields' => [ 'name' => ['type' => Type::string()], ], - 'resolveType' => function ( + 'resolveType' => static function ( $obj, $context, ResolveInfo $info diff --git a/tests/Executor/ValuesTest.php b/tests/Executor/ValuesTest.php index 24e5916..b0bc05a 100644 --- a/tests/Executor/ValuesTest.php +++ b/tests/Executor/ValuesTest.php @@ -43,6 +43,7 @@ class ValuesTest extends TestCase /** * @param mixed[] $variables + * * @return mixed[] */ private function runTestCase($variables) : array diff --git a/tests/Executor/VariablesTest.php b/tests/Executor/VariablesTest.php index 3a13e2a..0751c67 100644 --- a/tests/Executor/VariablesTest.php +++ b/tests/Executor/VariablesTest.php @@ -156,7 +156,7 @@ class VariablesTest extends TestCase return [ 'type' => Type::string(), 'args' => ['input' => $inputArg], - 'resolve' => function ($_, $args) { + 'resolve' => static function ($_, $args) { if (isset($args['input'])) { return json_encode($args['input']); } diff --git a/tests/Language/LexerTest.php b/tests/Language/LexerTest.php index a5b6823..ccb360d 100644 --- a/tests/Language/LexerTest.php +++ b/tests/Language/LexerTest.php @@ -42,6 +42,7 @@ class LexerTest extends TestCase /** * @param string $body + * * @return Token */ private function lexOne($body) @@ -433,8 +434,9 @@ class LexerTest extends TestCase } /** - * @dataProvider reportsUsefulStringErrors * @see it('lex reports useful string errors') + * + * @dataProvider reportsUsefulStringErrors */ public function testLexReportsUsefulStringErrors($str, $expectedMessage, $location) : void { @@ -466,8 +468,9 @@ class LexerTest extends TestCase } /** - * @dataProvider reportsUsefulBlockStringErrors * @see it('lex reports useful block string errors') + * + * @dataProvider reportsUsefulBlockStringErrors */ public function testReportsUsefulBlockStringErrors($str, $expectedMessage, $location) : void { @@ -561,8 +564,9 @@ class LexerTest extends TestCase } /** - * @dataProvider reportsUsefulNumberErrors * @see it('lex reports useful number errors') + * + * @dataProvider reportsUsefulNumberErrors */ public function testReportsUsefulNumberErrors($str, $expectedMessage, $location) : void { @@ -642,8 +646,9 @@ class LexerTest extends TestCase } /** - * @dataProvider reportsUsefulUnknownCharErrors * @see it('lex reports useful unknown character error') + * + * @dataProvider reportsUsefulUnknownCharErrors */ public function testReportsUsefulUnknownCharErrors($str, $expectedMessage, $location) : void { @@ -714,7 +719,7 @@ class LexerTest extends TestCase ], Utils::map( $tokens, - function ($tok) { + static function ($tok) { return $tok->kind; } ) diff --git a/tests/Language/ParserTest.php b/tests/Language/ParserTest.php index 6c83f59..1427739 100644 --- a/tests/Language/ParserTest.php +++ b/tests/Language/ParserTest.php @@ -19,6 +19,7 @@ use GraphQL\Language\Source; use GraphQL\Language\SourceLocation; use GraphQL\Utils\Utils; use PHPUnit\Framework\TestCase; +use stdClass; use function file_get_contents; use function sprintf; @@ -42,7 +43,7 @@ class ParserTest extends TestCase { $this->expectException(InvariantViolation::class); $this->expectExceptionMessage('GraphQL query body is expected to be string, but got stdClass'); - Parser::parse(new \stdClass()); + Parser::parse(new stdClass()); } public function parseProvidesUsefulErrors() @@ -72,8 +73,9 @@ fragment MissingOn Type } /** - * @dataProvider parseProvidesUsefulErrors * @see it('parse provides useful errors') + * + * @dataProvider parseProvidesUsefulErrors */ public function testParseProvidesUsefulErrors( $str, @@ -331,7 +333,7 @@ GRAPHQL '); $result = Parser::parse($source); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return [ 'start' => $start, 'end' => $end, @@ -442,7 +444,7 @@ GRAPHQL '); $result = Parser::parse($source); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return [ 'start' => $start, 'end' => $end, diff --git a/tests/Language/PrinterTest.php b/tests/Language/PrinterTest.php index 491871d..91e8514 100644 --- a/tests/Language/PrinterTest.php +++ b/tests/Language/PrinterTest.php @@ -4,11 +4,13 @@ declare(strict_types=1); namespace GraphQL\Tests\Language; +use ArrayObject; use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\NameNode; use GraphQL\Language\Parser; use GraphQL\Language\Printer; use PHPUnit\Framework\TestCase; +use Throwable; use function file_get_contents; class PrinterTest extends TestCase @@ -42,8 +44,8 @@ class PrinterTest extends TestCase */ public function testProducesHelpfulErrorMessages() : void { - $badAst1 = new \ArrayObject(['random' => 'Data']); - $this->expectException(\Throwable::class); + $badAst1 = new ArrayObject(['random' => 'Data']); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Invalid AST Node: {"random":"Data"}'); Printer::doPrint($badAst1); } diff --git a/tests/Language/SchemaParserTest.php b/tests/Language/SchemaParserTest.php index 5583957..d3ce873 100644 --- a/tests/Language/SchemaParserTest.php +++ b/tests/Language/SchemaParserTest.php @@ -23,7 +23,7 @@ type Hello { world: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -98,7 +98,7 @@ type Hello { world: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -145,7 +145,7 @@ type Hello { world: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -189,7 +189,7 @@ extend type Hello { } '; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -223,7 +223,7 @@ extend type Hello { { $body = 'extend type Hello implements Greeting'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -356,7 +356,7 @@ type Hello { }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -396,7 +396,7 @@ type Hello { { $body = 'type Hello implements World { field: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -434,7 +434,7 @@ type Hello { { $body = 'type Hello implements Wo & rld { field: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -473,7 +473,7 @@ type Hello { { $body = 'type Hello implements & Wo & rld { field: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -511,7 +511,7 @@ type Hello { { $body = 'enum Hello { WORLD }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -551,7 +551,7 @@ type Hello { { $body = 'enum Hello { WO, RLD }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -586,7 +586,7 @@ interface Hello { world: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -623,7 +623,7 @@ type Hello { world(flag: Boolean): String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -683,7 +683,7 @@ type Hello { world(flag: Boolean = true): String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -729,7 +729,7 @@ type Hello { world(things: [String]): String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -782,7 +782,7 @@ type Hello { world(argOne: Boolean, argTwo: Int): String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -832,7 +832,7 @@ type Hello { { $body = 'union Hello = World'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -861,7 +861,7 @@ type Hello { { $body = 'union Hello = Wo | Rld'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -967,7 +967,7 @@ type Hello { { $body = 'scalar Hello'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; @@ -997,7 +997,7 @@ input Hello { world: String }'; $doc = Parser::parse($body); - $loc = function ($start, $end) { + $loc = static function ($start, $end) { return TestUtils::locArray($start, $end); }; diff --git a/tests/Language/VisitorTest.php b/tests/Language/VisitorTest.php index 419dcc6..4a04326 100644 --- a/tests/Language/VisitorTest.php +++ b/tests/Language/VisitorTest.php @@ -68,7 +68,7 @@ class VisitorTest extends ValidatorTestCase private function checkVisitorFnArgs($ast, $args, $isEdited = false) { /** @var Node $node */ - list($node, $key, $parent, $path, $ancestors) = $args; + [$node, $key, $parent, $path, $ancestors] = $args; $parentArray = $parent && ! is_array($parent) ? ($parent instanceof NodeList ? iterator_to_array($parent) : $parent->toArray()) : $parent; @@ -880,21 +880,21 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null], - ['enter', 'OperationDefinition', null], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'c'], - ['leave', 'Name', 'c'], - ['leave', 'Field', null], - ['leave', 'SelectionSet', null], - ['leave', 'OperationDefinition', null], - ['leave', 'Document', null], + ['enter', 'Document', null], + ['enter', 'OperationDefinition', null], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'c'], + ['leave', 'Name', 'c'], + ['leave', 'Field', null], + ['leave', 'SelectionSet', null], + ['leave', 'OperationDefinition', null], + ['leave', 'Document', null], ], $visited ); @@ -939,40 +939,40 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['no-a', 'enter', 'Document', null], - ['no-b', 'enter', 'Document', null], - ['no-a', 'enter', 'OperationDefinition', null], - ['no-b', 'enter', 'OperationDefinition', null], - ['no-a', 'enter', 'SelectionSet', null], - ['no-b', 'enter', 'SelectionSet', null], - ['no-a', 'enter', 'Field', null], - ['no-b', 'enter', 'Field', null], - ['no-b', 'enter', 'Name', 'a'], - ['no-b', 'leave', 'Name', 'a'], - ['no-b', 'enter', 'SelectionSet', null], - ['no-b', 'enter', 'Field', null], - ['no-b', 'enter', 'Name', 'x'], - ['no-b', 'leave', 'Name', 'x'], - ['no-b', 'leave', 'Field', null], - ['no-b', 'leave', 'SelectionSet', null], - ['no-b', 'leave', 'Field', null], - ['no-a', 'enter', 'Field', null], - ['no-b', 'enter', 'Field', null], - ['no-a', 'enter', 'Name', 'b'], - ['no-a', 'leave', 'Name', 'b'], - ['no-a', 'enter', 'SelectionSet', null], - ['no-a', 'enter', 'Field', null], - ['no-a', 'enter', 'Name', 'y'], - ['no-a', 'leave', 'Name', 'y'], - ['no-a', 'leave', 'Field', null], - ['no-a', 'leave', 'SelectionSet', null], - ['no-a', 'leave', 'Field', null], - ['no-a', 'leave', 'SelectionSet', null], - ['no-b', 'leave', 'SelectionSet', null], - ['no-a', 'leave', 'OperationDefinition', null], - ['no-b', 'leave', 'OperationDefinition', null], - ['no-a', 'leave', 'Document', null], - ['no-b', 'leave', 'Document', null], + ['no-a', 'enter', 'Document', null], + ['no-b', 'enter', 'Document', null], + ['no-a', 'enter', 'OperationDefinition', null], + ['no-b', 'enter', 'OperationDefinition', null], + ['no-a', 'enter', 'SelectionSet', null], + ['no-b', 'enter', 'SelectionSet', null], + ['no-a', 'enter', 'Field', null], + ['no-b', 'enter', 'Field', null], + ['no-b', 'enter', 'Name', 'a'], + ['no-b', 'leave', 'Name', 'a'], + ['no-b', 'enter', 'SelectionSet', null], + ['no-b', 'enter', 'Field', null], + ['no-b', 'enter', 'Name', 'x'], + ['no-b', 'leave', 'Name', 'x'], + ['no-b', 'leave', 'Field', null], + ['no-b', 'leave', 'SelectionSet', null], + ['no-b', 'leave', 'Field', null], + ['no-a', 'enter', 'Field', null], + ['no-b', 'enter', 'Field', null], + ['no-a', 'enter', 'Name', 'b'], + ['no-a', 'leave', 'Name', 'b'], + ['no-a', 'enter', 'SelectionSet', null], + ['no-a', 'enter', 'Field', null], + ['no-a', 'enter', 'Name', 'y'], + ['no-a', 'leave', 'Name', 'y'], + ['no-a', 'leave', 'Field', null], + ['no-a', 'leave', 'SelectionSet', null], + ['no-a', 'leave', 'Field', null], + ['no-a', 'leave', 'SelectionSet', null], + ['no-b', 'leave', 'SelectionSet', null], + ['no-a', 'leave', 'OperationDefinition', null], + ['no-b', 'leave', 'OperationDefinition', null], + ['no-a', 'leave', 'Document', null], + ['no-b', 'leave', 'Document', null], ], $visited ); @@ -1004,19 +1004,19 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null], - ['enter', 'OperationDefinition', null], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'b'], - ['leave', 'Name', 'b'], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'x'], + ['enter', 'Document', null], + ['enter', 'OperationDefinition', null], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'b'], + ['leave', 'Name', 'b'], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'x'], ], $visited ); @@ -1063,26 +1063,26 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['break-a', 'enter', 'Document', null], - ['break-b', 'enter', 'Document', null], - ['break-a', 'enter', 'OperationDefinition', null], - ['break-b', 'enter', 'OperationDefinition', null], - ['break-a', 'enter', 'SelectionSet', null], - ['break-b', 'enter', 'SelectionSet', null], - ['break-a', 'enter', 'Field', null], - ['break-b', 'enter', 'Field', null], - ['break-a', 'enter', 'Name', 'a'], - ['break-b', 'enter', 'Name', 'a'], - ['break-b', 'leave', 'Name', 'a'], - ['break-b', 'enter', 'SelectionSet', null], - ['break-b', 'enter', 'Field', null], - ['break-b', 'enter', 'Name', 'y'], - ['break-b', 'leave', 'Name', 'y'], - ['break-b', 'leave', 'Field', null], - ['break-b', 'leave', 'SelectionSet', null], - ['break-b', 'leave', 'Field', null], - ['break-b', 'enter', 'Field', null], - ['break-b', 'enter', 'Name', 'b'], + ['break-a', 'enter', 'Document', null], + ['break-b', 'enter', 'Document', null], + ['break-a', 'enter', 'OperationDefinition', null], + ['break-b', 'enter', 'OperationDefinition', null], + ['break-a', 'enter', 'SelectionSet', null], + ['break-b', 'enter', 'SelectionSet', null], + ['break-a', 'enter', 'Field', null], + ['break-b', 'enter', 'Field', null], + ['break-a', 'enter', 'Name', 'a'], + ['break-b', 'enter', 'Name', 'a'], + ['break-b', 'leave', 'Name', 'a'], + ['break-b', 'enter', 'SelectionSet', null], + ['break-b', 'enter', 'Field', null], + ['break-b', 'enter', 'Name', 'y'], + ['break-b', 'leave', 'Name', 'y'], + ['break-b', 'leave', 'Field', null], + ['break-b', 'leave', 'SelectionSet', null], + ['break-b', 'leave', 'Field', null], + ['break-b', 'enter', 'Field', null], + ['break-b', 'enter', 'Name', 'b'], ], $visited ); @@ -1114,20 +1114,20 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null], - ['enter', 'OperationDefinition', null], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'b'], - ['leave', 'Name', 'b'], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'x'], - ['leave', 'Name', 'x'], + ['enter', 'Document', null], + ['enter', 'OperationDefinition', null], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'b'], + ['leave', 'Name', 'b'], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'x'], + ['leave', 'Name', 'x'], ], $visited ); @@ -1172,42 +1172,42 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['break-a', 'enter', 'Document', null], - ['break-b', 'enter', 'Document', null], - ['break-a', 'enter', 'OperationDefinition', null], - ['break-b', 'enter', 'OperationDefinition', null], - ['break-a', 'enter', 'SelectionSet', null], - ['break-b', 'enter', 'SelectionSet', null], - ['break-a', 'enter', 'Field', null], - ['break-b', 'enter', 'Field', null], - ['break-a', 'enter', 'Name', 'a'], - ['break-b', 'enter', 'Name', 'a'], - ['break-a', 'leave', 'Name', 'a'], - ['break-b', 'leave', 'Name', 'a'], - ['break-a', 'enter', 'SelectionSet', null], - ['break-b', 'enter', 'SelectionSet', null], - ['break-a', 'enter', 'Field', null], - ['break-b', 'enter', 'Field', null], - ['break-a', 'enter', 'Name', 'y'], - ['break-b', 'enter', 'Name', 'y'], - ['break-a', 'leave', 'Name', 'y'], - ['break-b', 'leave', 'Name', 'y'], - ['break-a', 'leave', 'Field', null], - ['break-b', 'leave', 'Field', null], - ['break-a', 'leave', 'SelectionSet', null], - ['break-b', 'leave', 'SelectionSet', null], - ['break-a', 'leave', 'Field', null], - ['break-b', 'leave', 'Field', null], - ['break-b', 'enter', 'Field', null], - ['break-b', 'enter', 'Name', 'b'], - ['break-b', 'leave', 'Name', 'b'], - ['break-b', 'enter', 'SelectionSet', null], - ['break-b', 'enter', 'Field', null], - ['break-b', 'enter', 'Name', 'x'], - ['break-b', 'leave', 'Name', 'x'], - ['break-b', 'leave', 'Field', null], - ['break-b', 'leave', 'SelectionSet', null], - ['break-b', 'leave', 'Field', null], + ['break-a', 'enter', 'Document', null], + ['break-b', 'enter', 'Document', null], + ['break-a', 'enter', 'OperationDefinition', null], + ['break-b', 'enter', 'OperationDefinition', null], + ['break-a', 'enter', 'SelectionSet', null], + ['break-b', 'enter', 'SelectionSet', null], + ['break-a', 'enter', 'Field', null], + ['break-b', 'enter', 'Field', null], + ['break-a', 'enter', 'Name', 'a'], + ['break-b', 'enter', 'Name', 'a'], + ['break-a', 'leave', 'Name', 'a'], + ['break-b', 'leave', 'Name', 'a'], + ['break-a', 'enter', 'SelectionSet', null], + ['break-b', 'enter', 'SelectionSet', null], + ['break-a', 'enter', 'Field', null], + ['break-b', 'enter', 'Field', null], + ['break-a', 'enter', 'Name', 'y'], + ['break-b', 'enter', 'Name', 'y'], + ['break-a', 'leave', 'Name', 'y'], + ['break-b', 'leave', 'Name', 'y'], + ['break-a', 'leave', 'Field', null], + ['break-b', 'leave', 'Field', null], + ['break-a', 'leave', 'SelectionSet', null], + ['break-b', 'leave', 'SelectionSet', null], + ['break-a', 'leave', 'Field', null], + ['break-b', 'leave', 'Field', null], + ['break-b', 'enter', 'Field', null], + ['break-b', 'enter', 'Name', 'b'], + ['break-b', 'leave', 'Name', 'b'], + ['break-b', 'enter', 'SelectionSet', null], + ['break-b', 'enter', 'Field', null], + ['break-b', 'enter', 'Name', 'x'], + ['break-b', 'leave', 'Name', 'x'], + ['break-b', 'leave', 'Field', null], + ['break-b', 'leave', 'SelectionSet', null], + ['break-b', 'leave', 'Field', null], ], $visited ); @@ -1254,30 +1254,30 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null], - ['enter', 'OperationDefinition', null], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'c'], - ['leave', 'Name', 'c'], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'c'], - ['leave', 'Name', 'c'], - ['leave', 'Field', null], - ['leave', 'SelectionSet', null], - ['leave', 'Field', null], - ['leave', 'SelectionSet', null], - ['leave', 'OperationDefinition', null], - ['leave', 'Document', null], + ['enter', 'Document', null], + ['enter', 'OperationDefinition', null], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'c'], + ['leave', 'Name', 'c'], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'c'], + ['leave', 'Name', 'c'], + ['leave', 'Field', null], + ['leave', 'SelectionSet', null], + ['leave', 'Field', null], + ['leave', 'SelectionSet', null], + ['leave', 'OperationDefinition', null], + ['leave', 'Document', null], ], $visited ); @@ -1324,36 +1324,36 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null], - ['enter', 'OperationDefinition', null], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'b'], - ['leave', 'Name', 'b'], - ['enter', 'Field', null], - ['enter', 'Name', 'c'], - ['leave', 'Name', 'c'], - ['enter', 'SelectionSet', null], - ['enter', 'Field', null], - ['enter', 'Name', 'a'], - ['leave', 'Name', 'a'], - ['leave', 'Field', null], - ['enter', 'Field', null], - ['enter', 'Name', 'b'], - ['leave', 'Name', 'b'], - ['enter', 'Field', null], - ['enter', 'Name', 'c'], - ['leave', 'Name', 'c'], - ['leave', 'Field', null], - ['leave', 'SelectionSet', null], - ['leave', 'Field', null], - ['leave', 'SelectionSet', null], - ['leave', 'OperationDefinition', null], - ['leave', 'Document', null], + ['enter', 'Document', null], + ['enter', 'OperationDefinition', null], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'b'], + ['leave', 'Name', 'b'], + ['enter', 'Field', null], + ['enter', 'Name', 'c'], + ['leave', 'Name', 'c'], + ['enter', 'SelectionSet', null], + ['enter', 'Field', null], + ['enter', 'Name', 'a'], + ['leave', 'Name', 'a'], + ['leave', 'Field', null], + ['enter', 'Field', null], + ['enter', 'Name', 'b'], + ['leave', 'Name', 'b'], + ['enter', 'Field', null], + ['enter', 'Name', 'c'], + ['leave', 'Name', 'c'], + ['leave', 'Field', null], + ['leave', 'SelectionSet', null], + ['leave', 'Field', null], + ['leave', 'SelectionSet', null], + ['leave', 'OperationDefinition', null], + ['leave', 'Document', null], ], $visited ); @@ -1408,46 +1408,46 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null, null, null, null], - ['enter', 'OperationDefinition', null, null, 'QueryRoot', null], - ['enter', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], - ['enter', 'Field', null, 'QueryRoot', 'Human', null], - ['enter', 'Name', 'human', 'QueryRoot', 'Human', null], - ['leave', 'Name', 'human', 'QueryRoot', 'Human', null], - ['enter', 'Argument', null, 'QueryRoot', 'Human', 'ID'], - ['enter', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], - ['leave', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], - ['enter', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], - ['leave', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], - ['leave', 'Argument', null, 'QueryRoot', 'Human', 'ID'], - ['enter', 'SelectionSet', null, 'Human', 'Human', null], - ['enter', 'Field', null, 'Human', 'String', null], - ['enter', 'Name', 'name', 'Human', 'String', null], - ['leave', 'Name', 'name', 'Human', 'String', null], - ['leave', 'Field', null, 'Human', 'String', null], - ['enter', 'Field', null, 'Human', '[Pet]', null], - ['enter', 'Name', 'pets', 'Human', '[Pet]', null], - ['leave', 'Name', 'pets', 'Human', '[Pet]', null], - ['enter', 'SelectionSet', null, 'Pet', '[Pet]', null], - ['enter', 'InlineFragment', null, 'Pet', 'Pet', null], - ['enter', 'SelectionSet', null, 'Pet', 'Pet', null], - ['enter', 'Field', null, 'Pet', 'String', null], - ['enter', 'Name', 'name', 'Pet', 'String', null], - ['leave', 'Name', 'name', 'Pet', 'String', null], - ['leave', 'Field', null, 'Pet', 'String', null], - ['leave', 'SelectionSet', null, 'Pet', 'Pet', null], - ['leave', 'InlineFragment', null, 'Pet', 'Pet', null], - ['leave', 'SelectionSet', null, 'Pet', '[Pet]', null], - ['leave', 'Field', null, 'Human', '[Pet]', null], - ['enter', 'Field', null, 'Human', null, null], - ['enter', 'Name', 'unknown', 'Human', null, null], - ['leave', 'Name', 'unknown', 'Human', null, null], - ['leave', 'Field', null, 'Human', null, null], - ['leave', 'SelectionSet', null, 'Human', 'Human', null], - ['leave', 'Field', null, 'QueryRoot', 'Human', null], - ['leave', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], - ['leave', 'OperationDefinition', null, null, 'QueryRoot', null], - ['leave', 'Document', null, null, null, null], + ['enter', 'Document', null, null, null, null], + ['enter', 'OperationDefinition', null, null, 'QueryRoot', null], + ['enter', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], + ['enter', 'Field', null, 'QueryRoot', 'Human', null], + ['enter', 'Name', 'human', 'QueryRoot', 'Human', null], + ['leave', 'Name', 'human', 'QueryRoot', 'Human', null], + ['enter', 'Argument', null, 'QueryRoot', 'Human', 'ID'], + ['enter', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], + ['leave', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], + ['enter', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], + ['leave', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], + ['leave', 'Argument', null, 'QueryRoot', 'Human', 'ID'], + ['enter', 'SelectionSet', null, 'Human', 'Human', null], + ['enter', 'Field', null, 'Human', 'String', null], + ['enter', 'Name', 'name', 'Human', 'String', null], + ['leave', 'Name', 'name', 'Human', 'String', null], + ['leave', 'Field', null, 'Human', 'String', null], + ['enter', 'Field', null, 'Human', '[Pet]', null], + ['enter', 'Name', 'pets', 'Human', '[Pet]', null], + ['leave', 'Name', 'pets', 'Human', '[Pet]', null], + ['enter', 'SelectionSet', null, 'Pet', '[Pet]', null], + ['enter', 'InlineFragment', null, 'Pet', 'Pet', null], + ['enter', 'SelectionSet', null, 'Pet', 'Pet', null], + ['enter', 'Field', null, 'Pet', 'String', null], + ['enter', 'Name', 'name', 'Pet', 'String', null], + ['leave', 'Name', 'name', 'Pet', 'String', null], + ['leave', 'Field', null, 'Pet', 'String', null], + ['leave', 'SelectionSet', null, 'Pet', 'Pet', null], + ['leave', 'InlineFragment', null, 'Pet', 'Pet', null], + ['leave', 'SelectionSet', null, 'Pet', '[Pet]', null], + ['leave', 'Field', null, 'Human', '[Pet]', null], + ['enter', 'Field', null, 'Human', null, null], + ['enter', 'Name', 'unknown', 'Human', null, null], + ['leave', 'Name', 'unknown', 'Human', null, null], + ['leave', 'Field', null, 'Human', null, null], + ['leave', 'SelectionSet', null, 'Human', 'Human', null], + ['leave', 'Field', null, 'QueryRoot', 'Human', null], + ['leave', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], + ['leave', 'OperationDefinition', null, null, 'QueryRoot', null], + ['leave', 'Document', null, null, null, null], ], $visited ); @@ -1534,48 +1534,48 @@ class VisitorTest extends ValidatorTestCase self::assertEquals( [ - ['enter', 'Document', null, null, null, null], - ['enter', 'OperationDefinition', null, null, 'QueryRoot', null], - ['enter', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], - ['enter', 'Field', null, 'QueryRoot', 'Human', null], - ['enter', 'Name', 'human', 'QueryRoot', 'Human', null], - ['leave', 'Name', 'human', 'QueryRoot', 'Human', null], - ['enter', 'Argument', null, 'QueryRoot', 'Human', 'ID'], - ['enter', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], - ['leave', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], - ['enter', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], - ['leave', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], - ['leave', 'Argument', null, 'QueryRoot', 'Human', 'ID'], - ['enter', 'SelectionSet', null, 'Human', 'Human', null], - ['enter', 'Field', null, 'Human', 'String', null], - ['enter', 'Name', 'name', 'Human', 'String', null], - ['leave', 'Name', 'name', 'Human', 'String', null], - ['leave', 'Field', null, 'Human', 'String', null], - ['enter', 'Field', null, 'Human', '[Pet]', null], - ['enter', 'Name', 'pets', 'Human', '[Pet]', null], - ['leave', 'Name', 'pets', 'Human', '[Pet]', null], - ['enter', 'SelectionSet', null, 'Pet', '[Pet]', null], - ['enter', 'Field', null, 'Pet', 'String!', null], - ['enter', 'Name', '__typename', 'Pet', 'String!', null], - ['leave', 'Name', '__typename', 'Pet', 'String!', null], - ['leave', 'Field', null, 'Pet', 'String!', null], - ['leave', 'SelectionSet', null, 'Pet', '[Pet]', null], - ['leave', 'Field', null, 'Human', '[Pet]', null], - ['leave', 'SelectionSet', null, 'Human', 'Human', null], - ['leave', 'Field', null, 'QueryRoot', 'Human', null], - ['enter', 'Field', null, 'QueryRoot', 'Alien', null], - ['enter', 'Name', 'alien', 'QueryRoot', 'Alien', null], - ['leave', 'Name', 'alien', 'QueryRoot', 'Alien', null], - ['enter', 'SelectionSet', null, 'Alien', 'Alien', null], - ['enter', 'Field', null, 'Alien', 'String!', null], - ['enter', 'Name', '__typename', 'Alien', 'String!', null], - ['leave', 'Name', '__typename', 'Alien', 'String!', null], - ['leave', 'Field', null, 'Alien', 'String!', null], - ['leave', 'SelectionSet', null, 'Alien', 'Alien', null], - ['leave', 'Field', null, 'QueryRoot', 'Alien', null], - ['leave', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], - ['leave', 'OperationDefinition', null, null, 'QueryRoot', null], - ['leave', 'Document', null, null, null, null], + ['enter', 'Document', null, null, null, null], + ['enter', 'OperationDefinition', null, null, 'QueryRoot', null], + ['enter', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], + ['enter', 'Field', null, 'QueryRoot', 'Human', null], + ['enter', 'Name', 'human', 'QueryRoot', 'Human', null], + ['leave', 'Name', 'human', 'QueryRoot', 'Human', null], + ['enter', 'Argument', null, 'QueryRoot', 'Human', 'ID'], + ['enter', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], + ['leave', 'Name', 'id', 'QueryRoot', 'Human', 'ID'], + ['enter', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], + ['leave', 'IntValue', null, 'QueryRoot', 'Human', 'ID'], + ['leave', 'Argument', null, 'QueryRoot', 'Human', 'ID'], + ['enter', 'SelectionSet', null, 'Human', 'Human', null], + ['enter', 'Field', null, 'Human', 'String', null], + ['enter', 'Name', 'name', 'Human', 'String', null], + ['leave', 'Name', 'name', 'Human', 'String', null], + ['leave', 'Field', null, 'Human', 'String', null], + ['enter', 'Field', null, 'Human', '[Pet]', null], + ['enter', 'Name', 'pets', 'Human', '[Pet]', null], + ['leave', 'Name', 'pets', 'Human', '[Pet]', null], + ['enter', 'SelectionSet', null, 'Pet', '[Pet]', null], + ['enter', 'Field', null, 'Pet', 'String!', null], + ['enter', 'Name', '__typename', 'Pet', 'String!', null], + ['leave', 'Name', '__typename', 'Pet', 'String!', null], + ['leave', 'Field', null, 'Pet', 'String!', null], + ['leave', 'SelectionSet', null, 'Pet', '[Pet]', null], + ['leave', 'Field', null, 'Human', '[Pet]', null], + ['leave', 'SelectionSet', null, 'Human', 'Human', null], + ['leave', 'Field', null, 'QueryRoot', 'Human', null], + ['enter', 'Field', null, 'QueryRoot', 'Alien', null], + ['enter', 'Name', 'alien', 'QueryRoot', 'Alien', null], + ['leave', 'Name', 'alien', 'QueryRoot', 'Alien', null], + ['enter', 'SelectionSet', null, 'Alien', 'Alien', null], + ['enter', 'Field', null, 'Alien', 'String!', null], + ['enter', 'Name', '__typename', 'Alien', 'String!', null], + ['leave', 'Name', '__typename', 'Alien', 'String!', null], + ['leave', 'Field', null, 'Alien', 'String!', null], + ['leave', 'SelectionSet', null, 'Alien', 'Alien', null], + ['leave', 'Field', null, 'QueryRoot', 'Alien', null], + ['leave', 'SelectionSet', null, 'QueryRoot', 'QueryRoot', null], + ['leave', 'OperationDefinition', null, null, 'QueryRoot', null], + ['leave', 'Document', null, null, null, null], ], $visited ); diff --git a/tests/Server/QueryExecutionTest.php b/tests/Server/QueryExecutionTest.php index a963a27..fffa9b8 100644 --- a/tests/Server/QueryExecutionTest.php +++ b/tests/Server/QueryExecutionTest.php @@ -17,6 +17,7 @@ use GraphQL\Server\ServerConfig; use GraphQL\Validator\DocumentValidator; use GraphQL\Validator\Rules\CustomValidationRule; use GraphQL\Validator\ValidationContext; +use stdClass; use function count; use function sprintf; @@ -119,7 +120,7 @@ class QueryExecutionTest extends ServerTestCase public function testPassesRootValueAndContext() : void { $rootValue = 'myRootValue'; - $context = new \stdClass(); + $context = new stdClass(); $this->config ->setContext($context) @@ -170,7 +171,7 @@ class QueryExecutionTest extends ServerTestCase $called = false; $rules = [ - new CustomValidationRule('SomeRule', function () use (&$called) { + new CustomValidationRule('SomeRule', static function () use (&$called) { $called = true; return []; @@ -190,7 +191,7 @@ class QueryExecutionTest extends ServerTestCase $called = false; $params = $doc = $operationType = null; - $this->config->setValidationRules(function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { + $this->config->setValidationRules(static function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { $called = true; $params = $p; $doc = $d; @@ -214,7 +215,7 @@ class QueryExecutionTest extends ServerTestCase $called1 = false; $called2 = false; - $this->config->setValidationRules(function (OperationParams $params) use ($q1, &$called1, &$called2) { + $this->config->setValidationRules(static function (OperationParams $params) use ($q1, &$called1, &$called2) { if ($params->query === $q1) { $called1 = true; @@ -224,7 +225,7 @@ class QueryExecutionTest extends ServerTestCase $called2 = true; return [ - new CustomValidationRule('MyRule', function (ValidationContext $context) { + new CustomValidationRule('MyRule', static function (ValidationContext $context) { $context->reportError(new Error('This is the error we are looking for!')); }), ]; @@ -353,7 +354,7 @@ class QueryExecutionTest extends ServerTestCase public function testAllowsPersistentQueries() : void { $called = false; - $this->config->setPersistentQueryLoader(function ($queryId, OperationParams $params) use (&$called) { + $this->config->setPersistentQueryLoader(static function ($queryId, OperationParams $params) use (&$called) { $called = true; self::assertEquals('some-id', $queryId); @@ -370,7 +371,7 @@ class QueryExecutionTest extends ServerTestCase // Make sure it allows returning document node: $called = false; - $this->config->setPersistentQueryLoader(function ($queryId, OperationParams $params) use (&$called) { + $this->config->setPersistentQueryLoader(static function ($queryId, OperationParams $params) use (&$called) { $called = true; self::assertEquals('some-id', $queryId); @@ -388,7 +389,7 @@ class QueryExecutionTest extends ServerTestCase 'Persistent query loader must return query string or instance of GraphQL\Language\AST\DocumentNode ' . 'but got: {"err":"err"}' ); - $this->config->setPersistentQueryLoader(function () { + $this->config->setPersistentQueryLoader(static function () { return ['err' => 'err']; }); $this->executePersistedQuery('some-id'); @@ -396,7 +397,7 @@ class QueryExecutionTest extends ServerTestCase public function testPersistedQueriesAreStillValidatedByDefault() : void { - $this->config->setPersistentQueryLoader(function () { + $this->config->setPersistentQueryLoader(static function () { return '{invalid}'; }); $result = $this->executePersistedQuery('some-id'); @@ -415,14 +416,14 @@ class QueryExecutionTest extends ServerTestCase public function testAllowSkippingValidationForPersistedQueries() : void { $this->config - ->setPersistentQueryLoader(function ($queryId) { + ->setPersistentQueryLoader(static function ($queryId) { if ($queryId === 'some-id') { return '{invalid}'; } return '{invalid2}'; }) - ->setValidationRules(function (OperationParams $params) { + ->setValidationRules(static function (OperationParams $params) { if ($params->queryId === 'some-id') { return []; } @@ -453,8 +454,8 @@ class QueryExecutionTest extends ServerTestCase { $this->expectException(InvariantViolation::class); $this->expectExceptionMessage('Expecting validation rules to be array or callable returning array, but got: instance of stdClass'); - $this->config->setValidationRules(function (OperationParams $params) { - return new \stdClass(); + $this->config->setValidationRules(static function (OperationParams $params) { + return new stdClass(); }); $this->executeQuery('{f1}'); } @@ -519,10 +520,10 @@ class QueryExecutionTest extends ServerTestCase ->setQueryBatching(true) ->setRootValue('1') ->setContext([ - 'buffer' => function ($num) use (&$calls) { + 'buffer' => static function ($num) use (&$calls) { $calls[] = sprintf('buffer: %d', $num); }, - 'load' => function ($num) use (&$calls) { + 'load' => static function ($num) use (&$calls) { $calls[] = sprintf('load: %d', $num); return sprintf('loaded: %d', $num); @@ -584,7 +585,7 @@ class QueryExecutionTest extends ServerTestCase $called = false; $params = $doc = $operationType = null; - $this->config->setContext(function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { + $this->config->setContext(static function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { $called = true; $params = $p; $doc = $d; @@ -604,7 +605,7 @@ class QueryExecutionTest extends ServerTestCase $called = false; $params = $doc = $operationType = null; - $this->config->setRootValue(function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { + $this->config->setRootValue(static function ($p, $d, $o) use (&$called, &$params, &$doc, &$operationType) { $called = true; $params = $p; $doc = $d; @@ -623,7 +624,7 @@ class QueryExecutionTest extends ServerTestCase { $called = false; $error = null; - $this->config->setErrorFormatter(function ($e) use (&$called, &$error) { + $this->config->setErrorFormatter(static function ($e) use (&$called, &$error) { $called = true; $error = $e; @@ -660,7 +661,7 @@ class QueryExecutionTest extends ServerTestCase $called = false; $errors = null; $formatter = null; - $this->config->setErrorsHandler(function ($e, $f) use (&$called, &$errors, &$formatter) { + $this->config->setErrorsHandler(static function ($e, $f) use (&$called, &$errors, &$formatter) { $called = true; $errors = $e; $formatter = $f; diff --git a/tests/Server/RequestParsingTest.php b/tests/Server/RequestParsingTest.php index e803910..d09e6c4 100644 --- a/tests/Server/RequestParsingTest.php +++ b/tests/Server/RequestParsingTest.php @@ -43,7 +43,7 @@ class RequestParsingTest extends TestCase $helper = new Helper(); - return $helper->parseHttpRequest(function () use ($content) { + return $helper->parseHttpRequest(static function () use ($content) { return $content; }); } @@ -125,6 +125,7 @@ class RequestParsingTest extends TestCase /** * @param mixed[] $postValue + * * @return OperationParams|OperationParams[] */ private function parseRawFormUrlencodedRequest($postValue) @@ -135,13 +136,14 @@ class RequestParsingTest extends TestCase $helper = new Helper(); - return $helper->parseHttpRequest(function () { + return $helper->parseHttpRequest(static function () { throw new InvariantViolation("Shouldn't read from php://input for urlencoded request"); }); } /** * @param mixed[] $postValue + * * @return OperationParams[]|OperationParams */ private function parsePsrFormUrlEncodedRequest($postValue) @@ -180,6 +182,7 @@ class RequestParsingTest extends TestCase /** * @param mixed[] $getValue + * * @return OperationParams */ private function parseRawGetRequest($getValue) @@ -189,13 +192,14 @@ class RequestParsingTest extends TestCase $helper = new Helper(); - return $helper->parseHttpRequest(function () { + return $helper->parseHttpRequest(static function () { throw new InvariantViolation("Shouldn't read from php://input for urlencoded request"); }); } /** * @param mixed[] $getValue + * * @return OperationParams[]|OperationParams */ private function parsePsrGetRequest($getValue) @@ -233,6 +237,7 @@ class RequestParsingTest extends TestCase /** * @param mixed[] $postValue + * * @return OperationParams|OperationParams[] */ private function parseRawMultipartFormDataRequest($postValue) @@ -243,13 +248,14 @@ class RequestParsingTest extends TestCase $helper = new Helper(); - return $helper->parseHttpRequest(function () { + return $helper->parseHttpRequest(static function () { throw new InvariantViolation("Shouldn't read from php://input for multipart/form-data request"); }); } /** * @param mixed[] $postValue + * * @return OperationParams|OperationParams[] */ private function parsePsrMultipartFormDataRequest($postValue) diff --git a/tests/Server/ServerConfigTest.php b/tests/Server/ServerConfigTest.php index d27fc59..a596ab3 100644 --- a/tests/Server/ServerConfigTest.php +++ b/tests/Server/ServerConfigTest.php @@ -11,6 +11,7 @@ use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; use PHPUnit\Framework\TestCase; +use stdClass; class ServerConfigTest extends TestCase { @@ -51,7 +52,7 @@ class ServerConfigTest extends TestCase $config->setContext($context); self::assertSame($context, $config->getContext()); - $context2 = new \stdClass(); + $context2 = new stdClass(); $config->setContext($context2); self::assertSame($context2, $config->getContext()); } @@ -64,7 +65,7 @@ class ServerConfigTest extends TestCase $config->setRootValue($rootValue); self::assertSame($rootValue, $config->getRootValue()); - $context2 = new \stdClass(); + $context2 = new stdClass(); $config->setRootValue($context2); self::assertSame($context2, $config->getRootValue()); } @@ -73,7 +74,7 @@ class ServerConfigTest extends TestCase { $config = ServerConfig::create(); - $formatter = function () { + $formatter = static function () { }; $config->setErrorFormatter($formatter); self::assertSame($formatter, $config->getErrorFormatter()); @@ -87,7 +88,7 @@ class ServerConfigTest extends TestCase { $config = ServerConfig::create(); - $handler = function () { + $handler = static function () { }; $config->setErrorsHandler($handler); self::assertSame($handler, $config->getErrorsHandler()); @@ -118,14 +119,14 @@ class ServerConfigTest extends TestCase $config->setValidationRules($rules); self::assertSame($rules, $config->getValidationRules()); - $rules = [function () { + $rules = [static function () { }, ]; $config->setValidationRules($rules); self::assertSame($rules, $config->getValidationRules()); - $rules = function () { - return [function () { + $rules = static function () { + return [static function () { }, ]; }; @@ -137,7 +138,7 @@ class ServerConfigTest extends TestCase { $config = ServerConfig::create(); - $resolver = function () { + $resolver = static function () { }; $config->setFieldResolver($resolver); self::assertSame($resolver, $config->getFieldResolver()); @@ -151,7 +152,7 @@ class ServerConfigTest extends TestCase { $config = ServerConfig::create(); - $loader = function () { + $loader = static function () { }; $config->setPersistentQueryLoader($loader); self::assertSame($loader, $config->getPersistentQueryLoader()); @@ -178,17 +179,17 @@ class ServerConfigTest extends TestCase 'schema' => new Schema([ 'query' => new ObjectType(['name' => 't', 'fields' => ['a' => Type::string()]]), ]), - 'context' => new \stdClass(), - 'rootValue' => new \stdClass(), - 'errorFormatter' => function () { + 'context' => new stdClass(), + 'rootValue' => new stdClass(), + 'errorFormatter' => static function () { }, 'promiseAdapter' => new SyncPromiseAdapter(), - 'validationRules' => [function () { + 'validationRules' => [static function () { }, ], - 'fieldResolver' => function () { + 'fieldResolver' => static function () { }, - 'persistentQueryLoader' => function () { + 'persistentQueryLoader' => static function () { }, 'debug' => true, 'queryBatching' => true, @@ -220,7 +221,7 @@ class ServerConfigTest extends TestCase public function testInvalidValidationRules() : void { - $rules = new \stdClass(); + $rules = new stdClass(); $config = ServerConfig::create(); $this->expectException(InvariantViolation::class); diff --git a/tests/Server/ServerTestCase.php b/tests/Server/ServerTestCase.php index 4ad9698..072acba 100644 --- a/tests/Server/ServerTestCase.php +++ b/tests/Server/ServerTestCase.php @@ -19,19 +19,19 @@ abstract class ServerTestCase extends TestCase { protected function buildSchema() { - $schema = new Schema([ + return new Schema([ 'query' => new ObjectType([ 'name' => 'Query', 'fields' => [ 'f1' => [ 'type' => Type::string(), - 'resolve' => function ($root, $args, $context, $info) { + 'resolve' => static function ($root, $args, $context, $info) { return $info->fieldName; }, ], 'fieldWithPhpError' => [ 'type' => Type::string(), - 'resolve' => function ($root, $args, $context, $info) { + 'resolve' => static function ($root, $args, $context, $info) { trigger_error('deprecated', E_USER_DEPRECATED); trigger_error('notice', E_USER_NOTICE); trigger_error('warning', E_USER_WARNING); @@ -43,19 +43,19 @@ abstract class ServerTestCase extends TestCase ], 'fieldWithSafeException' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { throw new UserError('This is the exception we want'); }, ], 'fieldWithUnsafeException' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { throw new Unsafe('This exception should not be shown to the user'); }, ], 'testContextAndRootValue' => [ 'type' => Type::string(), - 'resolve' => function ($root, $args, $context, $info) { + 'resolve' => static function ($root, $args, $context, $info) { $context->testedRootValue = $root; return $info->fieldName; @@ -68,7 +68,7 @@ abstract class ServerTestCase extends TestCase 'type' => Type::nonNull(Type::string()), ], ], - 'resolve' => function ($root, $args) { + 'resolve' => static function ($root, $args) { return $args['arg']; }, ], @@ -79,10 +79,10 @@ abstract class ServerTestCase extends TestCase 'type' => Type::nonNull(Type::int()), ], ], - 'resolve' => function ($root, $args, $context) { + 'resolve' => static function ($root, $args, $context) { $context['buffer']($args['num']); - return new Deferred(function () use ($args, $context) { + return new Deferred(static function () use ($args, $context) { return $context['load']($args['num']); }); }, @@ -103,7 +103,5 @@ abstract class ServerTestCase extends TestCase ], ]), ]); - - return $schema; } } diff --git a/tests/Server/StandardServerTest.php b/tests/Server/StandardServerTest.php index a1b596c..a672141 100644 --- a/tests/Server/StandardServerTest.php +++ b/tests/Server/StandardServerTest.php @@ -45,7 +45,7 @@ class StandardServerTest extends ServerTestCase $helper = new Helper(); - return $helper->parseHttpRequest(function () use ($content) { + return $helper->parseHttpRequest(static function () use ($content) { return $content; }); } diff --git a/tests/Server/Unsafe.php b/tests/Server/Unsafe.php index 2eb3742..a14a80d 100644 --- a/tests/Server/Unsafe.php +++ b/tests/Server/Unsafe.php @@ -4,15 +4,17 @@ declare(strict_types=1); namespace GraphQL\Tests\Server; +use Exception; use GraphQL\Error\ClientAware; -class Unsafe extends \Exception implements ClientAware +class Unsafe extends Exception implements ClientAware { /** * Returns true when exception message is safe to be displayed to a client. * - * @api * @return bool + * + * @api */ public function isClientSafe() { @@ -24,8 +26,9 @@ class Unsafe extends \Exception implements ClientAware * * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. * - * @api * @return string + * + * @api */ public function getCategory() { diff --git a/tests/StarWarsData.php b/tests/StarWarsData.php index 9034d99..6e422fa 100644 --- a/tests/StarWarsData.php +++ b/tests/StarWarsData.php @@ -129,11 +129,12 @@ class StarWarsData */ public static function getFriends($character) { - return array_map([__CLASS__, 'getCharacter'], $character['friends']); + return array_map([self::class, 'getCharacter'], $character['friends']); } /** * @param int $episode + * * @return mixed[] */ public static function getHero($episode) @@ -149,6 +150,7 @@ class StarWarsData /** * @param string $id + * * @return mixed|null */ public static function getHuman($id) @@ -160,6 +162,7 @@ class StarWarsData /** * @param string $id + * * @return mixed|null */ public static function getDroid($id) diff --git a/tests/StarWarsSchema.php b/tests/StarWarsSchema.php index f5dbfe1..cded7da 100644 --- a/tests/StarWarsSchema.php +++ b/tests/StarWarsSchema.php @@ -15,6 +15,7 @@ namespace GraphQL\Tests; * Wars trilogy. */ +use Exception; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\NonNull; @@ -108,7 +109,7 @@ class StarWarsSchema $characterInterface = new InterfaceType([ 'name' => 'Character', 'description' => 'A character in the Star Wars Trilogy', - 'fields' => function () use (&$characterInterface, $episodeEnum) { + 'fields' => static function () use (&$characterInterface, $episodeEnum) { return [ 'id' => [ 'type' => Type::nonNull(Type::string()), @@ -132,7 +133,7 @@ class StarWarsSchema ], ]; }, - 'resolveType' => function ($obj) use (&$humanType, &$droidType) { + 'resolveType' => static function ($obj) use (&$humanType, &$droidType) { return StarWarsData::getHuman($obj['id']) ? $humanType : $droidType; }, ]); @@ -164,18 +165,16 @@ class StarWarsSchema 'friends' => [ 'type' => Type::listOf($characterInterface), 'description' => 'The friends of the human, or an empty list if they have none.', - 'resolve' => function ($human, $args, $context, ResolveInfo $info) { + 'resolve' => static function ($human, $args, $context, ResolveInfo $info) { $fieldSelection = $info->getFieldSelection(); $fieldSelection['id'] = true; - $friends = array_map( - function ($friend) use ($fieldSelection) { + return array_map( + static function ($friend) use ($fieldSelection) { return array_intersect_key($friend, $fieldSelection); }, StarWarsData::getFriends($human) ); - - return $friends; }, ], 'appearsIn' => [ @@ -189,9 +188,9 @@ class StarWarsSchema 'secretBackstory' => [ 'type' => Type::string(), 'description' => 'Where are they from and how they came to be who they are.', - 'resolve' => function () { + 'resolve' => static function () { // This is to demonstrate error reporting - throw new \Exception('secretBackstory is secret.'); + throw new Exception('secretBackstory is secret.'); }, ], ], @@ -226,7 +225,7 @@ class StarWarsSchema 'friends' => [ 'type' => Type::listOf($characterInterface), 'description' => 'The friends of the droid, or an empty list if they have none.', - 'resolve' => function ($droid) { + 'resolve' => static function ($droid) { return StarWarsData::getFriends($droid); }, ], @@ -237,9 +236,9 @@ class StarWarsSchema 'secretBackstory' => [ 'type' => Type::string(), 'description' => 'Construction date and the name of the designer.', - 'resolve' => function () { + 'resolve' => static function () { // This is to demonstrate error reporting - throw new \Exception('secretBackstory is secret.'); + throw new Exception('secretBackstory is secret.'); }, ], 'primaryFunction' => [ @@ -262,7 +261,6 @@ class StarWarsSchema * human(id: String!): Human * droid(id: String!): Droid * } - * */ $queryType = new ObjectType([ 'name' => 'Query', @@ -275,7 +273,7 @@ class StarWarsSchema 'type' => $episodeEnum, ], ], - 'resolve' => function ($root, $args) { + 'resolve' => static function ($root, $args) { return StarWarsData::getHero($args['episode'] ?? null); }, ], @@ -288,7 +286,7 @@ class StarWarsSchema 'type' => Type::nonNull(Type::string()), ], ], - 'resolve' => function ($root, $args) { + 'resolve' => static function ($root, $args) { $humans = StarWarsData::humans(); return $humans[$args['id']] ?? null; @@ -303,7 +301,7 @@ class StarWarsSchema 'type' => Type::nonNull(Type::string()), ], ], - 'resolve' => function ($root, $args) { + 'resolve' => static function ($root, $args) { $droids = StarWarsData::droids(); return $droids[$args['id']] ?? null; diff --git a/tests/Type/DefinitionTest.php b/tests/Type/DefinitionTest.php index cb6d393..820159a 100644 --- a/tests/Type/DefinitionTest.php +++ b/tests/Type/DefinitionTest.php @@ -19,6 +19,8 @@ use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Schema; use GraphQL\Utils\Utils; use PHPUnit\Framework\TestCase; +use stdClass; +use Throwable; use function count; use function get_class; use function json_encode; @@ -80,11 +82,11 @@ class DefinitionTest extends TestCase $this->scalarType = new CustomScalarType([ 'name' => 'Scalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => function () { + 'parseValue' => static function () { }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]); @@ -403,7 +405,7 @@ class DefinitionTest extends TestCase 'fields' => [ 'f' => ['type' => Type::int()], ], - 'interfaces' => function () use (&$someInterface) { + 'interfaces' => static function () use (&$someInterface) { return [$someInterface]; }, ]); @@ -557,7 +559,7 @@ class DefinitionTest extends TestCase $user = new ObjectType([ 'name' => 'User', - 'fields' => function () use (&$blog, &$called) { + 'fields' => static function () use (&$blog, &$called) { self::assertNotNull($blog, 'Blog type is expected to be defined at this point, but it is null'); $called = true; @@ -566,20 +568,20 @@ class DefinitionTest extends TestCase 'blogs' => ['type' => Type::nonNull(Type::listOf(Type::nonNull($blog)))], ]; }, - 'interfaces' => function () use ($node) { + 'interfaces' => static function () use ($node) { return [$node]; }, ]); $blog = new ObjectType([ 'name' => 'Blog', - 'fields' => function () use ($user) { + 'fields' => static function () use ($user) { return [ 'id' => ['type' => Type::nonNull(Type::id())], 'owner' => ['type' => Type::nonNull($user)], ]; }, - 'interfaces' => function () use ($node) { + 'interfaces' => static function () use ($node) { return [$node]; }, ]); @@ -612,7 +614,7 @@ class DefinitionTest extends TestCase $called = false; $inputObject = new InputObjectType([ 'name' => 'InputObject', - 'fields' => function () use (&$inputObject, &$called) { + 'fields' => static function () use (&$inputObject, &$called) { $called = true; return [ @@ -649,7 +651,7 @@ class DefinitionTest extends TestCase $called = false; $interface = new InterfaceType([ 'name' => 'SomeInterface', - 'fields' => function () use (&$interface, &$called) { + 'fields' => static function () use (&$interface, &$called) { $called = true; return [ @@ -679,7 +681,7 @@ class DefinitionTest extends TestCase { $interface = new InterfaceType([ 'name' => 'SomeInterface', - 'fields' => function () use (&$interface) { + 'fields' => static function () use (&$interface) { return [ 'value' => Type::string(), 'nested' => $interface, @@ -730,11 +732,11 @@ class DefinitionTest extends TestCase { $idType = new CustomScalarType([ 'name' => 'ID', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => function () { + 'parseValue' => static function () { }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]); @@ -755,7 +757,7 @@ class DefinitionTest extends TestCase { $objType = new ObjectType([ 'name' => 'SomeObject', - 'fields' => function () { + 'fields' => static function () { return [ 'f' => ['type' => Type::string()], ]; @@ -805,7 +807,7 @@ class DefinitionTest extends TestCase { $objType = new ObjectType([ 'name' => 'SomeObject', - 'fields' => function () { + 'fields' => static function () { return [['field' => Type::string()]]; }, ]); @@ -901,7 +903,7 @@ class DefinitionTest extends TestCase { $objType = new ObjectType([ 'name' => 'SomeObject', - 'interfaces' => new \stdClass(), + 'interfaces' => new stdClass(), 'fields' => ['f' => ['type' => Type::string()]], ]); $this->expectException(InvariantViolation::class); @@ -918,8 +920,8 @@ class DefinitionTest extends TestCase { $objType = new ObjectType([ 'name' => 'SomeObject', - 'interfaces' => function () { - return new \stdClass(); + 'interfaces' => static function () { + return new stdClass(); }, 'fields' => ['f' => ['type' => Type::string()]], ]); @@ -939,7 +941,7 @@ class DefinitionTest extends TestCase { $this->expectNotToPerformAssertions(); // should not throw: - $this->schemaWithObjectWithFieldResolver(function () { + $this->schemaWithObjectWithFieldResolver(static function () { }); } @@ -1083,7 +1085,7 @@ class DefinitionTest extends TestCase $type = new InterfaceType([ 'name' => 'AnotherInterface', - 'resolveType' => new \stdClass(), + 'resolveType' => new stdClass(), 'fields' => ['f' => ['type' => Type::string()]], ]); $type->assertValid(); @@ -1148,7 +1150,7 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new UnionType([ 'name' => 'SomeUnion', - 'resolveType' => new \stdClass(), + 'resolveType' => new stdClass(), 'types' => [$this->objectWithIsTypeOf], ]) ); @@ -1164,7 +1166,7 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { return null; }, ]) @@ -1203,7 +1205,7 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => new \stdClass(), + 'serialize' => new stdClass(), ]) ); } @@ -1218,11 +1220,11 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => function () { + 'parseValue' => static function () { }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]) ); @@ -1240,9 +1242,9 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => function () { + 'parseValue' => static function () { }, ]) ); @@ -1260,9 +1262,9 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]) ); @@ -1280,10 +1282,10 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => new \stdClass(), - 'parseLiteral' => new \stdClass(), + 'parseValue' => new stdClass(), + 'parseLiteral' => new stdClass(), ]) ); } @@ -1317,7 +1319,7 @@ class DefinitionTest extends TestCase $this->schemaWithFieldType( new ObjectType([ 'name' => 'AnotherObject', - 'isTypeOf' => new \stdClass(), + 'isTypeOf' => new stdClass(), 'fields' => ['f' => ['type' => Type::string()]], ]) ); @@ -1411,7 +1413,7 @@ class DefinitionTest extends TestCase { $inputObjType = new InputObjectType([ 'name' => 'SomeInputObject', - 'fields' => function () { + 'fields' => static function () { return [ 'f' => ['type' => Type::string()], ]; @@ -1445,7 +1447,7 @@ class DefinitionTest extends TestCase { $inputObjType = new InputObjectType([ 'name' => 'SomeInputObject', - 'fields' => function () { + 'fields' => static function () { return []; }, ]); @@ -1467,7 +1469,7 @@ class DefinitionTest extends TestCase 'fields' => [ 'f' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return 0; }, ], @@ -1493,7 +1495,7 @@ class DefinitionTest extends TestCase 'fields' => [ 'f' => [ 'type' => Type::string(), - 'resolve' => new \stdClass(), + 'resolve' => new stdClass(), ], ], ]); @@ -1591,12 +1593,12 @@ class DefinitionTest extends TestCase Type::nonNull(Type::string()), ]; - $badTypes = [[], new \stdClass(), '', null]; + $badTypes = [[], new stdClass(), '', null]; foreach ($types as $type) { try { Type::listOf($type); - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->fail('List is expected to accept type: ' . get_class($type) . ', but got error: ' . $e->getMessage()); } } @@ -1630,14 +1632,14 @@ class DefinitionTest extends TestCase $notNullableTypes = [ Type::nonNull(Type::string()), [], - new \stdClass(), + new stdClass(), '', null, ]; foreach ($nullableTypes as $type) { try { Type::nonNull($type); - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->fail('NonNull is expected to accept type: ' . get_class($type) . ', but got error: ' . $e->getMessage()); } } @@ -1659,7 +1661,7 @@ class DefinitionTest extends TestCase { $FakeString = new CustomScalarType([ 'name' => 'String', - 'serialize' => function () { + 'serialize' => static function () { }, ]); diff --git a/tests/Type/EnumTypeTest.php b/tests/Type/EnumTypeTest.php index 0fc48f6..df920e2 100644 --- a/tests/Type/EnumTypeTest.php +++ b/tests/Type/EnumTypeTest.php @@ -51,10 +51,10 @@ class EnumTypeTest extends TestCase ]); $Complex1 = [ - 'someRandomFunction' => function () { + 'someRandomFunction' => static function () { }, ]; - $Complex2 = new \ArrayObject(['someRandomValue' => 123]); + $Complex2 = new ArrayObject(['someRandomValue' => 123]); $ComplexEnum = new EnumType([ 'name' => 'Complex', @@ -74,7 +74,7 @@ class EnumTypeTest extends TestCase 'fromInt' => ['type' => Type::int()], 'fromString' => ['type' => Type::string()], ], - 'resolve' => function ($value, $args) { + 'resolve' => static function ($value, $args) { if (isset($args['fromInt'])) { return $args['fromInt']; } @@ -92,7 +92,7 @@ class EnumTypeTest extends TestCase 'fromName' => ['type' => Type::string()], 'fromValue' => ['type' => Type::string()], ], - 'resolve' => function ($value, $args) { + 'resolve' => static function ($value, $args) { if (isset($args['fromName'])) { return $args['fromName']; } @@ -107,7 +107,7 @@ class EnumTypeTest extends TestCase 'fromEnum' => ['type' => $ColorType], 'fromInt' => ['type' => Type::int()], ], - 'resolve' => function ($value, $args) { + 'resolve' => static function ($value, $args) { if (isset($args['fromInt'])) { return $args['fromInt']; } @@ -132,7 +132,7 @@ class EnumTypeTest extends TestCase 'type' => Type::boolean(), ], ], - 'resolve' => function ($value, $args) use ($Complex2) { + 'resolve' => static function ($value, $args) use ($Complex2) { if (! empty($args['provideGoodValue'])) { // Note: this is one of the references of the internal values which // ComplexEnum allows. @@ -141,7 +141,7 @@ class EnumTypeTest extends TestCase if (! empty($args['provideBadValue'])) { // Note: similar shape, but not the same *reference* // as Complex2 above. Enum internal values require === equality. - return new \ArrayObject(['someRandomValue' => 123]); + return new ArrayObject(['someRandomValue' => 123]); } return $args['fromEnum']; @@ -156,7 +156,7 @@ class EnumTypeTest extends TestCase 'favoriteEnum' => [ 'type' => $ColorType, 'args' => ['color' => ['type' => $ColorType]], - 'resolve' => function ($value, $args) { + 'resolve' => static function ($value, $args) { return $args['color'] ?? null; }, ], @@ -169,7 +169,7 @@ class EnumTypeTest extends TestCase 'subscribeToEnum' => [ 'type' => $ColorType, 'args' => ['color' => ['type' => $ColorType]], - 'resolve' => function ($value, $args) { + 'resolve' => static function ($value, $args) { return $args['color'] ?? null; }, ], @@ -365,6 +365,7 @@ class EnumTypeTest extends TestCase /** * @see it('accepts enum literals as input arguments to subscriptions') + * * @todo */ public function testAcceptsEnumLiteralsAsInputArgumentsToSubscriptions() : void diff --git a/tests/Type/IntrospectionTest.php b/tests/Type/IntrospectionTest.php index 5007651..51feb40 100644 --- a/tests/Type/IntrospectionTest.php +++ b/tests/Type/IntrospectionTest.php @@ -1049,7 +1049,7 @@ class IntrospectionTest extends TestCase 'field' => [ 'type' => Type::string(), 'args' => ['complex' => ['type' => $TestInputObject]], - 'resolve' => function ($_, $args) { + 'resolve' => static function ($_, $args) { return json_encode($args['complex']); }, ], diff --git a/tests/Type/ResolutionTest.php b/tests/Type/ResolutionTest.php index 485085c..4a384fd 100644 --- a/tests/Type/ResolutionTest.php +++ b/tests/Type/ResolutionTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Type; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InterfaceType; @@ -460,8 +461,8 @@ class ResolutionTest extends TestCase $eager = new EagerResolution([]); $emptyDescriptor = $eager->getDescriptor(); - $typeLoader = function ($name) { - throw new \Exception('This should be never called for empty descriptor'); + $typeLoader = static function () { + throw new Exception('This should be never called for empty descriptor'); }; $lazy = new LazyResolution($emptyDescriptor, $typeLoader); @@ -547,7 +548,7 @@ class ResolutionTest extends TestCase ], ]; - $invalidTypeLoader = function ($name) { + $invalidTypeLoader = static function ($name) { switch ($name) { case 'null': return null; diff --git a/tests/Type/ResolveInfoTest.php b/tests/Type/ResolveInfoTest.php index f7797dd..d228a82 100644 --- a/tests/Type/ResolveInfoTest.php +++ b/tests/Type/ResolveInfoTest.php @@ -28,7 +28,7 @@ class ResolveInfoTest extends TestCase $author = new ObjectType([ 'name' => 'Author', - 'fields' => function () use ($image, &$article) { + 'fields' => static function () use ($image, &$article) { return [ 'id' => ['type' => Type::string()], 'name' => ['type' => Type::string()], @@ -151,7 +151,7 @@ class ResolveInfoTest extends TestCase 'fields' => [ 'article' => [ 'type' => $article, - 'resolve' => function ( + 'resolve' => static function ( $value, $args, $context, @@ -196,7 +196,7 @@ class ResolveInfoTest extends TestCase $author = new ObjectType([ 'name' => 'Author', - 'fields' => function () use ($image, &$article) { + 'fields' => static function () use ($image, &$article) { return [ 'id' => ['type' => Type::string()], 'name' => ['type' => Type::string()], @@ -324,7 +324,7 @@ class ResolveInfoTest extends TestCase 'fields' => [ 'article' => [ 'type' => $article, - 'resolve' => function ( + 'resolve' => static function ( $value, $args, $context, diff --git a/tests/Type/ScalarSerializationTest.php b/tests/Type/ScalarSerializationTest.php index 2203cb6..17f2368 100644 --- a/tests/Type/ScalarSerializationTest.php +++ b/tests/Type/ScalarSerializationTest.php @@ -7,6 +7,7 @@ namespace GraphQL\Tests\Type; use GraphQL\Error\Error; use GraphQL\Type\Definition\Type; use PHPUnit\Framework\TestCase; +use stdClass; class ScalarSerializationTest extends TestCase { @@ -176,7 +177,7 @@ class ScalarSerializationTest extends TestCase $stringType = Type::string(); $this->expectException(Error::class); $this->expectExceptionMessage('String cannot represent non scalar value: instance of stdClass'); - $stringType->serialize(new \stdClass()); + $stringType->serialize(new stdClass()); } /** @@ -215,6 +216,6 @@ class ScalarSerializationTest extends TestCase $idType = Type::id(); $this->expectException(Error::class); $this->expectExceptionMessage('ID type cannot represent non scalar value: instance of stdClass'); - $idType->serialize(new \stdClass()); + $idType->serialize(new stdClass()); } } diff --git a/tests/Type/SchemaTest.php b/tests/Type/SchemaTest.php index 288f0c2..c906bf8 100644 --- a/tests/Type/SchemaTest.php +++ b/tests/Type/SchemaTest.php @@ -46,7 +46,7 @@ class SchemaTest extends TestCase 'fields' => [ 'fieldName' => [ 'type' => Type::string(), - 'resolve' => function () { + 'resolve' => static function () { return ''; }, ], @@ -90,7 +90,7 @@ class SchemaTest extends TestCase 'fields' => [ 'getObject' => [ 'type' => $this->interfaceType, - 'resolve' => function () { + 'resolve' => static function () { return []; }, ], diff --git a/tests/Type/TypeLoaderTest.php b/tests/Type/TypeLoaderTest.php index 2e35d60..e7193ec 100644 --- a/tests/Type/TypeLoaderTest.php +++ b/tests/Type/TypeLoaderTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Type; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InterfaceType; @@ -11,6 +12,8 @@ use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; use PHPUnit\Framework\TestCase; +use stdClass; +use Throwable; use function lcfirst; class TypeLoaderTest extends TestCase @@ -55,7 +58,7 @@ class TypeLoaderTest extends TestCase 'id' => Type::string(), ]; }, - 'resolveType' => function () { + 'resolveType' => static function () { }, ]); @@ -69,7 +72,7 @@ class TypeLoaderTest extends TestCase 'body' => Type::string(), ]; }, - 'resolveType' => function () { + 'resolveType' => static function () { }, ]); @@ -152,7 +155,7 @@ class TypeLoaderTest extends TestCase 'name' => 'Query', 'fields' => ['a' => Type::string()], ]), - 'typeLoader' => function () { + 'typeLoader' => static function () { }, ]); } @@ -253,7 +256,7 @@ class TypeLoaderTest extends TestCase { $schema = new Schema([ 'query' => $this->query, - 'typeLoader' => function () { + 'typeLoader' => static function () { }, ]); @@ -267,8 +270,8 @@ class TypeLoaderTest extends TestCase { $schema = new Schema([ 'query' => $this->query, - 'typeLoader' => function () { - return new \stdClass(); + 'typeLoader' => static function () { + return new stdClass(); }, ]); @@ -297,12 +300,12 @@ class TypeLoaderTest extends TestCase { $schema = new Schema([ 'query' => $this->query, - 'typeLoader' => function () { - throw new \Exception('This is the exception we are looking for'); + 'typeLoader' => static function () { + throw new Exception('This is the exception we are looking for'); }, ]); - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('This is the exception we are looking for'); $schema->getType('Node'); diff --git a/tests/Type/ValidationTest.php b/tests/Type/ValidationTest.php index 102091c..04be994 100644 --- a/tests/Type/ValidationTest.php +++ b/tests/Type/ValidationTest.php @@ -66,11 +66,11 @@ class ValidationTest extends TestCase $this->SomeScalarType = new CustomScalarType([ 'name' => 'SomeScalar', - 'serialize' => function () { + 'serialize' => static function () { }, - 'parseValue' => function () { + 'parseValue' => static function () { }, - 'parseLiteral' => function () { + 'parseLiteral' => static function () { }, ]); @@ -144,19 +144,19 @@ class ValidationTest extends TestCase $types, Utils::map( $types, - function ($type) { + static function ($type) { return Type::listOf($type); } ), Utils::map( $types, - function ($type) { + static function ($type) { return Type::nonNull($type); } ), Utils::map( $types, - function ($type) { + static function ($type) { return Type::nonNull(Type::listOf($type)); } ) @@ -173,19 +173,19 @@ class ValidationTest extends TestCase { $this->assertEachCallableThrows( [ - function () { + static function () { return new ObjectType([]); }, - function () { + static function () { return new EnumType([]); }, - function () { + static function () { return new InputObjectType([]); }, - function () { + static function () { return new UnionType([]); }, - function () { + static function () { return new InterfaceType([]); }, ], @@ -347,7 +347,7 @@ class ValidationTest extends TestCase implode( "\n", array_map( - function ($error) { + static function ($error) { return $error->getMessage(); }, $array @@ -581,7 +581,7 @@ class ValidationTest extends TestCase $manualSchema2 = $this->schemaWithFieldType( new ObjectType([ 'name' => 'IncompleteObject', - 'fields' => function () { + 'fields' => static function () { return []; }, ]) @@ -989,6 +989,7 @@ class ValidationTest extends TestCase /** * @see it('rejects an Enum type with incorrectly named values') + * * @dataProvider invalidEnumValueName */ public function testRejectsAnEnumTypeWithIncorrectlyNamedValues($name, $expectedMessage) : void @@ -1974,7 +1975,7 @@ class ValidationTest extends TestCase public function testRejectsDifferentInstancesOfTheSameType() : void { // Invalid: always creates new instance vs returning one from registry - $typeLoader = function ($name) { + $typeLoader = static function ($name) { switch ($name) { case 'Query': return new ObjectType([ diff --git a/tests/Utils/AstFromValueTest.php b/tests/Utils/AstFromValueTest.php index 7b09b43..b01a73c 100644 --- a/tests/Utils/AstFromValueTest.php +++ b/tests/Utils/AstFromValueTest.php @@ -20,6 +20,7 @@ use GraphQL\Type\Definition\Type; use GraphQL\Utils\AST; use PHPUnit\Framework\TestCase; use stdClass; +use Throwable; class AstFromValueTest extends TestCase { @@ -61,14 +62,14 @@ class AstFromValueTest extends TestCase { // GraphQL spec does not allow coercing non-integer values to Int to avoid // accidental data loss. - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Int cannot represent non-integer value: 123.5'); AST::astFromValue(123.5, Type::int()); } public function testConvertsIntValuesToASTsCannotRepresentNon32bitsInteger() : void { - $this->expectException(\Throwable::class); + $this->expectException(Throwable::class); $this->expectExceptionMessage('Int cannot represent non 32-bit signed integer value: 1.0E+40'); AST::astFromValue( 1e40, @@ -165,7 +166,7 @@ class AstFromValueTest extends TestCase private function complexValue() { if (! $this->complexValue) { - $this->complexValue = new \stdClass(); + $this->complexValue = new stdClass(); $this->complexValue->someArbitrary = 'complexValue'; } @@ -232,6 +233,7 @@ class AstFromValueTest extends TestCase /** * @param mixed $value + * * @return ObjectFieldNode */ private function objectField(string $name, $value) @@ -257,9 +259,9 @@ class AstFromValueTest extends TestCase self::assertEquals( new ObjectValueNode([ - 'fields' => [ - $this->objectField('foo', new NullValueNode([])), - ], + 'fields' => [ + $this->objectField('foo', new NullValueNode([])), + ], ]), AST::astFromValue(['foo' => null], $inputObj) ); diff --git a/tests/Utils/BuildSchemaTest.php b/tests/Utils/BuildSchemaTest.php index 234157c..dfdf98a 100644 --- a/tests/Utils/BuildSchemaTest.php +++ b/tests/Utils/BuildSchemaTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Utils; +use Closure; use GraphQL\Error\Error; use GraphQL\GraphQL; use GraphQL\Language\AST\EnumTypeDefinitionNode; @@ -51,7 +52,7 @@ class BuildSchemaTest extends TestCase '); $root = [ - 'add' => function ($root, $args) { + 'add' => static function ($root, $args) { return $args['x'] + $args['y']; }, ]; @@ -1196,7 +1197,7 @@ interface Hello { $decorated = []; $calls = []; - $typeConfigDecorator = function ($defaultConfig, $node, $allNodesMap) use (&$decorated, &$calls) { + $typeConfigDecorator = static function ($defaultConfig, $node, $allNodesMap) use (&$decorated, &$calls) { $decorated[] = $defaultConfig['name']; $calls[] = [$defaultConfig, $node, $allNodesMap]; @@ -1207,17 +1208,17 @@ interface Hello { $schema->getTypeMap(); self::assertEquals(['Query', 'Color', 'Hello'], $decorated); - list($defaultConfig, $node, $allNodesMap) = $calls[0]; + [$defaultConfig, $node, $allNodesMap] = $calls[0]; self::assertInstanceOf(ObjectTypeDefinitionNode::class, $node); self::assertEquals('Query', $defaultConfig['name']); - self::assertInstanceOf(\Closure::class, $defaultConfig['fields']); - self::assertInstanceOf(\Closure::class, $defaultConfig['interfaces']); + self::assertInstanceOf(Closure::class, $defaultConfig['fields']); + self::assertInstanceOf(Closure::class, $defaultConfig['interfaces']); self::assertArrayHasKey('description', $defaultConfig); self::assertCount(5, $defaultConfig); self::assertEquals(array_keys($allNodesMap), ['Query', 'Color', 'Hello']); self::assertEquals('My description of Query', $schema->getType('Query')->description); - list($defaultConfig, $node, $allNodesMap) = $calls[1]; + [$defaultConfig, $node, $allNodesMap] = $calls[1]; self::assertInstanceOf(EnumTypeDefinitionNode::class, $node); self::assertEquals('Color', $defaultConfig['name']); $enumValue = [ @@ -1236,10 +1237,10 @@ interface Hello { self::assertEquals(array_keys($allNodesMap), ['Query', 'Color', 'Hello']); self::assertEquals('My description of Color', $schema->getType('Color')->description); - list($defaultConfig, $node, $allNodesMap) = $calls[2]; + [$defaultConfig, $node, $allNodesMap] = $calls[2]; self::assertInstanceOf(InterfaceTypeDefinitionNode::class, $node); self::assertEquals('Hello', $defaultConfig['name']); - self::assertInstanceOf(\Closure::class, $defaultConfig['fields']); + self::assertInstanceOf(Closure::class, $defaultConfig['fields']); self::assertArrayHasKey('description', $defaultConfig); self::assertCount(4, $defaultConfig); self::assertEquals(array_keys($allNodesMap), ['Query', 'Color', 'Hello']); @@ -1276,7 +1277,7 @@ type World implements Hello { $doc = Parser::parse($body); $created = []; - $typeConfigDecorator = function ($config, $node) use (&$created) { + $typeConfigDecorator = static function ($config, $node) use (&$created) { $created[] = $node->name->value; return $config; diff --git a/tests/Utils/MixedStoreTest.php b/tests/Utils/MixedStoreTest.php index 1e52d4a..42e64d7 100644 --- a/tests/Utils/MixedStoreTest.php +++ b/tests/Utils/MixedStoreTest.php @@ -7,6 +7,7 @@ namespace GraphQL\Tests\Utils; use GraphQL\Utils\MixedStore; use GraphQL\Utils\Utils; use PHPUnit\Framework\TestCase; +use stdClass; class MixedStoreTest extends TestCase { @@ -36,8 +37,8 @@ class MixedStoreTest extends TestCase '1', 'a', [], - new \stdClass(), - function () { + new stdClass(), + static function () { }, new MixedStore(), ]; @@ -111,7 +112,7 @@ class MixedStoreTest extends TestCase $this->assertAcceptsKeyValue([], $value); $this->assertAcceptsKeyValue([null], $value); $this->assertAcceptsKeyValue([[]], $value); - $this->assertAcceptsKeyValue([new \stdClass()], $value); + $this->assertAcceptsKeyValue([new stdClass()], $value); $this->assertAcceptsKeyValue(['a', 'b'], $value); $this->assertAcceptsKeyValue(['a' => 'b'], $value); } @@ -120,10 +121,10 @@ class MixedStoreTest extends TestCase public function testAcceptsObjectKeys() : void { foreach ($this->getPossibleValues() as $value) { - $this->assertAcceptsKeyValue(new \stdClass(), $value); + $this->assertAcceptsKeyValue(new stdClass(), $value); $this->assertAcceptsKeyValue(new MixedStore(), $value); $this->assertAcceptsKeyValue( - function () { + static function () { }, $value ); diff --git a/tests/Utils/QuotedOrListTest.php b/tests/Utils/QuotedOrListTest.php index afd67e7..53e8f69 100644 --- a/tests/Utils/QuotedOrListTest.php +++ b/tests/Utils/QuotedOrListTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Utils; use GraphQL\Utils\Utils; +use LogicException; use PHPUnit\Framework\TestCase; class QuotedOrListTest extends TestCase @@ -15,7 +16,7 @@ class QuotedOrListTest extends TestCase */ public function testResturnsResultsWhenInputIsEmpty() : void { - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); Utils::quotedOrList([]); } diff --git a/tests/Utils/SchemaPrinterTest.php b/tests/Utils/SchemaPrinterTest.php index 84954ce..e014e6b 100644 --- a/tests/Utils/SchemaPrinterTest.php +++ b/tests/Utils/SchemaPrinterTest.php @@ -591,7 +591,7 @@ type Query { { $oddType = new CustomScalarType([ 'name' => 'Odd', - 'serialize' => function ($value) { + 'serialize' => static function ($value) { return $value % 2 === 1 ? $value : null; }, ]); diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 0984714..b912382 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -5,16 +5,18 @@ declare(strict_types=1); namespace GraphQL\Tests; use GraphQL\Utils\Utils; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; +use stdClass; class UtilsTest extends TestCase { public function testAssignThrowsExceptionOnMissingRequiredKey() : void { - $object = new \stdClass(); + $object = new stdClass(); $object->requiredKey = 'value'; - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Key requiredKey is expected to be set and not to be null'); Utils::assign($object, [], ['requiredKey']); } diff --git a/tests/Validator/OverlappingFieldsCanBeMergedTest.php b/tests/Validator/OverlappingFieldsCanBeMergedTest.php index 411aefc..30291fa 100644 --- a/tests/Validator/OverlappingFieldsCanBeMergedTest.php +++ b/tests/Validator/OverlappingFieldsCanBeMergedTest.php @@ -703,7 +703,7 @@ class OverlappingFieldsCanBeMergedTest extends ValidatorTestCase $SomeBox = new InterfaceType([ 'name' => 'SomeBox', - 'fields' => function () use (&$SomeBox) { + 'fields' => static function () use (&$SomeBox) { return [ 'deepBox' => ['type' => $SomeBox], 'unrelatedField' => ['type' => Type::string()], @@ -714,7 +714,7 @@ class OverlappingFieldsCanBeMergedTest extends ValidatorTestCase $StringBox = new ObjectType([ 'name' => 'StringBox', 'interfaces' => [$SomeBox], - 'fields' => function () use (&$StringBox, &$IntBox) { + 'fields' => static function () use (&$StringBox, &$IntBox) { return [ 'scalar' => ['type' => Type::string()], 'deepBox' => ['type' => $StringBox], @@ -729,7 +729,7 @@ class OverlappingFieldsCanBeMergedTest extends ValidatorTestCase $IntBox = new ObjectType([ 'name' => 'IntBox', 'interfaces' => [$SomeBox], - 'fields' => function () use (&$StringBox, &$IntBox) { + 'fields' => static function () use (&$StringBox, &$IntBox) { return [ 'scalar' => ['type' => Type::int()], 'deepBox' => ['type' => $IntBox], @@ -797,7 +797,7 @@ class OverlappingFieldsCanBeMergedTest extends ValidatorTestCase ], ]); - $schema = new Schema([ + return new Schema([ 'query' => new ObjectType([ 'name' => 'QueryRoot', 'fields' => [ @@ -807,8 +807,6 @@ class OverlappingFieldsCanBeMergedTest extends ValidatorTestCase ]), 'types' => [$IntBox, $StringBox, $NonNullStringBox1Impl, $NonNullStringBox2Impl], ]); - - return $schema; } /** diff --git a/tests/Validator/QueryComplexityTest.php b/tests/Validator/QueryComplexityTest.php index d0004f0..998b751 100644 --- a/tests/Validator/QueryComplexityTest.php +++ b/tests/Validator/QueryComplexityTest.php @@ -168,10 +168,10 @@ class QueryComplexityTest extends QuerySecurityTestCase $reportedError = new Error('OtherValidatorError'); $otherRule = new CustomValidationRule( 'otherRule', - function (ValidationContext $context) use ($reportedError) { + static function (ValidationContext $context) use ($reportedError) { return [ NodeKind::OPERATION_DEFINITION => [ - 'leave' => function () use ($context, $reportedError) { + 'leave' => static function () use ($context, $reportedError) { $context->reportError($reportedError); }, ], diff --git a/tests/Validator/QueryDepthTest.php b/tests/Validator/QueryDepthTest.php index bccb26c..650d52d 100644 --- a/tests/Validator/QueryDepthTest.php +++ b/tests/Validator/QueryDepthTest.php @@ -14,6 +14,7 @@ class QueryDepthTest extends QuerySecurityTestCase * @param int $queryDepth * @param int $maxQueryDepth * @param string[][] $expectedErrors + * * @dataProvider queryDataProvider */ public function testSimpleQueries($queryDepth, $maxQueryDepth = 7, $expectedErrors = []) : void @@ -23,9 +24,7 @@ class QueryDepthTest extends QuerySecurityTestCase private function buildRecursiveQuery($depth) { - $query = sprintf('query MyQuery { human%s }', $this->buildRecursiveQueryPart($depth)); - - return $query; + return sprintf('query MyQuery { human%s }', $this->buildRecursiveQueryPart($depth)); } private function buildRecursiveQueryPart($depth) @@ -38,7 +37,7 @@ class QueryDepthTest extends QuerySecurityTestCase $part = $templates['human']; for ($i = 1; $i <= $depth; ++$i) { - $key = ($i % 2 === 1) ? 'human' : 'dog'; + $key = $i % 2 === 1 ? 'human' : 'dog'; $template = $templates[$key]; $part = sprintf($part, ($key === 'human' ? ' owner ' : '') . $template); @@ -52,6 +51,7 @@ class QueryDepthTest extends QuerySecurityTestCase * @param int $queryDepth * @param int $maxQueryDepth * @param string[][] $expectedErrors + * * @dataProvider queryDataProvider */ public function testFragmentQueries($queryDepth, $maxQueryDepth = 7, $expectedErrors = []) : void @@ -65,18 +65,17 @@ class QueryDepthTest extends QuerySecurityTestCase private function buildRecursiveUsingFragmentQuery($depth) { - $query = sprintf( + return sprintf( 'query MyQuery { human { ...F1 } } fragment F1 on Human %s', $this->buildRecursiveQueryPart($depth) ); - - return $query; } /** * @param int $queryDepth * @param int $maxQueryDepth * @param string[][] $expectedErrors + * * @dataProvider queryDataProvider */ public function testInlineFragmentQueries($queryDepth, $maxQueryDepth = 7, $expectedErrors = []) : void @@ -90,12 +89,10 @@ class QueryDepthTest extends QuerySecurityTestCase private function buildRecursiveUsingInlineFragmentQuery($depth) { - $query = sprintf( + return sprintf( 'query MyQuery { human { ...on Human %s } }', $this->buildRecursiveQueryPart($depth) ); - - return $query; } public function testComplexityIntrospectionQuery() : void diff --git a/tests/Validator/QuerySecuritySchema.php b/tests/Validator/QuerySecuritySchema.php index 534a340..64fcf45 100644 --- a/tests/Validator/QuerySecuritySchema.php +++ b/tests/Validator/QuerySecuritySchema.php @@ -66,7 +66,7 @@ class QuerySecuritySchema self::$humanType = new ObjectType( [ 'name' => 'Human', - 'fields' => function () { + 'fields' => static function () { return [ 'firstName' => ['type' => Type::nonNull(Type::string())], 'dogs' => [ @@ -75,7 +75,7 @@ class QuerySecuritySchema Type::nonNull(self::buildDogType()) ) ), - 'complexity' => function ($childrenComplexity, $args) { + 'complexity' => static function ($childrenComplexity, $args) { $complexity = isset($args['name']) ? 1 : 10; return $childrenComplexity + $complexity; diff --git a/tests/Validator/QuerySecurityTestCase.php b/tests/Validator/QuerySecurityTestCase.php index 7c4e036..4eb5f74 100644 --- a/tests/Validator/QuerySecurityTestCase.php +++ b/tests/Validator/QuerySecurityTestCase.php @@ -52,6 +52,7 @@ abstract class QuerySecurityTestCase extends TestCase * @param string $queryString * @param int $max * @param string[][] $expectedErrors + * * @return Error[] */ protected function assertDocumentValidator($queryString, $max, array $expectedErrors = []) : array diff --git a/tests/Validator/ValidatorTestCase.php b/tests/Validator/ValidatorTestCase.php index efafb11..55e9136 100644 --- a/tests/Validator/ValidatorTestCase.php +++ b/tests/Validator/ValidatorTestCase.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Tests\Validator; +use Exception; use GraphQL\Language\Parser; use GraphQL\Type\Definition\CustomScalarType; use GraphQL\Type\Definition\Directive; @@ -63,7 +64,7 @@ abstract class ValidatorTestCase extends TestCase $Canine = new InterfaceType([ 'name' => 'Canine', - 'fields' => function () { + 'fields' => static function () { return [ 'name' => [ 'type' => Type::string(), @@ -110,7 +111,7 @@ abstract class ValidatorTestCase extends TestCase $Cat = new ObjectType([ 'name' => 'Cat', - 'fields' => function () use (&$FurColor) { + 'fields' => static function () use (&$FurColor) { return [ 'name' => [ 'type' => Type::string(), @@ -141,7 +142,7 @@ abstract class ValidatorTestCase extends TestCase $Human = new ObjectType([ 'name' => 'Human', 'interfaces' => [$Being, $Intelligent], - 'fields' => function () use (&$Human, $Pet) { + 'fields' => static function () use (&$Human, $Pet) { return [ 'name' => [ 'type' => Type::string(), @@ -289,26 +290,26 @@ abstract class ValidatorTestCase extends TestCase $invalidScalar = new CustomScalarType([ 'name' => 'Invalid', - 'serialize' => function ($value) { + 'serialize' => static function ($value) { return $value; }, - 'parseLiteral' => function ($node) { - throw new \Exception('Invalid scalar is always invalid: ' . $node->value); + 'parseLiteral' => static function ($node) { + throw new Exception('Invalid scalar is always invalid: ' . $node->value); }, - 'parseValue' => function ($node) { - throw new \Exception('Invalid scalar is always invalid: ' . $node); + 'parseValue' => static function ($node) { + throw new Exception('Invalid scalar is always invalid: ' . $node); }, ]); $anyScalar = new CustomScalarType([ 'name' => 'Any', - 'serialize' => function ($value) { + 'serialize' => static function ($value) { return $value; }, - 'parseLiteral' => function ($node) { + 'parseLiteral' => static function ($node) { return $node; }, // Allows any value - 'parseValue' => function ($value) { + 'parseValue' => static function ($value) { return $value; }, // Allows any value ]); @@ -341,7 +342,7 @@ abstract class ValidatorTestCase extends TestCase ], ]); - $testSchema = new Schema([ + return new Schema([ 'query' => $queryRoot, 'directives' => [ Directive::includeDirective(), @@ -420,8 +421,6 @@ abstract class ValidatorTestCase extends TestCase ]), ], ]); - - return $testSchema; } protected function expectFailsRule($rule, $queryString, $errors) diff --git a/tests/Validator/ValuesOfCorrectTypeTest.php b/tests/Validator/ValuesOfCorrectTypeTest.php index b86c188..4de4df4 100644 --- a/tests/Validator/ValuesOfCorrectTypeTest.php +++ b/tests/Validator/ValuesOfCorrectTypeTest.php @@ -1286,6 +1286,7 @@ class ValuesOfCorrectTypeTest extends ValidatorTestCase * @see it('Partial object, unknown field arg') * * The sorting of equal elements has changed so that the test fails on php < 7 + * * @requires PHP 7.0 */ public function testPartialObjectUnknownFieldArg() : void From 73e75b63143f707c3d7cc015d3f53c3d4be5a621 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 11:03:10 +0200 Subject: [PATCH 03/10] Fix CS in src --- src/Deferred.php | 11 +++++++---- src/GraphQL.php | 19 +++++++++++++------ 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/Deferred.php b/src/Deferred.php index 6e962de..197eeeb 100644 --- a/src/Deferred.php +++ b/src/Deferred.php @@ -4,11 +4,14 @@ declare(strict_types=1); namespace GraphQL; +use Exception; use GraphQL\Executor\Promise\Adapter\SyncPromise; +use SplQueue; +use Throwable; class Deferred { - /** @var \SplQueue */ + /** @var SplQueue */ private static $queue; /** @var callable */ @@ -19,7 +22,7 @@ class Deferred public static function getQueue() { - return self::$queue ?: self::$queue = new \SplQueue(); + return self::$queue ?: self::$queue = new SplQueue(); } public static function runQueue() @@ -49,9 +52,9 @@ class Deferred try { $cb = $this->callback; $this->promise->resolve($cb()); - } catch (\Exception $e) { + } catch (Exception $e) { $this->promise->reject($e); - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->promise->reject($e); } } diff --git a/src/GraphQL.php b/src/GraphQL.php index f7915bb..e6fe8c9 100644 --- a/src/GraphQL.php +++ b/src/GraphQL.php @@ -64,12 +64,13 @@ class GraphQL * Empty array would allow to skip query validation (may be convenient for persisted * queries which are validated before persisting and assumed valid during execution) * - * @api * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param mixed[]|null $variableValues * @param ValidationRule[] $validationRules + * + * @api */ public static function executeQuery( SchemaType $schema, @@ -102,12 +103,13 @@ class GraphQL * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise. * Useful for Async PHP platforms. * - * @api * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param mixed[]|null $variableValues * @param ValidationRule[]|null $validationRules + * + * @api */ public static function promiseToExecute( PromiseAdapter $promiseAdapter, @@ -174,6 +176,7 @@ class GraphQL * @param mixed $rootValue * @param mixed $contextValue * @param mixed[]|null $variableValues + * * @return Promise|mixed[] */ public static function execute( @@ -203,7 +206,7 @@ class GraphQL if ($promiseAdapter instanceof SyncPromiseAdapter) { $result = $promiseAdapter->wait($result)->toArray(); } else { - $result = $result->then(function (ExecutionResult $r) { + $result = $result->then(static function (ExecutionResult $r) { return $r->toArray(); }); } @@ -255,8 +258,9 @@ class GraphQL /** * Returns directives defined in GraphQL spec * - * @api * @return Directive[] + * + * @api */ public static function getStandardDirectives() : array { @@ -266,8 +270,9 @@ class GraphQL /** * Returns types defined in GraphQL spec * - * @api * @return Type[] + * + * @api */ public static function getStandardTypes() : array { @@ -277,8 +282,9 @@ class GraphQL /** * Returns standard validation rules implementing GraphQL spec * - * @api * @return ValidationRule[] + * + * @api */ public static function getStandardValidationRules() : array { @@ -299,6 +305,7 @@ class GraphQL * Returns directives defined in GraphQL spec * * @deprecated Renamed to getStandardDirectives + * * @return Directive[] */ public static function getInternalDirectives() : array From 0063bd6c15a5ea96a6d2c36afbdc54684e95206d Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:36:07 +0200 Subject: [PATCH 04/10] Fix CS in src/Error --- src/Error/ClientAware.php | 6 ++- src/Error/Error.php | 31 +++++++++------ src/Error/FormattedError.php | 67 ++++++++++++++++++++------------ src/Error/InvariantViolation.php | 4 +- src/Error/UserError.php | 4 +- src/Error/Warning.php | 6 ++- 6 files changed, 77 insertions(+), 41 deletions(-) diff --git a/src/Error/ClientAware.php b/src/Error/ClientAware.php index c347004..adccb0c 100644 --- a/src/Error/ClientAware.php +++ b/src/Error/ClientAware.php @@ -17,8 +17,9 @@ interface ClientAware /** * Returns true when exception message is safe to be displayed to a client. * - * @api * @return bool + * + * @api */ public function isClientSafe(); @@ -27,8 +28,9 @@ interface ClientAware * * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. * - * @api * @return string + * + * @api */ public function getCategory(); } diff --git a/src/Error/Error.php b/src/Error/Error.php index 35019b2..8c3abb1 100644 --- a/src/Error/Error.php +++ b/src/Error/Error.php @@ -4,10 +4,13 @@ declare(strict_types=1); namespace GraphQL\Error; +use Exception; use GraphQL\Language\AST\Node; use GraphQL\Language\Source; use GraphQL\Language\SourceLocation; use GraphQL\Utils\Utils; +use JsonSerializable; +use Throwable; use Traversable; use function array_filter; use function array_map; @@ -28,7 +31,7 @@ use function iterator_to_array; * Class extends standard PHP `\Exception`, so all standard methods of base `\Exception` class * are available in addition to those listed below. */ -class Error extends \Exception implements \JsonSerializable, ClientAware +class Error extends Exception implements JsonSerializable, ClientAware { const CATEGORY_GRAPHQL = 'graphql'; const CATEGORY_INTERNAL = 'internal'; @@ -85,7 +88,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware * @param Node|Node[]|Traversable|null $nodes * @param mixed[]|null $positions * @param mixed[]|null $path - * @param \Throwable $previous + * @param Throwable $previous * @param mixed[] $extensions */ public function __construct( @@ -100,7 +103,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware parent::__construct($message, 0, $previous); // Compute list of blame nodes. - if ($nodes instanceof \Traversable) { + if ($nodes instanceof Traversable) { $nodes = iterator_to_array($nodes); } elseif ($nodes && ! is_array($nodes)) { $nodes = [$nodes]; @@ -136,6 +139,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware * @param mixed $error * @param Node[]|null $nodes * @param mixed[]|null $path + * * @return Error */ public static function createLocatedError($error, $nodes = null, $path = null) @@ -159,7 +163,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware $source = $error->source; $positions = $error->positions; $extensions = $error->extensions; - } elseif ($error instanceof \Exception || $error instanceof \Throwable) { + } elseif ($error instanceof Exception || $error instanceof Throwable) { $message = $error->getMessage(); $originalError = $error; } else { @@ -222,7 +226,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware { if ($this->positions === null && ! empty($this->nodes)) { $positions = array_map( - function ($node) { + static function ($node) { return isset($node->loc) ? $node->loc->start : null; }, $this->nodes @@ -230,7 +234,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware $this->positions = array_filter( $positions, - function ($p) { + static function ($p) { return $p !== null; } ); @@ -250,8 +254,9 @@ class Error extends \Exception implements \JsonSerializable, ClientAware * point out to field mentioned in multiple fragments. Errors during execution include a * single location, the field which produced the error. * - * @api * @return SourceLocation[] + * + * @api */ public function getLocations() { @@ -262,7 +267,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware if ($positions && $source) { $this->locations = array_map( - function ($pos) use ($source) { + static function ($pos) use ($source) { return $source->getLocation($pos); }, $positions @@ -270,7 +275,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware } elseif ($nodes) { $this->locations = array_filter( array_map( - function ($node) { + static function ($node) { if ($node->loc && $node->loc->source) { return $node->loc->source->getLocation($node->loc->start); } @@ -298,8 +303,9 @@ class Error extends \Exception implements \JsonSerializable, ClientAware * Returns an array describing the path from the root value to the field which produced this error. * Only included for execution errors. * - * @api * @return mixed[]|null + * + * @api */ public function getPath() { @@ -318,6 +324,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware * Returns array representation of error suitable for serialization * * @deprecated Use FormattedError::createFromException() instead + * * @return mixed[] */ public function toSerializableArray() @@ -328,7 +335,7 @@ class Error extends \Exception implements \JsonSerializable, ClientAware $locations = Utils::map( $this->getLocations(), - function (SourceLocation $loc) { + static function (SourceLocation $loc) { return $loc->toSerializableArray(); } ); @@ -348,7 +355,9 @@ class Error extends \Exception implements \JsonSerializable, ClientAware /** * Specify data which should be serialized to JSON + * * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + * * @return mixed data which can be serialized by json_encode, * which is a value of any type other than a resource. */ diff --git a/src/Error/FormattedError.php b/src/Error/FormattedError.php index 8ca886a..e03b2ac 100644 --- a/src/Error/FormattedError.php +++ b/src/Error/FormattedError.php @@ -4,12 +4,16 @@ declare(strict_types=1); namespace GraphQL\Error; +use Countable; +use ErrorException; +use Exception; use GraphQL\Language\AST\Node; use GraphQL\Language\Source; use GraphQL\Language\SourceLocation; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\WrappingType; use GraphQL\Utils\Utils; +use Throwable; use function addcslashes; use function array_filter; use function array_intersect_key; @@ -45,8 +49,9 @@ class FormattedError * Set default error message for internal errors formatted using createFormattedError(). * This value can be overridden by passing 3rd argument to `createFormattedError()`. * - * @api * @param string $msg + * + * @api */ public static function setInternalErrorMessage($msg) { @@ -132,6 +137,7 @@ class FormattedError /** * @param int $len + * * @return string */ private static function whitespace($len) @@ -141,6 +147,7 @@ class FormattedError /** * @param int $len + * * @return string */ private static function lpad($len, $str) @@ -157,17 +164,20 @@ class FormattedError * * For a list of available debug flags see GraphQL\Error\Debug constants. * - * @api - * @param \Throwable $e - * @param bool|int $debug - * @param string $internalErrorMessage + * @param Throwable $e + * @param bool|int $debug + * @param string $internalErrorMessage + * * @return mixed[] - * @throws \Throwable + * + * @throws Throwable + * + * @api */ public static function createFromException($e, $debug = false, $internalErrorMessage = null) { Utils::invariant( - $e instanceof \Exception || $e instanceof \Throwable, + $e instanceof Exception || $e instanceof Throwable, 'Expected exception, got %s', Utils::getVariableType($e) ); @@ -189,7 +199,7 @@ class FormattedError if ($e instanceof Error) { $locations = Utils::map( $e->getLocations(), - function (SourceLocation $loc) { + static function (SourceLocation $loc) { return $loc->toSerializableArray(); } ); @@ -215,11 +225,13 @@ class FormattedError * Decorates spec-compliant $formattedError with debug entries according to $debug flags * (see GraphQL\Error\Debug for available flags) * - * @param mixed[] $formattedError - * @param \Throwable $e - * @param bool $debug + * @param mixed[] $formattedError + * @param Throwable $e + * @param bool $debug + * * @return mixed[] - * @throws \Throwable + * + * @throws Throwable */ public static function addDebugEntries(array $formattedError, $e, $debug) { @@ -228,7 +240,7 @@ class FormattedError } Utils::invariant( - $e instanceof \Exception || $e instanceof \Throwable, + $e instanceof Exception || $e instanceof Throwable, 'Expected exception, got %s', Utils::getVariableType($e) ); @@ -259,7 +271,7 @@ class FormattedError } if ($debug & Debug::INCLUDE_TRACE) { - if ($e instanceof \ErrorException || $e instanceof \Error) { + if ($e instanceof ErrorException || $e instanceof \Error) { $formattedError += [ 'file' => $e->getFile(), 'line' => $e->getLine(), @@ -282,15 +294,16 @@ class FormattedError * If initial formatter is not set, FormattedError::createFromException is used * * @param bool $debug - * @return callable|\Closure + * + * @return callable|callable */ public static function prepareFormatter(?callable $formatter = null, $debug) { - $formatter = $formatter ?: function ($e) { + $formatter = $formatter ?: static function ($e) { return FormattedError::createFromException($e); }; if ($debug) { - $formatter = function ($e) use ($formatter, $debug) { + $formatter = static function ($e) use ($formatter, $debug) { return FormattedError::addDebugEntries($formatter($e), $e, $debug); }; } @@ -301,9 +314,11 @@ class FormattedError /** * Returns error trace as serializable array * - * @api - * @param \Throwable $error + * @param Throwable $error + * * @return mixed[] + * + * @api */ public static function toSafeTrace($error) { @@ -319,12 +334,12 @@ class FormattedError } return array_map( - function ($err) { + static function ($err) { $safeErr = array_intersect_key($err, ['file' => true, 'line' => true]); if (isset($err['function'])) { $func = $err['function']; - $args = ! empty($err['args']) ? array_map([__CLASS__, 'printVar'], $err['args']) : []; + $args = ! empty($err['args']) ? array_map([self::class, 'printVar'], $err['args']) : []; $funcStr = $func . '(' . implode(', ', $args) . ')'; if (isset($err['class'])) { @@ -342,6 +357,7 @@ class FormattedError /** * @param mixed $var + * * @return string */ public static function printVar($var) @@ -356,7 +372,7 @@ class FormattedError } if (is_object($var)) { - return 'instance of ' . get_class($var) . ($var instanceof \Countable ? '(' . count($var) . ')' : ''); + return 'instance of ' . get_class($var) . ($var instanceof Countable ? '(' . count($var) . ')' : ''); } if (is_array($var)) { return 'array(' . count($var) . ')'; @@ -382,8 +398,10 @@ class FormattedError /** * @deprecated as of v0.8.0 + * * @param string $error * @param SourceLocation[] $locations + * * @return mixed[] */ public static function create($error, array $locations = []) @@ -392,7 +410,7 @@ class FormattedError if (! empty($locations)) { $formatted['locations'] = array_map( - function ($loc) { + static function ($loc) { return $loc->toArray(); }, $locations @@ -404,9 +422,10 @@ class FormattedError /** * @deprecated as of v0.10.0, use general purpose method createFromException() instead + * * @return mixed[] */ - public static function createFromPHPError(\ErrorException $e) + public static function createFromPHPError(ErrorException $e) { return [ 'message' => $e->getMessage(), diff --git a/src/Error/InvariantViolation.php b/src/Error/InvariantViolation.php index f108109..6f9cfad 100644 --- a/src/Error/InvariantViolation.php +++ b/src/Error/InvariantViolation.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Error; +use LogicException; + /** * Class InvariantVoilation * @@ -11,6 +13,6 @@ namespace GraphQL\Error; * This exception should not inherit base Error exception as it is raised when there is an error somewhere in * user-land code */ -class InvariantViolation extends \LogicException +class InvariantViolation extends LogicException { } diff --git a/src/Error/UserError.php b/src/Error/UserError.php index a04ed78..67bb9bb 100644 --- a/src/Error/UserError.php +++ b/src/Error/UserError.php @@ -4,12 +4,14 @@ declare(strict_types=1); namespace GraphQL\Error; +use RuntimeException; + /** * Class UserError * * Error caused by actions of GraphQL clients. Can be safely displayed to a client... */ -class UserError extends \RuntimeException implements ClientAware +class UserError extends RuntimeException implements ClientAware { /** * @return bool diff --git a/src/Error/Warning.php b/src/Error/Warning.php index 16add8b..a652968 100644 --- a/src/Error/Warning.php +++ b/src/Error/Warning.php @@ -50,8 +50,9 @@ final class Warning * * When passing true - suppresses all warnings. * - * @api * @param bool|int $suppress + * + * @api */ public static function suppress($suppress = true) { @@ -74,8 +75,9 @@ final class Warning * * When passing true - re-enables all warnings. * - * @api * @param bool|int $enable + * + * @api */ public static function enable($enable = true) { From bfebcd7bee928a3405235d188fbee95e21048b19 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:54:16 +0200 Subject: [PATCH 05/10] Fix CS in src/Executor --- src/Executor/ExecutionResult.php | 15 +- src/Executor/Executor.php | 142 ++++++++++++------ .../Promise/Adapter/ReactPromiseAdapter.php | 4 +- src/Executor/Promise/Adapter/SyncPromise.php | 31 ++-- .../Promise/Adapter/SyncPromiseAdapter.php | 10 +- src/Executor/Promise/Promise.php | 3 +- src/Executor/Promise/PromiseAdapter.php | 31 ++-- src/Executor/Values.php | 21 ++- 8 files changed, 163 insertions(+), 94 deletions(-) diff --git a/src/Executor/ExecutionResult.php b/src/Executor/ExecutionResult.php index dbc3591..6ac7d41 100644 --- a/src/Executor/ExecutionResult.php +++ b/src/Executor/ExecutionResult.php @@ -6,6 +6,7 @@ namespace GraphQL\Executor; use GraphQL\Error\Error; use GraphQL\Error\FormattedError; +use JsonSerializable; use function array_map; /** @@ -16,7 +17,7 @@ use function array_map; * Could be converted to [spec-compliant](https://facebook.github.io/graphql/#sec-Response-Format) * serializable array using `toArray()` */ -class ExecutionResult implements \JsonSerializable +class ExecutionResult implements JsonSerializable { /** * Data collected from resolvers during query execution @@ -77,8 +78,9 @@ class ExecutionResult implements \JsonSerializable * // ... other keys * ); * - * @api * @return self + * + * @api */ public function setErrorFormatter(callable $errorFormatter) { @@ -97,8 +99,9 @@ class ExecutionResult implements \JsonSerializable * return array_map($formatter, $errors); * } * - * @api * @return self + * + * @api */ public function setErrorsHandler(callable $handler) { @@ -125,16 +128,18 @@ class ExecutionResult implements \JsonSerializable * $debug argument must be either bool (only adds "debugMessage" to result) or sum of flags from * GraphQL\Error\Debug * - * @api * @param bool|int $debug + * * @return mixed[] + * + * @api */ public function toArray($debug = false) { $result = []; if (! empty($this->errors)) { - $errorsHandler = $this->errorsHandler ?: function (array $errors, callable $formatter) { + $errorsHandler = $this->errorsHandler ?: static function (array $errors, callable $formatter) { return array_map($formatter, $errors); }; diff --git a/src/Executor/Executor.php b/src/Executor/Executor.php index 511939e..41d2eab 100644 --- a/src/Executor/Executor.php +++ b/src/Executor/Executor.php @@ -4,7 +4,9 @@ declare(strict_types=1); namespace GraphQL\Executor; +use ArrayAccess; use ArrayObject; +use Exception; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\Error\Warning; @@ -33,12 +35,18 @@ use GraphQL\Type\Introspection; use GraphQL\Type\Schema; use GraphQL\Utils\TypeInfo; use GraphQL\Utils\Utils; +use RuntimeException; +use SplObjectStorage; +use stdClass; +use Throwable; +use Traversable; use function array_keys; use function array_merge; use function array_reduce; use function array_values; use function get_class; use function is_array; +use function is_callable; use function is_object; use function is_string; use function sprintf; @@ -52,7 +60,7 @@ class Executor private static $UNDEFINED; /** @var callable|string[] */ - private static $defaultFieldResolver = [__CLASS__, 'defaultFieldResolver']; + private static $defaultFieldResolver = [self::class, 'defaultFieldResolver']; /** @var PromiseAdapter */ private static $promiseAdapter; @@ -60,7 +68,7 @@ class Executor /** @var ExecutionContext */ private $exeContext; - /** @var \SplObjectStorage */ + /** @var SplObjectStorage */ private $subFieldCache; private function __construct(ExecutionContext $context) @@ -70,13 +78,13 @@ class Executor } $this->exeContext = $context; - $this->subFieldCache = new \SplObjectStorage(); + $this->subFieldCache = new SplObjectStorage(); } /** * Custom default resolve function * - * @throws \Exception + * @throws Exception */ public static function setDefaultFieldResolver(callable $fn) { @@ -89,13 +97,14 @@ class Executor * Always returns ExecutionResult and never throws. All errors which occur during operation * execution are collected in `$result->errors`. * - * @api - * @param mixed|null $rootValue - * @param mixed[]|null $contextValue - * @param mixed[]|\ArrayAccess|null $variableValues - * @param string|null $operationName + * @param mixed|null $rootValue + * @param mixed[]|null $contextValue + * @param mixed[]|ArrayAccess|null $variableValues + * @param string|null $operationName * * @return ExecutionResult|Promise + * + * @api */ public static function execute( Schema $schema, @@ -146,12 +155,14 @@ class Executor * * Useful for async PHP platforms. * - * @api * @param mixed[]|null $rootValue * @param mixed[]|null $contextValue * @param mixed[]|null $variableValues * @param string|null $operationName + * * @return Promise + * + * @api */ public static function promiseToExecute( PromiseAdapter $promiseAdapter, @@ -187,10 +198,10 @@ class Executor * Constructs an ExecutionContext object from the arguments passed to * execute, which we will pass throughout the other execution methods. * - * @param mixed[] $rootValue - * @param mixed[] $contextValue - * @param mixed[]|\Traversable $rawVariableValues - * @param string|null $operationName + * @param mixed[] $rootValue + * @param mixed[] $contextValue + * @param mixed[]|Traversable $rawVariableValues + * @param string|null $operationName * * @return ExecutionContext|Error[] */ @@ -297,7 +308,8 @@ class Executor } /** - * @param mixed|null|Promise $data + * @param mixed|Promise|null $data + * * @return ExecutionResult|Promise */ private function buildResponse($data) @@ -317,12 +329,13 @@ class Executor * Implements the "Evaluating operations" section of the spec. * * @param mixed[] $rootValue - * @return Promise|\stdClass|mixed[] + * + * @return Promise|stdClass|mixed[] */ private function executeOperation(OperationDefinitionNode $operation, $rootValue) { $type = $this->getOperationRootType($this->exeContext->schema, $operation); - $fields = $this->collectFields($type, $operation->selectionSet, new \ArrayObject(), new \ArrayObject()); + $fields = $this->collectFields($type, $operation->selectionSet, new ArrayObject(), new ArrayObject()); $path = []; @@ -357,6 +370,7 @@ class Executor * Extracts the root type of the operation from the schema. * * @return ObjectType + * * @throws Error */ private function getOperationRootType(Schema $schema, OperationDefinitionNode $operation) @@ -411,7 +425,7 @@ class Executor * @param ArrayObject $fields * @param ArrayObject $visitedFragmentNames * - * @return \ArrayObject + * @return ArrayObject */ private function collectFields( ObjectType $runtimeType, @@ -428,7 +442,7 @@ class Executor } $name = self::getFieldEntryKey($selection); if (! isset($fields[$name])) { - $fields[$name] = new \ArrayObject(); + $fields[$name] = new ArrayObject(); } $fields[$name][] = $selection; break; @@ -475,6 +489,7 @@ class Executor * directives, where @skip has higher precedence than @include. * * @param FragmentSpreadNode|FieldNode|InlineFragmentNode $node + * * @return bool */ private function shouldIncludeNode($node) @@ -521,6 +536,7 @@ class Executor * Determines if a fragment is applicable to the given type. * * @param FragmentDefinitionNode|InlineFragmentNode $fragment + * * @return bool */ private function doesFragmentConditionMatch( @@ -551,7 +567,8 @@ class Executor * @param mixed[] $sourceValue * @param mixed[] $path * @param ArrayObject $fields - * @return Promise|\stdClass|mixed[] + * + * @return Promise|stdClass|mixed[] */ private function executeFieldsSerially(ObjectType $parentType, $sourceValue, $path, $fields) { @@ -567,7 +584,7 @@ class Executor } $promise = $this->getPromise($result); if ($promise) { - return $promise->then(function ($resolvedResult) use ($responseName, $results) { + return $promise->then(static function ($resolvedResult) use ($responseName, $results) { $results[$responseName] = $resolvedResult; return $results; }); @@ -578,7 +595,7 @@ class Executor [] ); if ($this->isPromise($result)) { - return $result->then(function ($resolvedResults) { + return $result->then(static function ($resolvedResults) { return self::fixResultsIfEmptyArray($resolvedResults); }); } @@ -595,7 +612,7 @@ class Executor * @param FieldNode[] $fieldNodes * @param mixed[] $path * - * @return mixed[]|\Exception|mixed|null + * @return mixed[]|Exception|mixed|null */ private function resolveField(ObjectType $parentType, $source, $fieldNodes, $path) { @@ -705,7 +722,8 @@ class Executor * @param mixed $source * @param mixed $context * @param ResolveInfo $info - * @return \Throwable|Promise|mixed + * + * @return Throwable|Promise|mixed */ private function resolveOrError($fieldDef, $fieldNode, $resolveFn, $source, $context, $info) { @@ -719,9 +737,9 @@ class Executor ); return $resolveFn($source, $args, $context, $info); - } catch (\Exception $error) { + } catch (Exception $error) { return $error; - } catch (\Throwable $error) { + } catch (Throwable $error) { return $error; } } @@ -733,6 +751,7 @@ class Executor * @param FieldNode[] $fieldNodes * @param string[] $path * @param mixed $result + * * @return mixed[]|Promise|null */ private function completeValueCatchingError( @@ -796,7 +815,9 @@ class Executor * @param FieldNode[] $fieldNodes * @param string[] $path * @param mixed $result + * * @return mixed[]|mixed|Promise|null + * * @throws Error */ public function completeValueWithLocatedError( @@ -829,9 +850,9 @@ class Executor } return $completed; - } catch (\Exception $error) { + } catch (Exception $error) { throw Error::createLocatedError($error, $fieldNodes, $path); - } catch (\Throwable $error) { + } catch (Throwable $error) { throw Error::createLocatedError($error, $fieldNodes, $path); } } @@ -860,9 +881,11 @@ class Executor * @param FieldNode[] $fieldNodes * @param string[] $path * @param mixed $result + * * @return mixed[]|mixed|Promise|null + * * @throws Error - * @throws \Throwable + * @throws Throwable */ private function completeValue( Type $returnType, @@ -880,7 +903,7 @@ class Executor }); } - if ($result instanceof \Exception || $result instanceof \Throwable) { + if ($result instanceof Exception || $result instanceof Throwable) { throw $result; } @@ -949,11 +972,12 @@ class Executor return $this->completeObjectValue($returnType, $fieldNodes, $info, $path, $result); } - throw new \RuntimeException(sprintf('Cannot complete value of unexpected type "%s".', $returnType)); + throw new RuntimeException(sprintf('Cannot complete value of unexpected type "%s".', $returnType)); } /** * @param mixed $value + * * @return bool */ private function isPromise($value) @@ -966,6 +990,7 @@ class Executor * otherwise returns null. * * @param mixed $value + * * @return Promise|null */ private function getPromise($value) @@ -998,14 +1023,15 @@ class Executor * * @param mixed[] $values * @param Promise|mixed|null $initialValue + * * @return mixed[] */ - private function promiseReduce(array $values, \Closure $callback, $initialValue) + private function promiseReduce(array $values, callable $callback, $initialValue) { return array_reduce($values, function ($previous, $value) use ($callback) { $promise = $this->getPromise($previous); if ($promise) { - return $promise->then(function ($resolved) use ($callback, $value) { + return $promise->then(static function ($resolved) use ($callback, $value) { return $callback($resolved, $value); }); } @@ -1020,14 +1046,16 @@ class Executor * @param FieldNode[] $fieldNodes * @param mixed[] $path * @param mixed $result + * * @return mixed[]|Promise - * @throws \Exception + * + * @throws Exception */ private function completeListValue(ListOfType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) { $itemType = $returnType->getWrappedType(); Utils::invariant( - is_array($result) || $result instanceof \Traversable, + is_array($result) || $result instanceof Traversable, 'User Error: expected iterable, but did not find one for field ' . $info->parentType . '.' . $info->fieldName . '.' ); $containsPromise = false; @@ -1051,20 +1079,22 @@ class Executor * Complete a Scalar or Enum by serializing to a valid value, throwing if serialization is not possible. * * @param mixed $result + * * @return mixed - * @throws \Exception + * + * @throws Exception */ private function completeLeafValue(LeafType $returnType, &$result) { try { return $returnType->serialize($result); - } catch (\Exception $error) { + } catch (Exception $error) { throw new InvariantViolation( 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), 0, $error ); - } catch (\Throwable $error) { + } catch (Throwable $error) { throw new InvariantViolation( 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), 0, @@ -1080,7 +1110,9 @@ class Executor * @param FieldNode[] $fieldNodes * @param mixed[] $path * @param mixed[] $result + * * @return mixed + * * @throws Error */ private function completeAbstractValue(AbstractType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) @@ -1142,6 +1174,7 @@ class Executor * * @param mixed|null $value * @param mixed|null $context + * * @return ObjectType|Promise|null */ private function defaultTypeResolver($value, $context, ResolveInfo $info, AbstractType $abstractType) @@ -1190,7 +1223,7 @@ class Executor if (! empty($promisedIsTypeOfResults)) { return $this->exeContext->promises->all($promisedIsTypeOfResults) - ->then(function ($isTypeOfResults) use ($possibleTypes) { + ->then(static function ($isTypeOfResults) use ($possibleTypes) { foreach ($isTypeOfResults as $index => $result) { if ($result) { return $possibleTypes[$index]; @@ -1210,7 +1243,9 @@ class Executor * @param FieldNode[] $fieldNodes * @param mixed[] $path * @param mixed $result - * @return mixed[]|Promise|\stdClass + * + * @return mixed[]|Promise|stdClass + * * @throws Error */ private function completeObjectValue(ObjectType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) @@ -1260,6 +1295,7 @@ class Executor /** * @param mixed[] $result * @param FieldNode[] $fieldNodes + * * @return Error */ private function invalidReturnTypeError( @@ -1277,7 +1313,9 @@ class Executor * @param FieldNode[] $fieldNodes * @param mixed[] $path * @param mixed[] $result - * @return mixed[]|Promise|\stdClass + * + * @return mixed[]|Promise|stdClass + * * @throws Error */ private function collectAndExecuteSubfields( @@ -1294,12 +1332,12 @@ class Executor private function collectSubFields(ObjectType $returnType, $fieldNodes) : ArrayObject { if (! isset($this->subFieldCache[$returnType])) { - $this->subFieldCache[$returnType] = new \SplObjectStorage(); + $this->subFieldCache[$returnType] = new SplObjectStorage(); } if (! isset($this->subFieldCache[$returnType][$fieldNodes])) { // Collect sub-fields to execute to complete this value. - $subFieldNodes = new \ArrayObject(); - $visitedFragmentNames = new \ArrayObject(); + $subFieldNodes = new ArrayObject(); + $visitedFragmentNames = new ArrayObject(); foreach ($fieldNodes as $fieldNode) { if (! isset($fieldNode->selectionSet)) { @@ -1325,7 +1363,8 @@ class Executor * @param mixed|null $source * @param mixed[] $path * @param ArrayObject $fields - * @return Promise|\stdClass|mixed[] + * + * @return Promise|stdClass|mixed[] */ private function executeFields(ObjectType $parentType, $source, $path, $fields) { @@ -1361,12 +1400,13 @@ class Executor * @see https://github.com/webonyx/graphql-php/issues/59 * * @param mixed[] $results - * @return \stdClass|mixed[] + * + * @return stdClass|mixed[] */ private static function fixResultsIfEmptyArray($results) { if ($results === []) { - return new \stdClass(); + return new stdClass(); } return $results; @@ -1380,6 +1420,7 @@ class Executor * any promises. * * @param (string|Promise)[] $assoc + * * @return mixed */ private function promiseForAssocArray(array $assoc) @@ -1389,7 +1430,7 @@ class Executor $promise = $this->exeContext->promises->all($valuesAndPromises); - return $promise->then(function ($values) use ($keys) { + return $promise->then(static function ($values) use ($keys) { $resolvedResults = []; foreach ($values as $i => $value) { $resolvedResults[$keys[$i]] = $value; @@ -1403,6 +1444,7 @@ class Executor * @param string|ObjectType|null $runtimeTypeOrName * @param FieldNode[] $fieldNodes * @param mixed $result + * * @return ObjectType */ private function ensureValidRuntimeType( @@ -1471,7 +1513,7 @@ class Executor $fieldName = $info->fieldName; $property = null; - if (is_array($source) || $source instanceof \ArrayAccess) { + if (is_array($source) || $source instanceof ArrayAccess) { if (isset($source[$fieldName])) { $property = $source[$fieldName]; } @@ -1481,6 +1523,6 @@ class Executor } } - return $property instanceof \Closure ? $property($source, $args, $context, $info) : $property; + return is_callable($property) ? $property($source, $args, $context, $info) : $property; } } diff --git a/src/Executor/Promise/Adapter/ReactPromiseAdapter.php b/src/Executor/Promise/Adapter/ReactPromiseAdapter.php index 4feb3c0..446d904 100644 --- a/src/Executor/Promise/Adapter/ReactPromiseAdapter.php +++ b/src/Executor/Promise/Adapter/ReactPromiseAdapter.php @@ -80,12 +80,12 @@ class ReactPromiseAdapter implements PromiseAdapter // TODO: rework with generators when PHP minimum required version is changed to 5.5+ $promisesOrValues = Utils::map( $promisesOrValues, - function ($item) { + static function ($item) { return $item instanceof Promise ? $item->adoptedPromise : $item; } ); - $promise = all($promisesOrValues)->then(function ($values) use ($promisesOrValues) { + $promise = all($promisesOrValues)->then(static function ($values) use ($promisesOrValues) { $orderedResults = []; foreach ($promisesOrValues as $key => $value) { diff --git a/src/Executor/Promise/Adapter/SyncPromise.php b/src/Executor/Promise/Adapter/SyncPromise.php index fd0f3ba..4d1f96e 100644 --- a/src/Executor/Promise/Adapter/SyncPromise.php +++ b/src/Executor/Promise/Adapter/SyncPromise.php @@ -4,8 +4,10 @@ declare(strict_types=1); namespace GraphQL\Executor\Promise\Adapter; +use Exception; use GraphQL\Executor\ExecutionResult; use GraphQL\Utils\Utils; +use SplQueue; use Throwable; use function is_object; use function method_exists; @@ -22,7 +24,7 @@ class SyncPromise const FULFILLED = 'fulfilled'; const REJECTED = 'rejected'; - /** @var \SplQueue */ + /** @var SplQueue */ public static $queue; /** @var string */ @@ -33,6 +35,7 @@ class SyncPromise /** * Promises created in `then` method of this promise and awaiting for resolution of this promise + * * @var mixed[][] */ private $waiting = []; @@ -51,7 +54,7 @@ class SyncPromise switch ($this->state) { case self::PENDING: if ($value === $this) { - throw new \Exception('Cannot resolve promise with self'); + throw new Exception('Cannot resolve promise with self'); } if (is_object($value) && method_exists($value, 'then')) { $value->then( @@ -72,11 +75,11 @@ class SyncPromise break; case self::FULFILLED: if ($this->result !== $value) { - throw new \Exception('Cannot change value of fulfilled promise'); + throw new Exception('Cannot change value of fulfilled promise'); } break; case self::REJECTED: - throw new \Exception('Cannot resolve rejected promise'); + throw new Exception('Cannot resolve rejected promise'); } return $this; @@ -84,8 +87,8 @@ class SyncPromise public function reject($reason) { - if (! $reason instanceof \Exception && ! $reason instanceof \Throwable) { - throw new \Exception('SyncPromise::reject() has to be called with an instance of \Throwable'); + if (! $reason instanceof Exception && ! $reason instanceof Throwable) { + throw new Exception('SyncPromise::reject() has to be called with an instance of \Throwable'); } switch ($this->state) { @@ -96,11 +99,11 @@ class SyncPromise break; case self::REJECTED: if ($reason !== $this->result) { - throw new \Exception('Cannot change rejection reason'); + throw new Exception('Cannot change rejection reason'); } break; case self::FULFILLED: - throw new \Exception('Cannot reject fulfilled promise'); + throw new Exception('Cannot reject fulfilled promise'); } return $this; @@ -116,14 +119,14 @@ class SyncPromise foreach ($this->waiting as $descriptor) { self::getQueue()->enqueue(function () use ($descriptor) { /** @var $promise self */ - list($promise, $onFulfilled, $onRejected) = $descriptor; + [$promise, $onFulfilled, $onRejected] = $descriptor; if ($this->state === self::FULFILLED) { try { $promise->resolve($onFulfilled ? $onFulfilled($this->result) : $this->result); - } catch (\Exception $e) { + } catch (Exception $e) { $promise->reject($e); - } catch (\Throwable $e) { + } catch (Throwable $e) { $promise->reject($e); } } elseif ($this->state === self::REJECTED) { @@ -133,9 +136,9 @@ class SyncPromise } else { $promise->reject($this->result); } - } catch (\Exception $e) { + } catch (Exception $e) { $promise->reject($e); - } catch (\Throwable $e) { + } catch (Throwable $e) { $promise->reject($e); } } @@ -146,7 +149,7 @@ class SyncPromise public static function getQueue() { - return self::$queue ?: self::$queue = new \SplQueue(); + return self::$queue ?: self::$queue = new SplQueue(); } public function then(?callable $onFulfilled = null, ?callable $onRejected = null) diff --git a/src/Executor/Promise/Adapter/SyncPromiseAdapter.php b/src/Executor/Promise/Adapter/SyncPromiseAdapter.php index 3ec9246..2df02af 100644 --- a/src/Executor/Promise/Adapter/SyncPromiseAdapter.php +++ b/src/Executor/Promise/Adapter/SyncPromiseAdapter.php @@ -4,12 +4,14 @@ declare(strict_types=1); namespace GraphQL\Executor\Promise\Adapter; +use Exception; use GraphQL\Deferred; use GraphQL\Error\InvariantViolation; use GraphQL\Executor\ExecutionResult; use GraphQL\Executor\Promise\Promise; use GraphQL\Executor\Promise\PromiseAdapter; use GraphQL\Utils\Utils; +use Throwable; use function count; /** @@ -67,9 +69,9 @@ class SyncPromiseAdapter implements PromiseAdapter 'reject', ] ); - } catch (\Exception $e) { + } catch (Exception $e) { $promise->reject($e); - } catch (\Throwable $e) { + } catch (Throwable $e) { $promise->reject($e); } @@ -111,7 +113,7 @@ class SyncPromiseAdapter implements PromiseAdapter if ($promiseOrValue instanceof Promise) { $result[$index] = null; $promiseOrValue->then( - function ($value) use ($index, &$count, $total, &$result, $all) { + static function ($value) use ($index, &$count, $total, &$result, $all) { $result[$index] = $value; $count++; if ($count < $total) { @@ -167,7 +169,6 @@ class SyncPromiseAdapter implements PromiseAdapter /** * Execute just before starting to run promise completion - * */ protected function beforeWait(Promise $promise) { @@ -175,7 +176,6 @@ class SyncPromiseAdapter implements PromiseAdapter /** * Execute while running promise completion - * */ protected function onWait(Promise $promise) { diff --git a/src/Executor/Promise/Promise.php b/src/Executor/Promise/Promise.php index 2f060e1..5823d14 100644 --- a/src/Executor/Promise/Promise.php +++ b/src/Executor/Promise/Promise.php @@ -24,14 +24,13 @@ class Promise */ public function __construct($adoptedPromise, PromiseAdapter $adapter) { - Utils::invariant(! $adoptedPromise instanceof self, 'Expecting promise from adapted system, got ' . __CLASS__); + Utils::invariant(! $adoptedPromise instanceof self, 'Expecting promise from adapted system, got ' . self::class); $this->adapter = $adapter; $this->adoptedPromise = $adoptedPromise; } /** - * * @return Promise */ public function then(?callable $onFulfilled = null, ?callable $onRejected = null) diff --git a/src/Executor/Promise/PromiseAdapter.php b/src/Executor/Promise/PromiseAdapter.php index 74582fa..c3d4098 100644 --- a/src/Executor/Promise/PromiseAdapter.php +++ b/src/Executor/Promise/PromiseAdapter.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Executor\Promise; +use Throwable; + /** * Provides a means for integration of async PHP platforms ([related docs](data-fetching.md#async-php)) */ @@ -12,18 +14,22 @@ interface PromiseAdapter /** * Return true if the value is a promise or a deferred of the underlying platform * - * @api * @param mixed $value + * * @return bool + * + * @api */ public function isThenable($value); /** * Converts thenable of the underlying platform into GraphQL\Executor\Promise\Promise instance * - * @api * @param object $thenable + * * @return Promise + * + * @api */ public function convertThenable($thenable); @@ -31,9 +37,9 @@ interface PromiseAdapter * Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\Executor\Promise\Promise. * - * @api - * * @return Promise + * + * @api */ public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null); @@ -43,17 +49,20 @@ interface PromiseAdapter * Expected resolver signature: * function(callable $resolve, callable $reject) * - * @api * @return Promise + * + * @api */ public function create(callable $resolver); /** * Creates a fulfilled Promise for a value if the value is not a promise. * - * @api * @param mixed $value + * * @return Promise + * + * @api */ public function createFulfilled($value = null); @@ -61,9 +70,11 @@ interface PromiseAdapter * Creates a rejected promise for a reason if the reason is not a promise. If * the provided reason is a promise, then it is returned as-is. * - * @api - * @param \Throwable $reason + * @param Throwable $reason + * * @return Promise + * + * @api */ public function createRejected($reason); @@ -71,9 +82,11 @@ interface PromiseAdapter * Given an array of promises (or values), returns a promise that is fulfilled when all the * items in the array are fulfilled. * - * @api * @param Promise[]|mixed[] $promisesOrValues Promises or values. + * * @return Promise + * + * @api */ public function all(array $promisesOrValues); } diff --git a/src/Executor/Values.php b/src/Executor/Values.php index 53e66cb..5550544 100644 --- a/src/Executor/Values.php +++ b/src/Executor/Values.php @@ -27,6 +27,7 @@ use GraphQL\Utils\AST; use GraphQL\Utils\TypeInfo; use GraphQL\Utils\Utils; use GraphQL\Utils\Value; +use stdClass; use Throwable; use function array_key_exists; use function array_map; @@ -41,6 +42,7 @@ class Values * * @param VariableDefinitionNode[] $varDefNodes * @param mixed[] $inputs + * * @return mixed[] */ public static function getVariableValues(Schema $schema, $varDefNodes, array $inputs) @@ -125,7 +127,7 @@ class Values if (isset($node->directives) && $node->directives instanceof NodeList) { $directiveNode = Utils::find( $node->directives, - function (DirectiveNode $directive) use ($directiveDef) { + static function (DirectiveNode $directive) use ($directiveDef) { return $directive->name->value === $directiveDef->name; } ); @@ -145,7 +147,9 @@ class Values * @param FieldDefinition|Directive $def * @param FieldNode|DirectiveNode $node * @param mixed[] $variableValues + * * @return mixed[] + * * @throws Error */ public static function getArgumentValues($def, $node, $variableValues = null) @@ -162,7 +166,7 @@ class Values /** @var ArgumentNode[] $argNodeMap */ $argNodeMap = $argNodes ? Utils::keyMap( $argNodes, - function (ArgumentNode $arg) { + static function (ArgumentNode $arg) { return $arg->name->value; } ) : []; @@ -222,18 +226,21 @@ class Values /** * @deprecated as of 8.0 (Moved to \GraphQL\Utils\AST::valueFromAST) * - * @param ValueNode $valueNode - * @param null $variables - * @return mixed[]|null|\stdClass + * @param ValueNode $valueNode + * @param mixed[]|null $variables + * + * @return mixed[]|stdClass|null */ - public static function valueFromAST($valueNode, InputType $type, $variables = null) + public static function valueFromAST($valueNode, InputType $type, ?array $variables = null) { return AST::valueFromAST($valueNode, $type, $variables); } /** * @deprecated as of 0.12 (Use coerceValue() directly for richer information) + * * @param mixed[] $value + * * @return string[] */ public static function isValidPHPValue($value, InputType $type) @@ -242,7 +249,7 @@ class Values return $errors ? array_map( - function (Throwable $error) { + static function (Throwable $error) { return $error->getMessage(); }, $errors From a95d2ad140537dc37ec969c4c2bb8c7ba643992c Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:48:10 +0200 Subject: [PATCH 06/10] Fix CS in src/Language --- src/Language/AST/EnumTypeDefinitionNode.php | 2 +- src/Language/AST/Location.php | 1 + src/Language/AST/Node.php | 2 + src/Language/AST/NodeList.php | 14 ++- src/Language/DirectiveLocation.php | 1 + src/Language/Lexer.php | 112 +++++++++++--------- src/Language/Parser.php | 79 +++++++++++++- src/Language/Printer.php | 38 +++---- src/Language/Source.php | 3 +- src/Language/SourceLocation.php | 4 +- src/Language/Token.php | 1 - src/Language/Visitor.php | 34 +++--- 12 files changed, 197 insertions(+), 94 deletions(-) diff --git a/src/Language/AST/EnumTypeDefinitionNode.php b/src/Language/AST/EnumTypeDefinitionNode.php index f21ae83..4ecd8fd 100644 --- a/src/Language/AST/EnumTypeDefinitionNode.php +++ b/src/Language/AST/EnumTypeDefinitionNode.php @@ -15,7 +15,7 @@ class EnumTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var DirectiveNode[] */ public $directives; - /** @var EnumValueDefinitionNode[]|null|NodeList */ + /** @var EnumValueDefinitionNode[]|NodeList|null */ public $values; /** @var StringValueNode|null */ diff --git a/src/Language/AST/Location.php b/src/Language/AST/Location.php index 9eb7e1c..7ea05ad 100644 --- a/src/Language/AST/Location.php +++ b/src/Language/AST/Location.php @@ -51,6 +51,7 @@ class Location /** * @param int $start * @param int $end + * * @return static */ public static function create($start, $end) diff --git a/src/Language/AST/Node.php b/src/Language/AST/Node.php index c61d149..826478b 100644 --- a/src/Language/AST/Node.php +++ b/src/Language/AST/Node.php @@ -61,6 +61,7 @@ abstract class Node /** * @param string|NodeList|Location|Node|(Node|NodeList|Location)[] $value + * * @return string|NodeList|Location|Node */ private function cloneValue($value) @@ -94,6 +95,7 @@ abstract class Node /** * @param bool $recursive + * * @return mixed[] */ public function toArray($recursive = false) diff --git a/src/Language/AST/NodeList.php b/src/Language/AST/NodeList.php index 5028022..2e7de79 100644 --- a/src/Language/AST/NodeList.php +++ b/src/Language/AST/NodeList.php @@ -4,19 +4,24 @@ declare(strict_types=1); namespace GraphQL\Language\AST; +use ArrayAccess; +use Countable; +use Generator; use GraphQL\Utils\AST; +use IteratorAggregate; use function array_merge; use function array_splice; use function count; use function is_array; -class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable +class NodeList implements ArrayAccess, IteratorAggregate, Countable { /** @var Node[]|mixed[] */ private $nodes; /** * @param Node[]|mixed[] $nodes + * * @return static */ public static function create(array $nodes) @@ -25,7 +30,6 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable } /** - * * @param Node[]|mixed[] $nodes */ public function __construct(array $nodes) @@ -35,6 +39,7 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable /** * @param mixed $offset + * * @return bool */ public function offsetExists($offset) @@ -44,6 +49,7 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable /** * @param mixed $offset + * * @return mixed */ public function offsetGet($offset) @@ -81,6 +87,7 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable * @param int $offset * @param int $length * @param mixed $replacement + * * @return NodeList */ public function splice($offset, $length, $replacement = null) @@ -90,6 +97,7 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable /** * @param NodeList|Node[] $list + * * @return NodeList */ public function merge($list) @@ -101,7 +109,7 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable } /** - * @return \Generator + * @return Generator */ public function getIterator() { diff --git a/src/Language/DirectiveLocation.php b/src/Language/DirectiveLocation.php index 77a0caf..5f22537 100644 --- a/src/Language/DirectiveLocation.php +++ b/src/Language/DirectiveLocation.php @@ -55,6 +55,7 @@ class DirectiveLocation /** * @param string $name + * * @return bool */ public static function has($name) diff --git a/src/Language/Lexer.php b/src/Language/Lexer.php index 223b6f8..d3b80ac 100644 --- a/src/Language/Lexer.php +++ b/src/Language/Lexer.php @@ -92,10 +92,8 @@ class Lexer */ public function advance() { - $this->lastToken = $this->token; - $token = $this->token = $this->lookahead(); - - return $token; + $this->lastToken = $this->token; + return $this->token = $this->lookahead(); } public function lookahead() @@ -112,6 +110,7 @@ class Lexer /** * @return Token + * * @throws SyntaxError */ private function readToken(Token $prev) @@ -129,7 +128,7 @@ class Lexer } // Read next char and advance string cursor: - list (, $code, $bytes) = $this->readChar(true); + [, $code, $bytes] = $this->readChar(true); // SourceCharacter if ($code < 0x0020 && $code !== 0x0009 && $code !== 0x000A && $code !== 0x000D) { @@ -156,8 +155,8 @@ class Lexer case 41: // ) return new Token(Token::PAREN_R, $position, $position + 1, $line, $col, $prev); case 46: // . - list (, $charCode1) = $this->readChar(true); - list (, $charCode2) = $this->readChar(true); + [, $charCode1] = $this->readChar(true); + [, $charCode2] = $this->readChar(true); if ($charCode1 === 46 && $charCode2 === 46) { return new Token(Token::SPREAD, $position, $position + 3, $line, $col, $prev); @@ -254,8 +253,8 @@ class Lexer ->readNumber($line, $col, $prev); // " case 34: - list(, $nextCode) = $this->readChar(); - list(, $nextNextCode) = $this->moveStringCursor(1, 1)->readChar(); + [, $nextCode] = $this->readChar(); + [, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar(); if ($nextCode === 34 && $nextNextCode === 34) { return $this->moveStringCursor(-2, (-1 * $bytes) - 1) @@ -284,13 +283,14 @@ class Lexer * * @param int $line * @param int $col + * * @return Token */ private function readName($line, $col, Token $prev) { - $value = ''; - $start = $this->position; - list ($char, $code) = $this->readChar(); + $value = ''; + $start = $this->position; + [$char, $code] = $this->readChar(); while ($code && ( $code === 95 || // _ @@ -298,8 +298,8 @@ class Lexer $code >= 65 && $code <= 90 || // A-Z $code >= 97 && $code <= 122 // a-z )) { - $value .= $char; - list ($char, $code) = $this->moveStringCursor(1, 1)->readChar(); + $value .= $char; + [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } return new Token( @@ -322,26 +322,28 @@ class Lexer * * @param int $line * @param int $col + * * @return Token + * * @throws SyntaxError */ private function readNumber($line, $col, Token $prev) { - $value = ''; - $start = $this->position; - list ($char, $code) = $this->readChar(); + $value = ''; + $start = $this->position; + [$char, $code] = $this->readChar(); $isFloat = false; if ($code === 45) { // - - $value .= $char; - list ($char, $code) = $this->moveStringCursor(1, 1)->readChar(); + $value .= $char; + [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } // guard against leading zero's if ($code === 48) { // 0 - $value .= $char; - list ($char, $code) = $this->moveStringCursor(1, 1)->readChar(); + $value .= $char; + [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); if ($code >= 48 && $code <= 57) { throw new SyntaxError( @@ -351,23 +353,23 @@ class Lexer ); } } else { - $value .= $this->readDigits(); - list ($char, $code) = $this->readChar(); + $value .= $this->readDigits(); + [$char, $code] = $this->readChar(); } if ($code === 46) { // . $isFloat = true; $this->moveStringCursor(1, 1); - $value .= $char; - $value .= $this->readDigits(); - list ($char, $code) = $this->readChar(); + $value .= $char; + $value .= $this->readDigits(); + [$char, $code] = $this->readChar(); } if ($code === 69 || $code === 101) { // E e - $isFloat = true; - $value .= $char; - list ($char, $code) = $this->moveStringCursor(1, 1)->readChar(); + $isFloat = true; + $value .= $char; + [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); if ($code === 43 || $code === 45) { // + - $value .= $char; @@ -392,14 +394,14 @@ class Lexer */ private function readDigits() { - list ($char, $code) = $this->readChar(); + [$char, $code] = $this->readChar(); if ($code >= 48 && $code <= 57) { // 0 - 9 $value = ''; do { - $value .= $char; - list ($char, $code) = $this->moveStringCursor(1, 1)->readChar(); + $value .= $char; + [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } while ($code >= 48 && $code <= 57); // 0 - 9 return $value; @@ -419,7 +421,9 @@ class Lexer /** * @param int $line * @param int $col + * * @return Token + * * @throws SyntaxError */ private function readString($line, $col, Token $prev) @@ -458,8 +462,8 @@ class Lexer $this->moveStringCursor(1, $bytes); if ($code === 92) { // \ - $value .= $chunk; - list (, $code) = $this->readChar(true); + $value .= $chunk; + [, $code] = $this->readChar(true); switch ($code) { case 34: @@ -487,8 +491,8 @@ class Lexer $value .= "\t"; break; case 117: - $position = $this->position; - list ($hex) = $this->readChars(4, true); + $position = $this->position; + [$hex] = $this->readChars(4, true); if (! preg_match('/[0-9a-fA-F]{4}/', $hex)) { throw new SyntaxError( $this->source, @@ -512,7 +516,7 @@ class Lexer $chunk .= $char; } - list ($char, $code, $bytes) = $this->readChar(); + [$char, $code, $bytes] = $this->readChar(); } throw new SyntaxError( @@ -532,7 +536,7 @@ class Lexer $start = $this->position; // Skip leading quotes and read first string char: - list ($char, $code, $bytes) = $this->moveStringCursor(3, 3)->readChar(); + [$char, $code, $bytes] = $this->moveStringCursor(3, 3)->readChar(); $chunk = ''; $value = ''; @@ -541,8 +545,8 @@ class Lexer // Closing Triple-Quote (""") if ($code === 34) { // Move 2 quotes - list(, $nextCode) = $this->moveStringCursor(1, 1)->readChar(); - list(, $nextNextCode) = $this->moveStringCursor(1, 1)->readChar(); + [, $nextCode] = $this->moveStringCursor(1, 1)->readChar(); + [, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar(); if ($nextCode === 34 && $nextNextCode === 34) { $value .= $chunk; @@ -567,9 +571,9 @@ class Lexer $this->assertValidBlockStringCharacterCode($code, $this->position); $this->moveStringCursor(1, $bytes); - list(, $nextCode) = $this->readChar(); - list(, $nextNextCode) = $this->moveStringCursor(1, 1)->readChar(); - list(, $nextNextNextCode) = $this->moveStringCursor(1, 1)->readChar(); + [, $nextCode] = $this->readChar(); + [, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar(); + [, $nextNextNextCode] = $this->moveStringCursor(1, 1)->readChar(); // Escape Triple-Quote (\""") if ($code === 92 && @@ -585,7 +589,7 @@ class Lexer $chunk .= $char; } - list ($char, $code, $bytes) = $this->readChar(); + [$char, $code, $bytes] = $this->readChar(); } throw new SyntaxError( @@ -626,7 +630,7 @@ class Lexer private function positionAfterWhitespace() { while ($this->position < $this->source->length) { - list(, $code, $bytes) = $this->readChar(); + [, $code, $bytes] = $this->readChar(); // Skip whitespace // tab | space | comma | BOM @@ -637,7 +641,7 @@ class Lexer $this->line++; $this->lineStart = $this->position; } elseif ($code === 13) { // carriage return - list(, $nextCode, $nextBytes) = $this->moveStringCursor(1, $bytes)->readChar(); + [, $nextCode, $nextBytes] = $this->moveStringCursor(1, $bytes)->readChar(); if ($nextCode === 10) { // lf after cr $this->moveStringCursor(1, $nextBytes); @@ -657,6 +661,7 @@ class Lexer * * @param int $line * @param int $col + * * @return Token */ private function readComment($line, $col, Token $prev) @@ -666,8 +671,8 @@ class Lexer $bytes = 1; do { - list ($char, $code, $bytes) = $this->moveStringCursor(1, $bytes)->readChar(); - $value .= $char; + [$char, $code, $bytes] = $this->moveStringCursor(1, $bytes)->readChar(); + $value .= $char; } while ($code && // SourceCharacter but not LineTerminator ($code > 0x001F || $code === 0x0009) @@ -689,6 +694,7 @@ class Lexer * * @param bool $advance * @param int $byteStreamPosition + * * @return (string|int)[] */ private function readChar($advance = false, $byteStreamPosition = null) @@ -736,6 +742,7 @@ class Lexer * @param int $charCount * @param bool $advance * @param null $byteStreamPosition + * * @return (string|int)[] */ private function readChars($charCount, $advance = false, $byteStreamPosition = null) @@ -745,10 +752,10 @@ class Lexer $byteOffset = $byteStreamPosition ?: $this->byteStreamPosition; for ($i = 0; $i < $charCount; $i++) { - list ($char, $code, $bytes) = $this->readChar(false, $byteOffset); - $totalBytes += $bytes; - $byteOffset += $bytes; - $result .= $char; + [$char, $code, $bytes] = $this->readChar(false, $byteOffset); + $totalBytes += $bytes; + $byteOffset += $bytes; + $result .= $char; } if ($advance) { $this->moveStringCursor($charCount, $totalBytes); @@ -762,6 +769,7 @@ class Lexer * * @param int $positionOffset * @param int $byteStreamOffset + * * @return self */ private function moveStringCursor($positionOffset, $byteStreamOffset) diff --git a/src/Language/Parser.php b/src/Language/Parser.php index 9471981..10f0859 100644 --- a/src/Language/Parser.php +++ b/src/Language/Parser.php @@ -102,11 +102,14 @@ class Parser * Note: this feature is experimental and may change or be removed in the * future.) * - * @api * @param Source|string $source * @param bool[] $options + * * @return DocumentNode + * * @throws SyntaxError + * + * @api */ public static function parse($source, array $options = []) { @@ -126,10 +129,12 @@ class Parser * * Consider providing the results to the utility function: `GraphQL\Utils\AST::valueFromAST()`. * - * @api * @param Source|string $source * @param bool[] $options + * * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode + * + * @api */ public static function parseValue($source, array $options = []) { @@ -152,10 +157,12 @@ class Parser * * Consider providing the results to the utility function: `GraphQL\Utils\AST::typeFromAST()`. * - * @api * @param Source|string $source * @param bool[] $options + * * @return ListTypeNode|NameNode|NonNullTypeNode + * + * @api */ public static function parseType($source, array $options = []) { @@ -172,7 +179,6 @@ class Parser private $lexer; /** - * * @param bool[] $options */ public function __construct(Source $source, array $options = []) @@ -199,6 +205,7 @@ class Parser * Determines if the next token is of a given kind * * @param string $kind + * * @return bool */ private function peek($kind) @@ -211,6 +218,7 @@ class Parser * the parser. Otherwise, do not change the parser state and return false. * * @param string $kind + * * @return bool */ private function skip($kind) @@ -227,8 +235,11 @@ class Parser /** * If the next token is of the given kind, return that token after advancing * the parser. Otherwise, do not change the parser state and return false. + * * @param string $kind + * * @return Token + * * @throws SyntaxError */ private function expect($kind) @@ -254,7 +265,9 @@ class Parser * false. * * @param string $value + * * @return Token + * * @throws SyntaxError */ private function expectKeyword($value) @@ -292,7 +305,9 @@ class Parser * @param string $openKind * @param callable $parseFn * @param string $closeKind + * * @return NodeList + * * @throws SyntaxError */ private function any($openKind, $parseFn, $closeKind) @@ -316,7 +331,9 @@ class Parser * @param string $openKind * @param callable $parseFn * @param string $closeKind + * * @return NodeList + * * @throws SyntaxError */ private function many($openKind, $parseFn, $closeKind) @@ -335,6 +352,7 @@ class Parser * Converts a name lex token into a name parse node. * * @return NameNode + * * @throws SyntaxError */ private function parseName() @@ -351,6 +369,7 @@ class Parser * Implements the parsing rules in the Document section. * * @return DocumentNode + * * @throws SyntaxError */ private function parseDocument() @@ -371,6 +390,7 @@ class Parser /** * @return ExecutableDefinitionNode|TypeSystemDefinitionNode + * * @throws SyntaxError */ private function parseDefinition() @@ -408,6 +428,7 @@ class Parser /** * @return ExecutableDefinitionNode + * * @throws SyntaxError */ private function parseExecutableDefinition() @@ -433,6 +454,7 @@ class Parser /** * @return OperationDefinitionNode + * * @throws SyntaxError */ private function parseOperationDefinition() @@ -468,6 +490,7 @@ class Parser /** * @return string + * * @throws SyntaxError */ private function parseOperationType() @@ -503,6 +526,7 @@ class Parser /** * @return VariableDefinitionNode + * * @throws SyntaxError */ private function parseVariableDefinition() @@ -524,6 +548,7 @@ class Parser /** * @return VariableNode + * * @throws SyntaxError */ private function parseVariable() @@ -575,6 +600,7 @@ class Parser /** * @return FieldNode + * * @throws SyntaxError */ private function parseField() @@ -602,7 +628,9 @@ class Parser /** * @param bool $isConst + * * @return ArgumentNode[]|NodeList + * * @throws SyntaxError */ private function parseArguments($isConst) @@ -622,6 +650,7 @@ class Parser /** * @return ArgumentNode + * * @throws SyntaxError */ private function parseArgument() @@ -641,6 +670,7 @@ class Parser /** * @return ArgumentNode + * * @throws SyntaxError */ private function parseConstArgument() @@ -662,6 +692,7 @@ class Parser /** * @return FragmentSpreadNode|InlineFragmentNode + * * @throws SyntaxError */ private function parseFragment() @@ -693,6 +724,7 @@ class Parser /** * @return FragmentDefinitionNode + * * @throws SyntaxError */ private function parseFragmentDefinition() @@ -724,6 +756,7 @@ class Parser /** * @return NameNode + * * @throws SyntaxError */ private function parseFragmentName() @@ -756,7 +789,9 @@ class Parser * EnumValue : Name but not `true`, `false` or `null` * * @param bool $isConst + * * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode|VariableNode|ListValueNode|ObjectValueNode|NullValueNode + * * @throws SyntaxError */ private function parseValueLiteral($isConst) @@ -834,6 +869,7 @@ class Parser /** * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode|VariableNode + * * @throws SyntaxError */ private function parseConstValue() @@ -851,6 +887,7 @@ class Parser /** * @param bool $isConst + * * @return ListValueNode */ private function parseArray($isConst) @@ -872,6 +909,7 @@ class Parser /** * @param bool $isConst + * * @return ObjectValueNode */ private function parseObject($isConst) @@ -891,6 +929,7 @@ class Parser /** * @param bool $isConst + * * @return ObjectFieldNode */ private function parseObjectField($isConst) @@ -911,7 +950,9 @@ class Parser /** * @param bool $isConst + * * @return DirectiveNode[]|NodeList + * * @throws SyntaxError */ private function parseDirectives($isConst) @@ -926,7 +967,9 @@ class Parser /** * @param bool $isConst + * * @return DirectiveNode + * * @throws SyntaxError */ private function parseDirective($isConst) @@ -947,6 +990,7 @@ class Parser * Handles the Type: TypeName, ListType, and NonNullType parsing rules. * * @return ListTypeNode|NameNode|NonNullTypeNode + * * @throws SyntaxError */ private function parseTypeReference() @@ -1001,6 +1045,7 @@ class Parser * - InputObjectTypeDefinition * * @return TypeSystemDefinitionNode + * * @throws SyntaxError */ private function parseTypeSystemDefinition() @@ -1056,6 +1101,7 @@ class Parser /** * @return SchemaDefinitionNode + * * @throws SyntaxError */ private function parseSchemaDefinition() @@ -1081,6 +1127,7 @@ class Parser /** * @return OperationTypeDefinitionNode + * * @throws SyntaxError */ private function parseOperationTypeDefinition() @@ -1099,6 +1146,7 @@ class Parser /** * @return ScalarTypeDefinitionNode + * * @throws SyntaxError */ private function parseScalarTypeDefinition() @@ -1119,6 +1167,7 @@ class Parser /** * @return ObjectTypeDefinitionNode + * * @throws SyntaxError */ private function parseObjectTypeDefinition() @@ -1168,6 +1217,7 @@ class Parser /** * @return FieldDefinitionNode[]|NodeList + * * @throws SyntaxError */ private function parseFieldsDefinition() @@ -1196,6 +1246,7 @@ class Parser /** * @return FieldDefinitionNode + * * @throws SyntaxError */ private function parseFieldDefinition() @@ -1220,6 +1271,7 @@ class Parser /** * @return InputValueDefinitionNode[]|NodeList + * * @throws SyntaxError */ private function parseArgumentDefs() @@ -1239,6 +1291,7 @@ class Parser /** * @return InputValueDefinitionNode + * * @throws SyntaxError */ private function parseInputValueDef() @@ -1266,6 +1319,7 @@ class Parser /** * @return InterfaceTypeDefinitionNode + * * @throws SyntaxError */ private function parseInterfaceTypeDefinition() @@ -1291,6 +1345,7 @@ class Parser * - Description? union Name Directives[Const]? UnionMemberTypes? * * @return UnionTypeDefinitionNode + * * @throws SyntaxError */ private function parseUnionTypeDefinition() @@ -1334,6 +1389,7 @@ class Parser /** * @return EnumTypeDefinitionNode + * * @throws SyntaxError */ private function parseEnumTypeDefinition() @@ -1356,6 +1412,7 @@ class Parser /** * @return EnumValueDefinitionNode[]|NodeList + * * @throws SyntaxError */ private function parseEnumValuesDefinition() @@ -1373,6 +1430,7 @@ class Parser /** * @return EnumValueDefinitionNode + * * @throws SyntaxError */ private function parseEnumValueDefinition() @@ -1392,6 +1450,7 @@ class Parser /** * @return InputObjectTypeDefinitionNode + * * @throws SyntaxError */ private function parseInputObjectTypeDefinition() @@ -1414,6 +1473,7 @@ class Parser /** * @return InputValueDefinitionNode[]|NodeList + * * @throws SyntaxError */ private function parseInputFieldsDefinition() @@ -1439,6 +1499,7 @@ class Parser * - InputObjectTypeDefinition * * @return TypeExtensionNode + * * @throws SyntaxError */ private function parseTypeExtension() @@ -1469,6 +1530,7 @@ class Parser /** * @return SchemaTypeExtensionNode + * * @throws SyntaxError */ private function parseSchemaTypeExtension() @@ -1496,6 +1558,7 @@ class Parser /** * @return ScalarTypeExtensionNode + * * @throws SyntaxError */ private function parseScalarTypeExtension() @@ -1518,6 +1581,7 @@ class Parser /** * @return ObjectTypeExtensionNode + * * @throws SyntaxError */ private function parseObjectTypeExtension() @@ -1548,6 +1612,7 @@ class Parser /** * @return InterfaceTypeExtensionNode + * * @throws SyntaxError */ private function parseInterfaceTypeExtension() @@ -1578,6 +1643,7 @@ class Parser * - extend union Name Directives[Const] * * @return UnionTypeExtensionNode + * * @throws SyntaxError */ private function parseUnionTypeExtension() @@ -1604,6 +1670,7 @@ class Parser /** * @return EnumTypeExtensionNode + * * @throws SyntaxError */ private function parseEnumTypeExtension() @@ -1630,6 +1697,7 @@ class Parser /** * @return InputObjectTypeExtensionNode + * * @throws SyntaxError */ private function parseInputObjectTypeExtension() @@ -1659,6 +1727,7 @@ class Parser * - directive @ Name ArgumentsDefinition? on DirectiveLocations * * @return DirectiveDefinitionNode + * * @throws SyntaxError */ private function parseDirectiveDefinition() @@ -1683,6 +1752,7 @@ class Parser /** * @return NameNode[] + * * @throws SyntaxError */ private function parseDirectiveLocations() @@ -1699,6 +1769,7 @@ class Parser /** * @return NameNode + * * @throws SyntaxError */ private function parseDirectiveLocation() diff --git a/src/Language/Printer.php b/src/Language/Printer.php index f3148ed..891f411 100644 --- a/src/Language/Printer.php +++ b/src/Language/Printer.php @@ -73,9 +73,11 @@ class Printer /** * Prints AST to string. Capable of printing GraphQL queries and Type definition language. * - * @api * @param Node $ast + * * @return string + * + * @api */ public static function doPrint($ast) { @@ -95,11 +97,11 @@ class Printer $ast, [ 'leave' => [ - NodeKind::NAME => function (Node $node) { + NodeKind::NAME => static function (Node $node) { return '' . $node->value; }, - NodeKind::VARIABLE => function ($node) { + NodeKind::VARIABLE => static function ($node) { return '$' . $node->name; }, @@ -143,7 +145,7 @@ class Printer ); }, - NodeKind::ARGUMENT => function (ArgumentNode $node) { + NodeKind::ARGUMENT => static function (ArgumentNode $node) { return $node->name . ': ' . $node->value; }, @@ -172,11 +174,11 @@ class Printer . $node->selectionSet; }, - NodeKind::INT => function (IntValueNode $node) { + NodeKind::INT => static function (IntValueNode $node) { return $node->value; }, - NodeKind::FLOAT => function (FloatValueNode $node) { + NodeKind::FLOAT => static function (FloatValueNode $node) { return $node->value; }, @@ -188,15 +190,15 @@ class Printer return json_encode($node->value); }, - NodeKind::BOOLEAN => function (BooleanValueNode $node) { + NodeKind::BOOLEAN => static function (BooleanValueNode $node) { return $node->value ? 'true' : 'false'; }, - NodeKind::NULL => function (NullValueNode $node) { + NodeKind::NULL => static function (NullValueNode $node) { return 'null'; }, - NodeKind::ENUM => function (EnumValueNode $node) { + NodeKind::ENUM => static function (EnumValueNode $node) { return $node->value; }, @@ -208,7 +210,7 @@ class Printer return '{' . $this->join($node->fields, ', ') . '}'; }, - NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) { + NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) { return $node->name . ': ' . $node->value; }, @@ -216,15 +218,15 @@ class Printer return '@' . $node->name . $this->wrap('(', $this->join($node->arguments, ', '), ')'); }, - NodeKind::NAMED_TYPE => function (NamedTypeNode $node) { + NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) { return $node->name; }, - NodeKind::LIST_TYPE => function (ListTypeNode $node) { + NodeKind::LIST_TYPE => static function (ListTypeNode $node) { return '[' . $node->type . ']'; }, - NodeKind::NON_NULL_TYPE => function (NonNullTypeNode $node) { + NodeKind::NON_NULL_TYPE => static function (NonNullTypeNode $node) { return $node->type . '!'; }, @@ -239,7 +241,7 @@ class Printer ); }, - NodeKind::OPERATION_TYPE_DEFINITION => function (OperationTypeDefinitionNode $def) { + NodeKind::OPERATION_TYPE_DEFINITION => static function (OperationTypeDefinitionNode $def) { return $def->operation . ': ' . $def->type; }, @@ -432,7 +434,7 @@ class Printer ); } - public function addDescription(\Closure $cb) + public function addDescription(callable $cb) { return function ($node) use ($cb) { return $this->join([$node->description, $cb($node)], "\n"); @@ -454,7 +456,7 @@ class Printer */ public function block($array) { - return ($array && $this->length($array)) + return $array && $this->length($array) ? "{\n" . $this->indent($this->join($array, "\n")) . "\n}" : ''; } @@ -481,7 +483,7 @@ class Printer $separator, Utils::filter( $maybeArray, - function ($x) { + static function ($x) { return (bool) $x; } ) @@ -498,7 +500,7 @@ class Printer { $escaped = str_replace('"""', '\\"""', $value); - return (($value[0] === ' ' || $value[0] === "\t") && strpos($value, "\n") === false) + return ($value[0] === ' ' || $value[0] === "\t") && strpos($value, "\n") === false ? ('"""' . preg_replace('/"$/', "\"\n", $escaped) . '"""') : ('"""' . "\n" . ($isDescription ? $escaped : $this->indent($escaped)) . "\n" . '"""'); } diff --git a/src/Language/Source.php b/src/Language/Source.php index 1beb8bc..7e94030 100644 --- a/src/Language/Source.php +++ b/src/Language/Source.php @@ -27,8 +27,6 @@ class Source public $locationOffset; /** - * - * * A representation of source input to GraphQL. * `name` and `locationOffset` are optional. They are useful for clients who * store GraphQL documents in source files; for example, if the GraphQL input @@ -63,6 +61,7 @@ class Source /** * @param int $position + * * @return SourceLocation */ public function getLocation($position) diff --git a/src/Language/SourceLocation.php b/src/Language/SourceLocation.php index 2c406ca..8877f84 100644 --- a/src/Language/SourceLocation.php +++ b/src/Language/SourceLocation.php @@ -4,7 +4,9 @@ declare(strict_types=1); namespace GraphQL\Language; -class SourceLocation implements \JsonSerializable +use JsonSerializable; + +class SourceLocation implements JsonSerializable { /** @var int */ public $line; diff --git a/src/Language/Token.php b/src/Language/Token.php index a1c966c..831b3ad 100644 --- a/src/Language/Token.php +++ b/src/Language/Token.php @@ -85,7 +85,6 @@ class Token public $next; /** - * * @param string $kind * @param int $start * @param int $end diff --git a/src/Language/Visitor.php b/src/Language/Visitor.php index 1a27f5a..e652d66 100644 --- a/src/Language/Visitor.php +++ b/src/Language/Visitor.php @@ -5,10 +5,12 @@ declare(strict_types=1); namespace GraphQL\Language; use ArrayObject; +use Exception; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\NodeList; use GraphQL\Utils\TypeInfo; +use SplFixedArray; use stdClass; use function array_pop; use function array_splice; @@ -172,12 +174,15 @@ class Visitor /** * Visit the AST (see class description for details) * - * @api * @param Node|ArrayObject|stdClass $root * @param callable[] $visitor * @param mixed[]|null $keyMap + * * @return Node|mixed - * @throws \Exception + * + * @throws Exception + * + * @api */ public static function visit($root, $visitor, $keyMap = null) { @@ -247,7 +252,7 @@ class Visitor $stack = $stack['prev']; } else { $key = $parent ? ($inArray ? $index : $keys[$index]) : $UNDEFINED; - $node = $parent ? (($parent instanceof NodeList || is_array($parent)) ? $parent[$key] : $parent->{$key}) : $newRoot; + $node = $parent ? ($parent instanceof NodeList || is_array($parent) ? $parent[$key] : $parent->{$key}) : $newRoot; if ($node === null || $node === $UNDEFINED) { continue; } @@ -259,7 +264,7 @@ class Visitor $result = null; if (! $node instanceof NodeList && ! is_array($node)) { if (! ($node instanceof Node)) { - throw new \Exception('Invalid AST Node: ' . json_encode($node)); + throw new Exception('Invalid AST Node: ' . json_encode($node)); } $visitFn = self::getVisitFn($visitor, $node->kind, $isLeaving); @@ -333,8 +338,9 @@ class Visitor /** * Returns marker for visitor break * - * @api * @return VisitorOperation + * + * @api */ public static function stop() { @@ -347,8 +353,9 @@ class Visitor /** * Returns marker for skipping current node * - * @api * @return VisitorOperation + * + * @api */ public static function skipNode() { @@ -361,8 +368,9 @@ class Visitor /** * Returns marker for removing a node * - * @api * @return VisitorOperation + * + * @api */ public static function removeNode() { @@ -374,15 +382,16 @@ class Visitor /** * @param callable[][] $visitors + * * @return callable[][] */ public static function visitInParallel($visitors) { $visitorsCount = count($visitors); - $skipping = new \SplFixedArray($visitorsCount); + $skipping = new SplFixedArray($visitorsCount); return [ - 'enter' => function (Node $node) use ($visitors, $skipping, $visitorsCount) { + 'enter' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) { for ($i = 0; $i < $visitorsCount; $i++) { if (! empty($skipping[$i])) { continue; @@ -413,7 +422,7 @@ class Visitor } } }, - 'leave' => function (Node $node) use ($visitors, $skipping, $visitorsCount) { + 'leave' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) { for ($i = 0; $i < $visitorsCount; $i++) { if (empty($skipping[$i])) { $fn = self::getVisitFn( @@ -449,7 +458,7 @@ class Visitor public static function visitWithTypeInfo(TypeInfo $typeInfo, $visitor) { return [ - 'enter' => function (Node $node) use ($typeInfo, $visitor) { + 'enter' => static function (Node $node) use ($typeInfo, $visitor) { $typeInfo->enter($node); $fn = self::getVisitFn($visitor, $node->kind, false); @@ -467,7 +476,7 @@ class Visitor return null; }, - 'leave' => function (Node $node) use ($typeInfo, $visitor) { + 'leave' => static function (Node $node) use ($typeInfo, $visitor) { $fn = self::getVisitFn($visitor, $node->kind, true); $result = $fn ? call_user_func_array($fn, func_get_args()) : null; $typeInfo->leave($node); @@ -481,6 +490,7 @@ class Visitor * @param callable[]|null $visitor * @param string $kind * @param bool $isLeaving + * * @return callable|null */ public static function getVisitFn($visitor, $kind, $isLeaving) From 7ba98ce773a197c99d3e350fca0dac79a10ad903 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:35:23 +0200 Subject: [PATCH 07/10] Fix CS in src/Server --- src/Server/Helper.php | 54 +++++++++++++++++++++++----------- src/Server/OperationParams.php | 11 +++++-- src/Server/RequestError.php | 3 +- src/Server/ServerConfig.php | 50 +++++++++++++++++++++---------- src/Server/StandardServer.php | 29 +++++++++++------- 5 files changed, 100 insertions(+), 47 deletions(-) diff --git a/src/Server/Helper.php b/src/Server/Helper.php index 552f449..ff62b2b 100644 --- a/src/Server/Helper.php +++ b/src/Server/Helper.php @@ -17,6 +17,7 @@ use GraphQL\Language\AST\DocumentNode; use GraphQL\Language\Parser; use GraphQL\Utils\AST; use GraphQL\Utils\Utils; +use JsonSerializable; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; @@ -52,9 +53,11 @@ class Helper * * For PSR-7 request parsing use `parsePsrRequest()` instead. * - * @api * @return OperationParams|OperationParams[] + * * @throws RequestError + * + * @api */ public function parseHttpRequest(?callable $readRawBodyFn = null) { @@ -104,12 +107,15 @@ class Helper * * Returned value is a suitable input for `executeOperation` or `executeBatch` (if array) * - * @api * @param string $method * @param mixed[] $bodyParams * @param mixed[] $queryParams + * * @return OperationParams|OperationParams[] + * * @throws RequestError + * + * @api */ public function parseRequestParams($method, array $bodyParams, array $queryParams) { @@ -136,8 +142,9 @@ class Helper * Checks validity of OperationParams extracted from HTTP request and returns an array of errors * if params are invalid (or empty array when params are valid) * - * @api * @return Error[] + * + * @api */ public function validateOperationParams(OperationParams $params) { @@ -185,9 +192,9 @@ class Helper * Executes GraphQL operation with given server configuration and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * - * @api - * * @return ExecutionResult|Promise + * + * @api */ public function executeOperation(ServerConfig $config, OperationParams $op) { @@ -205,9 +212,11 @@ class Helper * Executes batched GraphQL operations with shared promise queue * (thus, effectively batching deferreds|promises of all queries at once) * - * @api * @param OperationParams[] $operations + * * @return ExecutionResult|ExecutionResult[]|Promise + * + * @api */ public function executeBatch(ServerConfig $config, array $operations) { @@ -230,6 +239,7 @@ class Helper /** * @param bool $isBatch + * * @return Promise */ private function promiseToExecuteOperation( @@ -252,7 +262,7 @@ class Helper if (! empty($errors)) { $errors = Utils::map( $errors, - function (RequestError $err) { + static function (RequestError $err) { return Error::createLocatedError($err, null, null); } ); @@ -294,7 +304,7 @@ class Helper ); } - $applyErrorHandling = function (ExecutionResult $result) use ($config) { + $applyErrorHandling = static function (ExecutionResult $result) use ($config) { if ($config->getErrorsHandler()) { $result->setErrorsHandler($config->getErrorsHandler()); } @@ -315,6 +325,7 @@ class Helper /** * @return mixed + * * @throws RequestError */ private function loadPersistedQuery(ServerConfig $config, OperationParams $operationParams) @@ -341,6 +352,7 @@ class Helper /** * @param string $operationType + * * @return mixed[]|null */ private function resolveValidationRules( @@ -368,13 +380,14 @@ class Helper /** * @param string $operationType + * * @return mixed */ private function resolveRootValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, $operationType) { $root = $config->getRootValue(); - if ($root instanceof \Closure) { + if (is_callable($root)) { $root = $root($params, $doc, $operationType); } @@ -383,6 +396,7 @@ class Helper /** * @param string $operationType + * * @return mixed */ private function resolveContextValue( @@ -393,7 +407,7 @@ class Helper ) { $context = $config->getContext(); - if ($context instanceof \Closure) { + if (is_callable($context)) { $context = $context($params, $doc, $operationType); } @@ -403,9 +417,10 @@ class Helper /** * Send response using standard PHP `header()` and `echo`. * - * @api * @param Promise|ExecutionResult|ExecutionResult[] $result * @param bool $exitWhenDone + * + * @api */ public function sendResponse($result, $exitWhenDone = false) { @@ -425,9 +440,9 @@ class Helper } /** - * @param mixed[]|\JsonSerializable $jsonSerializable - * @param int $httpStatus - * @param bool $exitWhenDone + * @param mixed[]|JsonSerializable $jsonSerializable + * @param int $httpStatus + * @param bool $exitWhenDone */ public function emitResponse($jsonSerializable, $httpStatus, $exitWhenDone) { @@ -450,6 +465,7 @@ class Helper /** * @param ExecutionResult|mixed[] $result + * * @return int */ private function resolveHttpStatus($result) @@ -457,7 +473,7 @@ class Helper if (is_array($result) && isset($result[0])) { Utils::each( $result, - function ($executionResult, $index) { + static function ($executionResult, $index) { if (! $executionResult instanceof ExecutionResult) { throw new InvariantViolation(sprintf( 'Expecting every entry of batched query result to be instance of %s but entry at position %d is %s', @@ -490,9 +506,11 @@ class Helper /** * Converts PSR-7 request to OperationParams[] * - * @api * @return OperationParams[]|OperationParams + * * @throws RequestError + * + * @api */ public function parsePsrRequest(ServerRequestInterface $request) { @@ -541,9 +559,11 @@ class Helper /** * Converts query execution result to PSR-7 response * - * @api * @param Promise|ExecutionResult|ExecutionResult[] $result + * * @return Promise|ResponseInterface + * + * @api */ public function toPsrResponse($result, ResponseInterface $response, StreamInterface $writableBodyStream) { diff --git a/src/Server/OperationParams.php b/src/Server/OperationParams.php index b951808..8085d1e 100644 --- a/src/Server/OperationParams.php +++ b/src/Server/OperationParams.php @@ -55,10 +55,12 @@ class OperationParams /** * Creates an instance from given array * - * @api * @param mixed[] $params * @param bool $readonly + * * @return OperationParams + * + * @api */ public static function create(array $params, $readonly = false) { @@ -97,9 +99,11 @@ class OperationParams } /** - * @api * @param string $key + * * @return mixed + * + * @api */ public function getOriginalInput($key) { @@ -110,8 +114,9 @@ class OperationParams * Indicates that operation is executed in read-only context * (e.g. via HTTP GET request) * - * @api * @return bool + * + * @api */ public function isReadOnly() { diff --git a/src/Server/RequestError.php b/src/Server/RequestError.php index cde74f4..320aad4 100644 --- a/src/Server/RequestError.php +++ b/src/Server/RequestError.php @@ -4,9 +4,10 @@ declare(strict_types=1); namespace GraphQL\Server; +use Exception; use GraphQL\Error\ClientAware; -class RequestError extends \Exception implements ClientAware +class RequestError extends Exception implements ClientAware { /** * Returns true when exception message is safe to be displayed to client diff --git a/src/Server/ServerConfig.php b/src/Server/ServerConfig.php index 73364bd..d121ec5 100644 --- a/src/Server/ServerConfig.php +++ b/src/Server/ServerConfig.php @@ -34,9 +34,11 @@ class ServerConfig * Converts an array of options to instance of ServerConfig * (or just returns empty config when array is not passed). * - * @api * @param mixed[] $config + * * @return ServerConfig + * + * @api */ public static function create(array $config = []) { @@ -55,10 +57,10 @@ class ServerConfig /** @var Schema */ private $schema; - /** @var mixed|\Closure */ + /** @var mixed|callable */ private $context; - /** @var mixed|\Closure */ + /** @var mixed|callable */ private $rootValue; /** @var callable|null */ @@ -86,8 +88,9 @@ class ServerConfig private $persistentQueryLoader; /** - * @api * @return self + * + * @api */ public function setSchema(Schema $schema) { @@ -97,9 +100,11 @@ class ServerConfig } /** - * @api - * @param mixed|\Closure $context + * @param mixed|callable $context + * * @return self + * + * @api */ public function setContext($context) { @@ -109,9 +114,11 @@ class ServerConfig } /** - * @api - * @param mixed|\Closure $rootValue + * @param mixed|callable $rootValue + * * @return self + * + * @api */ public function setRootValue($rootValue) { @@ -123,8 +130,9 @@ class ServerConfig /** * Expects function(Throwable $e) : array * - * @api * @return self + * + * @api */ public function setErrorFormatter(callable $errorFormatter) { @@ -136,8 +144,9 @@ class ServerConfig /** * Expects function(array $errors, callable $formatter) : array * - * @api * @return self + * + * @api */ public function setErrorsHandler(callable $handler) { @@ -149,9 +158,11 @@ class ServerConfig /** * Set validation rules for this server. * - * @api * @param ValidationRule[]|callable $validationRules + * * @return self + * + * @api */ public function setValidationRules($validationRules) { @@ -168,8 +179,9 @@ class ServerConfig } /** - * @api * @return self + * + * @api */ public function setFieldResolver(callable $fieldResolver) { @@ -183,8 +195,9 @@ class ServerConfig * * This function must return query string or valid DocumentNode. * - * @api * @return self + * + * @api */ public function setPersistentQueryLoader(callable $persistentQueryLoader) { @@ -196,9 +209,11 @@ class ServerConfig /** * Set response debug flags. See GraphQL\Error\Debug class for a list of all available flags * - * @api * @param bool|int $set + * * @return self + * + * @api */ public function setDebug($set = true) { @@ -210,9 +225,11 @@ class ServerConfig /** * Allow batching queries (disabled by default) * - * @api * @param bool $enableBatching + * * @return self + * + * @api */ public function setQueryBatching($enableBatching) { @@ -222,8 +239,9 @@ class ServerConfig } /** - * @api * @return self + * + * @api */ public function setPromiseAdapter(PromiseAdapter $promiseAdapter) { diff --git a/src/Server/StandardServer.php b/src/Server/StandardServer.php index 92a8f3d..63bd140 100644 --- a/src/Server/StandardServer.php +++ b/src/Server/StandardServer.php @@ -12,6 +12,7 @@ use GraphQL\Utils\Utils; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; +use Throwable; use function is_array; /** @@ -34,7 +35,6 @@ use function is_array; * $server->handleRequest(); * * See [dedicated section in docs](executing-queries.md#using-server) for details. - * */ class StandardServer { @@ -49,10 +49,11 @@ class StandardServer * Useful when an exception is thrown somewhere outside of server execution context * (e.g. during schema instantiation). * + * @param Throwable $error + * @param bool $debug + * @param bool $exitWhenDone + * * @api - * @param \Throwable $error - * @param bool $debug - * @param bool $exitWhenDone */ public static function send500Error($error, $debug = false, $exitWhenDone = false) { @@ -66,8 +67,9 @@ class StandardServer /** * Creates new instance of a standard GraphQL HTTP server * - * @api * @param ServerConfig|mixed[] $config + * + * @api */ public function __construct($config) { @@ -91,9 +93,10 @@ class StandardServer * See `executeRequest()` if you prefer to emit response yourself * (e.g. using Response object of some framework) * - * @api * @param OperationParams|OperationParams[] $parsedBody * @param bool $exitWhenDone + * + * @api */ public function handleRequest($parsedBody = null, $exitWhenDone = false) { @@ -111,10 +114,13 @@ class StandardServer * * PSR-7 compatible method executePsrRequest() does exactly this. * - * @api * @param OperationParams|OperationParams[] $parsedBody + * * @return ExecutionResult|ExecutionResult[]|Promise + * * @throws InvariantViolation + * + * @api */ public function executeRequest($parsedBody = null) { @@ -135,8 +141,9 @@ class StandardServer * See `executePsrRequest()` if you prefer to create response yourself * (e.g. using specific JsonResponse instance of some framework). * - * @api * @return ResponseInterface|Promise + * + * @api */ public function processPsrRequest( ServerRequestInterface $request, @@ -151,8 +158,9 @@ class StandardServer * Executes GraphQL operation and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * - * @api * @return ExecutionResult|ExecutionResult[]|Promise + * + * @api */ public function executePsrRequest(ServerRequestInterface $request) { @@ -164,8 +172,9 @@ class StandardServer * Returns an instance of Server helper, which contains most of the actual logic for * parsing / validating / executing request (which could be re-used by other server implementations) * - * @api * @return Helper + * + * @api */ public function getHelper() { From 18a5639cb77545d1c0d6979f5a7979a4d60606a9 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:51:11 +0200 Subject: [PATCH 08/10] Fix CS in src/Type --- src/Type/Definition/AbstractType.php | 1 + src/Type/Definition/BooleanType.php | 10 +++- src/Type/Definition/CustomScalarType.php | 7 ++- src/Type/Definition/Directive.php | 1 - src/Type/Definition/EnumType.php | 15 ++++- src/Type/Definition/FieldArgument.php | 2 +- src/Type/Definition/FieldDefinition.php | 6 +- src/Type/Definition/FloatType.php | 11 +++- src/Type/Definition/IDType.php | 13 ++++- src/Type/Definition/InputObjectField.php | 1 - src/Type/Definition/InputObjectType.php | 6 +- src/Type/Definition/IntType.php | 12 +++- src/Type/Definition/InterfaceType.php | 4 +- src/Type/Definition/LeafType.php | 9 ++- src/Type/Definition/ListOfType.php | 3 +- src/Type/Definition/NonNull.php | 10 +++- src/Type/Definition/ObjectType.php | 11 +++- src/Type/Definition/ResolveInfo.php | 4 +- src/Type/Definition/StringType.php | 13 ++++- src/Type/Definition/Type.php | 71 +++++++++++++++++------- src/Type/Definition/UnionType.php | 1 + src/Type/Definition/WrappingType.php | 1 + src/Type/EagerResolution.php | 1 - src/Type/Introspection.php | 65 +++++++++++----------- src/Type/LazyResolution.php | 1 - src/Type/Resolution.php | 1 + src/Type/Schema.php | 49 +++++++++++----- src/Type/SchemaConfig.php | 47 +++++++++++----- src/Type/SchemaValidationContext.php | 17 +++++- 29 files changed, 277 insertions(+), 116 deletions(-) diff --git a/src/Type/Definition/AbstractType.php b/src/Type/Definition/AbstractType.php index f573610..356dceb 100644 --- a/src/Type/Definition/AbstractType.php +++ b/src/Type/Definition/AbstractType.php @@ -17,6 +17,7 @@ interface AbstractType * * @param object $objectValue * @param mixed[] $context + * * @return mixed */ public function resolveType($objectValue, $context, ResolveInfo $info); diff --git a/src/Type/Definition/BooleanType.php b/src/Type/Definition/BooleanType.php index c77fa3e..1c24a53 100644 --- a/src/Type/Definition/BooleanType.php +++ b/src/Type/Definition/BooleanType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\Node; @@ -23,6 +24,7 @@ class BooleanType extends ScalarType /** * @param mixed $value + * * @return bool */ public function serialize($value) @@ -32,7 +34,9 @@ class BooleanType extends ScalarType /** * @param mixed $value + * * @return bool + * * @throws Error */ public function parseValue($value) @@ -47,8 +51,10 @@ class BooleanType extends ScalarType /** * @param Node $valueNode * @param mixed[]|null $variables + * * @return bool|null - * @throws \Exception + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -57,6 +63,6 @@ class BooleanType extends ScalarType } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } } diff --git a/src/Type/Definition/CustomScalarType.php b/src/Type/Definition/CustomScalarType.php index 08fcea4..21766ab 100644 --- a/src/Type/Definition/CustomScalarType.php +++ b/src/Type/Definition/CustomScalarType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Language\AST\Node; use GraphQL\Utils\AST; use GraphQL\Utils\Utils; @@ -18,6 +19,7 @@ class CustomScalarType extends ScalarType { /** * @param mixed $value + * * @return mixed */ public function serialize($value) @@ -27,6 +29,7 @@ class CustomScalarType extends ScalarType /** * @param mixed $value + * * @return mixed */ public function parseValue($value) @@ -41,8 +44,10 @@ class CustomScalarType extends ScalarType /** * @param Node $valueNode * @param mixed[]|null $variables + * * @return mixed - * @throws \Exception + * + * @throws Exception */ public function parseLiteral(/* GraphQL\Language\AST\ValueNode */ $valueNode, diff --git a/src/Type/Definition/Directive.php b/src/Type/Definition/Directive.php index b572948..754d442 100644 --- a/src/Type/Definition/Directive.php +++ b/src/Type/Definition/Directive.php @@ -41,7 +41,6 @@ class Directive public $config; /** - * * @param mixed[] $config */ public function __construct(array $config) diff --git a/src/Type/Definition/EnumType.php b/src/Type/Definition/EnumType.php index 638a6ef..aa5c8b4 100644 --- a/src/Type/Definition/EnumType.php +++ b/src/Type/Definition/EnumType.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use ArrayObject; +use Exception; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\EnumTypeDefinitionNode; @@ -54,6 +56,7 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp /** * @param string|mixed[] $name + * * @return EnumValueDefinition|null */ public function getValue($name) @@ -73,7 +76,7 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp private function getNameLookup() { if (! $this->nameLookup) { - $lookup = new \ArrayObject(); + $lookup = new ArrayObject(); foreach ($this->getValues() as $value) { $lookup[$value->name] = $value; } @@ -123,7 +126,9 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp /** * @param mixed $value + * * @return mixed + * * @throws Error */ public function serialize($value) @@ -154,7 +159,9 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp /** * @param mixed $value + * * @return mixed + * * @throws Error */ public function parseValue($value) @@ -170,8 +177,10 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp /** * @param Node $valueNode * @param mixed[]|null $variables + * * @return null - * @throws \Exception + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -186,7 +195,7 @@ class EnumType extends Type implements InputType, OutputType, LeafType, NamedTyp } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } /** diff --git a/src/Type/Definition/FieldArgument.php b/src/Type/Definition/FieldArgument.php index 610a60e..33cad0d 100644 --- a/src/Type/Definition/FieldArgument.php +++ b/src/Type/Definition/FieldArgument.php @@ -38,7 +38,6 @@ class FieldArgument private $defaultValueExists = false; /** - * * @param mixed[] $def */ public function __construct(array $def) @@ -68,6 +67,7 @@ class FieldArgument /** * @param mixed[] $config + * * @return FieldArgument[] */ public static function createMap(array $config) diff --git a/src/Type/Definition/FieldDefinition.php b/src/Type/Definition/FieldDefinition.php index f8a1155..42ef1cc 100644 --- a/src/Type/Definition/FieldDefinition.php +++ b/src/Type/Definition/FieldDefinition.php @@ -65,7 +65,6 @@ class FieldDefinition private $complexityFn; /** - * * @param mixed[] $config */ protected function __construct(array $config) @@ -140,6 +139,7 @@ class FieldDefinition /** * @param mixed[] $field + * * @return FieldDefinition */ public static function create($field) @@ -149,6 +149,7 @@ class FieldDefinition /** * @param int $childrenComplexity + * * @return mixed */ public static function defaultComplexity($childrenComplexity) @@ -158,6 +159,7 @@ class FieldDefinition /** * @param string $name + * * @return FieldArgument|null */ public function getArg($name) @@ -189,7 +191,7 @@ class FieldDefinition } /** - * @return callable|\Closure + * @return callable|callable */ public function getComplexityFn() { diff --git a/src/Type/Definition/FloatType.php b/src/Type/Definition/FloatType.php index 12df7cb..0e6eba0 100644 --- a/src/Type/Definition/FloatType.php +++ b/src/Type/Definition/FloatType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\FloatValueNode; use GraphQL\Language\AST\IntValueNode; @@ -27,7 +28,9 @@ values as specified by /** * @param mixed $value + * * @return float|null + * * @throws Error */ public function serialize($value) @@ -55,7 +58,9 @@ values as specified by /** * @param mixed $value + * * @return float|null + * * @throws Error */ public function parseValue($value) @@ -66,8 +71,10 @@ values as specified by /** * @param Node $valueNode * @param mixed[]|null $variables + * * @return float|null - * @throws \Exception + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -76,6 +83,6 @@ values as specified by } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } } diff --git a/src/Type/Definition/IDType.php b/src/Type/Definition/IDType.php index 456f105..8077393 100644 --- a/src/Type/Definition/IDType.php +++ b/src/Type/Definition/IDType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\Node; @@ -30,7 +31,9 @@ When expected as an input type, any string (such as `"4"`) or integer /** * @param mixed $value + * * @return string + * * @throws Error */ public function serialize($value) @@ -53,7 +56,9 @@ When expected as an input type, any string (such as `"4"`) or integer /** * @param mixed $value + * * @return string + * * @throws Error */ public function parseValue($value) @@ -68,8 +73,10 @@ When expected as an input type, any string (such as `"4"`) or integer /** * @param Node $valueNode * @param mixed[]|null $variables - * @return null|string - * @throws \Exception + * + * @return string|null + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -78,6 +85,6 @@ When expected as an input type, any string (such as `"4"`) or integer } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } } diff --git a/src/Type/Definition/InputObjectField.php b/src/Type/Definition/InputObjectField.php index 5ceb3f4..6f01c94 100644 --- a/src/Type/Definition/InputObjectField.php +++ b/src/Type/Definition/InputObjectField.php @@ -38,7 +38,6 @@ class InputObjectField private $defaultValueExists = false; /** - * * @param mixed[] $opts */ public function __construct(array $opts) diff --git a/src/Type/Definition/InputObjectType.php b/src/Type/Definition/InputObjectType.php index 542a0d1..e43caad 100644 --- a/src/Type/Definition/InputObjectType.php +++ b/src/Type/Definition/InputObjectType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\InputObjectTypeDefinitionNode; use GraphQL\Language\AST\InputObjectTypeExtensionNode; @@ -29,7 +30,6 @@ class InputObjectType extends Type implements InputType, NamedType public $extensionASTNodes; /** - * * @param mixed[] $config */ public function __construct(array $config) @@ -49,8 +49,10 @@ class InputObjectType extends Type implements InputType, NamedType /** * @param string $name + * * @return InputObjectField - * @throws \Exception + * + * @throws Exception */ public function getField($name) { diff --git a/src/Type/Definition/IntType.php b/src/Type/Definition/IntType.php index 5b87643..1f59a92 100644 --- a/src/Type/Definition/IntType.php +++ b/src/Type/Definition/IntType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\Node; @@ -36,7 +37,9 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; /** * @param mixed $value + * * @return int|null + * * @throws Error */ public function serialize($value) @@ -46,6 +49,7 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; /** * @param mixed $value + * * @return int */ private function coerceInt($value) @@ -78,7 +82,9 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; /** * @param mixed $value + * * @return int|null + * * @throws Error */ public function parseValue($value) @@ -89,8 +95,10 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; /** * @param Node $valueNode * @param mixed[]|null $variables + * * @return int|null - * @throws \Exception + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -102,6 +110,6 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } } diff --git a/src/Type/Definition/InterfaceType.php b/src/Type/Definition/InterfaceType.php index 297ad40..7c18323 100644 --- a/src/Type/Definition/InterfaceType.php +++ b/src/Type/Definition/InterfaceType.php @@ -27,7 +27,6 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT private $fields; /** - * * @param mixed[] $config */ public function __construct(array $config) @@ -47,6 +46,7 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT /** * @param mixed $type + * * @return self */ public static function assertInterfaceType($type) @@ -61,6 +61,7 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT /** * @param string $name + * * @return FieldDefinition */ public function getField($name) @@ -91,6 +92,7 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT * * @param object $objectValue * @param mixed[] $context + * * @return callable|null */ public function resolveType($objectValue, $context, ResolveInfo $info) diff --git a/src/Type/Definition/LeafType.php b/src/Type/Definition/LeafType.php index ff7ed97..ece7355 100644 --- a/src/Type/Definition/LeafType.php +++ b/src/Type/Definition/LeafType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\Node; @@ -19,7 +20,9 @@ interface LeafType * Serializes an internal value to include in a response. * * @param mixed $value + * * @return mixed + * * @throws Error */ public function serialize($value); @@ -30,7 +33,9 @@ interface LeafType * In the case of an invalid value this method must throw an Exception * * @param mixed $value + * * @return mixed + * * @throws Error */ public function parseValue($value); @@ -42,8 +47,10 @@ interface LeafType * * @param Node $valueNode * @param mixed[]|null $variables + * * @return mixed - * @throws \Exception + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null); } diff --git a/src/Type/Definition/ListOfType.php b/src/Type/Definition/ListOfType.php index e6a8596..7fdb6e6 100644 --- a/src/Type/Definition/ListOfType.php +++ b/src/Type/Definition/ListOfType.php @@ -33,12 +33,13 @@ class ListOfType extends Type implements WrappingType, OutputType, InputType /** * @param bool $recurse + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType */ public function getWrappedType($recurse = false) { $type = $this->ofType; - return ($recurse && $type instanceof WrappingType) ? $type->getWrappedType($recurse) : $type; + return $recurse && $type instanceof WrappingType ? $type->getWrappedType($recurse) : $type; } } diff --git a/src/Type/Definition/NonNull.php b/src/Type/Definition/NonNull.php index 46b11d1..f3ebbca 100644 --- a/src/Type/Definition/NonNull.php +++ b/src/Type/Definition/NonNull.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Utils\Utils; @@ -17,7 +18,8 @@ class NonNull extends Type implements WrappingType, OutputType, InputType /** * @param callable|Type $type - * @throws \Exception + * + * @throws Exception */ public function __construct($type) { @@ -26,6 +28,7 @@ class NonNull extends Type implements WrappingType, OutputType, InputType /** * @param mixed $type + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType */ public static function assertNullableType($type) @@ -40,6 +43,7 @@ class NonNull extends Type implements WrappingType, OutputType, InputType /** * @param mixed $type + * * @return self */ public static function assertNullType($type) @@ -62,13 +66,15 @@ class NonNull extends Type implements WrappingType, OutputType, InputType /** * @param bool $recurse + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType + * * @throws InvariantViolation */ public function getWrappedType($recurse = false) { $type = $this->ofType; - return ($recurse && $type instanceof WrappingType) ? $type->getWrappedType($recurse) : $type; + return $recurse && $type instanceof WrappingType ? $type->getWrappedType($recurse) : $type; } } diff --git a/src/Type/Definition/ObjectType.php b/src/Type/Definition/ObjectType.php index 43263ce..5cb9556 100644 --- a/src/Type/Definition/ObjectType.php +++ b/src/Type/Definition/ObjectType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\AST\ObjectTypeExtensionNode; @@ -52,7 +53,6 @@ use function sprintf; * ]; * } * ]); - * */ class ObjectType extends Type implements OutputType, CompositeType, NamedType { @@ -75,7 +75,6 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType private $interfaceMap; /** - * * @param mixed[] $config */ public function __construct(array $config) @@ -96,6 +95,7 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType /** * @param mixed $type + * * @return self */ public static function assertObjectType($type) @@ -110,8 +110,10 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType /** * @param string $name + * * @return FieldDefinition - * @throws \Exception + * + * @throws Exception */ public function getField($name) { @@ -125,6 +127,7 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType /** * @return FieldDefinition[] + * * @throws InvariantViolation */ public function getFields() @@ -139,6 +142,7 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType /** * @param InterfaceType $iface + * * @return bool */ public function implementsInterface($iface) @@ -184,6 +188,7 @@ class ObjectType extends Type implements OutputType, CompositeType, NamedType /** * @param mixed[] $value * @param mixed[]|null $context + * * @return bool|null */ public function isTypeOf($value, $context, ResolveInfo $info) diff --git a/src/Type/Definition/ResolveInfo.php b/src/Type/Definition/ResolveInfo.php index fb508d2..a31abff 100644 --- a/src/Type/Definition/ResolveInfo.php +++ b/src/Type/Definition/ResolveInfo.php @@ -139,9 +139,11 @@ class ResolveInfo * Warning: this method it is a naive implementation which does not take into account * conditional typed fragments. So use it with care for fields of interface and union types. * - * @api * @param int $depth How many levels to include in output + * * @return bool[] + * + * @api */ public function getFieldSelection($depth = 0) { diff --git a/src/Type/Definition/StringType.php b/src/Type/Definition/StringType.php index 61dbd39..ebfcf4a 100644 --- a/src/Type/Definition/StringType.php +++ b/src/Type/Definition/StringType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\StringValueNode; @@ -29,7 +30,9 @@ represent free-form human-readable text.'; /** * @param mixed $value + * * @return mixed|string + * * @throws Error */ public function serialize($value) @@ -67,7 +70,9 @@ represent free-form human-readable text.'; /** * @param mixed $value + * * @return string + * * @throws Error */ public function parseValue($value) @@ -78,8 +83,10 @@ represent free-form human-readable text.'; /** * @param Node $valueNode * @param mixed[]|null $variables - * @return null|string - * @throws \Exception + * + * @return string|null + * + * @throws Exception */ public function parseLiteral($valueNode, ?array $variables = null) { @@ -88,6 +95,6 @@ represent free-form human-readable text.'; } // Intentionally without message, as all information already in wrapped Exception - throw new \Exception(); + throw new Exception(); } } diff --git a/src/Type/Definition/Type.php b/src/Type/Definition/Type.php index 0fab77d..b89bbf4 100644 --- a/src/Type/Definition/Type.php +++ b/src/Type/Definition/Type.php @@ -4,10 +4,14 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Type\Introspection; use GraphQL\Utils\Utils; +use JsonSerializable; +use ReflectionClass; +use Throwable; use function array_keys; use function array_merge; use function in_array; @@ -17,7 +21,7 @@ use function preg_replace; * Registry of standard GraphQL types * and a base class for all other types. */ -abstract class Type implements \JsonSerializable +abstract class Type implements JsonSerializable { public const STRING = 'String'; public const INT = 'Int'; @@ -44,8 +48,9 @@ abstract class Type implements \JsonSerializable public $config; /** - * @api * @return IDType + * + * @api */ public static function id() { @@ -54,6 +59,7 @@ abstract class Type implements \JsonSerializable /** * @param string $name + * * @return (IDType|StringType|FloatType|IntType|BooleanType)[]|IDType|StringType|FloatType|IntType|BooleanType */ private static function getInternalType($name = null) @@ -72,8 +78,9 @@ abstract class Type implements \JsonSerializable } /** - * @api * @return StringType + * + * @api */ public static function string() { @@ -81,8 +88,9 @@ abstract class Type implements \JsonSerializable } /** - * @api * @return BooleanType + * + * @api */ public static function boolean() { @@ -90,8 +98,9 @@ abstract class Type implements \JsonSerializable } /** - * @api * @return IntType + * + * @api */ public static function int() { @@ -99,8 +108,9 @@ abstract class Type implements \JsonSerializable } /** - * @api * @return FloatType + * + * @api */ public static function float() { @@ -108,9 +118,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType + * * @return ListOfType + * + * @api */ public static function listOf($wrappedType) { @@ -118,9 +130,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType $wrappedType + * * @return NonNull + * + * @api */ public static function nonNull($wrappedType) { @@ -166,9 +180,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isInputType($type) { @@ -180,9 +196,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType + * + * @api */ public static function getNamedType($type) { @@ -197,9 +215,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isOutputType($type) { @@ -211,9 +231,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isLeafType($type) { @@ -221,9 +243,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isCompositeType($type) { @@ -231,9 +255,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isAbstractType($type) { @@ -242,6 +268,7 @@ abstract class Type implements \JsonSerializable /** * @param mixed $type + * * @return mixed */ public static function assertType($type) @@ -255,9 +282,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return bool + * + * @api */ public static function isType($type) { @@ -265,9 +294,11 @@ abstract class Type implements \JsonSerializable } /** - * @api * @param Type $type + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType + * + * @api */ public static function getNullableType($type) { @@ -305,15 +336,15 @@ abstract class Type implements \JsonSerializable { try { return $this->toString(); - } catch (\Exception $e) { + } catch (Exception $e) { echo $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { echo $e; } } /** - * @return null|string + * @return string|null */ protected function tryInferName() { @@ -324,7 +355,7 @@ abstract class Type implements \JsonSerializable // If class is extended - infer name from className // QueryType -> Type // SomeOtherType -> SomeOther - $tmp = new \ReflectionClass($this); + $tmp = new ReflectionClass($this); $name = $tmp->getShortName(); if ($tmp->getNamespaceName() !== __NAMESPACE__) { diff --git a/src/Type/Definition/UnionType.php b/src/Type/Definition/UnionType.php index ea3ec64..221c828 100644 --- a/src/Type/Definition/UnionType.php +++ b/src/Type/Definition/UnionType.php @@ -104,6 +104,7 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, * * @param object $objectValue * @param mixed $context + * * @return callable|null */ public function resolveType($objectValue, $context, ResolveInfo $info) diff --git a/src/Type/Definition/WrappingType.php b/src/Type/Definition/WrappingType.php index d93d0f4..8bff768 100644 --- a/src/Type/Definition/WrappingType.php +++ b/src/Type/Definition/WrappingType.php @@ -8,6 +8,7 @@ interface WrappingType { /** * @param bool $recurse + * * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType */ public function getWrappedType($recurse = false); diff --git a/src/Type/EagerResolution.php b/src/Type/EagerResolution.php index e75819c..a67b39b 100644 --- a/src/Type/EagerResolution.php +++ b/src/Type/EagerResolution.php @@ -25,7 +25,6 @@ class EagerResolution implements Resolution private $implementations = []; /** - * * @param Type[] $initialTypes */ public function __construct(array $initialTypes) diff --git a/src/Type/Introspection.php b/src/Type/Introspection.php index cab3a62..6e3d78e 100644 --- a/src/Type/Introspection.php +++ b/src/Type/Introspection.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type; +use Exception; use GraphQL\Language\DirectiveLocation; use GraphQL\Language\Printer; use GraphQL\Type\Definition\Directive; @@ -44,6 +45,7 @@ class Introspection * Default: true * * @param bool[]|bool $options + * * @return string */ public static function getIntrospectionQuery($options = []) @@ -157,6 +159,7 @@ EOD; /** * @param Type $type + * * @return bool */ public static function isIntrospectionType($type) @@ -193,14 +196,14 @@ EOD; 'types' => [ 'description' => 'A list of all types supported by this server.', 'type' => new NonNull(new ListOfType(new NonNull(self::_type()))), - 'resolve' => function (Schema $schema) { + 'resolve' => static function (Schema $schema) { return array_values($schema->getTypeMap()); }, ], 'queryType' => [ 'description' => 'The type that query operations will be rooted at.', 'type' => new NonNull(self::_type()), - 'resolve' => function (Schema $schema) { + 'resolve' => static function (Schema $schema) { return $schema->getQueryType(); }, ], @@ -209,21 +212,21 @@ EOD; 'If this server supports mutation, the type that ' . 'mutation operations will be rooted at.', 'type' => self::_type(), - 'resolve' => function (Schema $schema) { + 'resolve' => static function (Schema $schema) { return $schema->getMutationType(); }, ], 'subscriptionType' => [ 'description' => 'If this server support subscription, the type that subscription operations will be rooted at.', 'type' => self::_type(), - 'resolve' => function (Schema $schema) { + 'resolve' => static function (Schema $schema) { return $schema->getSubscriptionType(); }, ], 'directives' => [ 'description' => 'A list of all directives supported by this server.', 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_directive()))), - 'resolve' => function (Schema $schema) { + 'resolve' => static function (Schema $schema) { return $schema->getDirectives(); }, ], @@ -250,11 +253,11 @@ EOD; 'Object and Interface types provide the fields they describe. Abstract ' . 'types, Union and Interface, provide the Object types possible ' . 'at runtime. List and NonNull types compose other types.', - 'fields' => function () { + 'fields' => static function () { return [ 'kind' => [ 'type' => Type::nonNull(self::_typeKind()), - 'resolve' => function (Type $type) { + 'resolve' => static function (Type $type) { switch (true) { case $type instanceof ListOfType: return TypeKind::LIST_KIND; @@ -273,7 +276,7 @@ EOD; case $type instanceof UnionType: return TypeKind::UNION; default: - throw new \Exception('Unknown kind of type: ' . Utils::printSafe($type)); + throw new Exception('Unknown kind of type: ' . Utils::printSafe($type)); } }, ], @@ -284,14 +287,14 @@ EOD; 'args' => [ 'includeDeprecated' => ['type' => Type::boolean(), 'defaultValue' => false], ], - 'resolve' => function (Type $type, $args) { + 'resolve' => static function (Type $type, $args) { if ($type instanceof ObjectType || $type instanceof InterfaceType) { $fields = $type->getFields(); if (empty($args['includeDeprecated'])) { $fields = array_filter( $fields, - function (FieldDefinition $field) { + static function (FieldDefinition $field) { return ! $field->deprecationReason; } ); @@ -305,7 +308,7 @@ EOD; ], 'interfaces' => [ 'type' => Type::listOf(Type::nonNull(self::_type())), - 'resolve' => function ($type) { + 'resolve' => static function ($type) { if ($type instanceof ObjectType) { return $type->getInterfaces(); } @@ -315,7 +318,7 @@ EOD; ], 'possibleTypes' => [ 'type' => Type::listOf(Type::nonNull(self::_type())), - 'resolve' => function ($type, $args, $context, ResolveInfo $info) { + 'resolve' => static function ($type, $args, $context, ResolveInfo $info) { if ($type instanceof InterfaceType || $type instanceof UnionType) { return $info->schema->getPossibleTypes($type); } @@ -328,14 +331,14 @@ EOD; 'args' => [ 'includeDeprecated' => ['type' => Type::boolean(), 'defaultValue' => false], ], - 'resolve' => function ($type, $args) { + 'resolve' => static function ($type, $args) { if ($type instanceof EnumType) { $values = array_values($type->getValues()); if (empty($args['includeDeprecated'])) { $values = array_filter( $values, - function ($value) { + static function ($value) { return ! $value->deprecationReason; } ); @@ -349,7 +352,7 @@ EOD; ], 'inputFields' => [ 'type' => Type::listOf(Type::nonNull(self::_inputValue())), - 'resolve' => function ($type) { + 'resolve' => static function ($type) { if ($type instanceof InputObjectType) { return array_values($type->getFields()); } @@ -359,7 +362,7 @@ EOD; ], 'ofType' => [ 'type' => self::_type(), - 'resolve' => function ($type) { + 'resolve' => static function ($type) { if ($type instanceof WrappingType) { return $type->getWrappedType(); } @@ -431,25 +434,25 @@ EOD; 'description' => 'Object and Interface types are described by a list of Fields, each of ' . 'which has a name, potentially a list of arguments, and a return type.', - 'fields' => function () { + 'fields' => static function () { return [ 'name' => ['type' => Type::nonNull(Type::string())], 'description' => ['type' => Type::string()], 'args' => [ 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_inputValue()))), - 'resolve' => function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) { return empty($field->args) ? [] : $field->args; }, ], 'type' => [ 'type' => Type::nonNull(self::_type()), - 'resolve' => function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) { return $field->getType(); }, ], 'isDeprecated' => [ 'type' => Type::nonNull(Type::boolean()), - 'resolve' => function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) { return (bool) $field->deprecationReason; }, ], @@ -474,13 +477,13 @@ EOD; 'Arguments provided to Fields or Directives and the input fields of an ' . 'InputObject are represented as Input Values which describe their type ' . 'and optionally a default value.', - 'fields' => function () { + 'fields' => static function () { return [ 'name' => ['type' => Type::nonNull(Type::string())], 'description' => ['type' => Type::string()], 'type' => [ 'type' => Type::nonNull(self::_type()), - 'resolve' => function ($value) { + 'resolve' => static function ($value) { return method_exists($value, 'getType') ? $value->getType() : $value->type; }, ], @@ -488,7 +491,7 @@ EOD; 'type' => Type::string(), 'description' => 'A GraphQL-formatted string representing the default value for this input value.', - 'resolve' => function ($inputValue) { + 'resolve' => static function ($inputValue) { /** @var FieldArgument|InputObjectField $inputValue */ return ! $inputValue->defaultValueExists() ? null @@ -521,7 +524,7 @@ EOD; 'description' => ['type' => Type::string()], 'isDeprecated' => [ 'type' => Type::nonNull(Type::boolean()), - 'resolve' => function ($enumValue) { + 'resolve' => static function ($enumValue) { return (bool) $enumValue->deprecationReason; }, ], @@ -557,7 +560,7 @@ EOD; ], 'args' => [ 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_inputValue()))), - 'resolve' => function (Directive $directive) { + 'resolve' => static function (Directive $directive) { return $directive->args ?: []; }, ], @@ -567,7 +570,7 @@ EOD; 'onOperation' => [ 'deprecationReason' => 'Use `locations`.', 'type' => Type::nonNull(Type::boolean()), - 'resolve' => function ($d) { + 'resolve' => static function ($d) { return in_array(DirectiveLocation::QUERY, $d->locations) || in_array(DirectiveLocation::MUTATION, $d->locations) || in_array(DirectiveLocation::SUBSCRIPTION, $d->locations); @@ -576,7 +579,7 @@ EOD; 'onFragment' => [ 'deprecationReason' => 'Use `locations`.', 'type' => Type::nonNull(Type::boolean()), - 'resolve' => function ($d) { + 'resolve' => static function ($d) { return in_array(DirectiveLocation::FRAGMENT_SPREAD, $d->locations) || in_array(DirectiveLocation::INLINE_FRAGMENT, $d->locations) || in_array(DirectiveLocation::FRAGMENT_DEFINITION, $d->locations); @@ -585,7 +588,7 @@ EOD; 'onField' => [ 'deprecationReason' => 'Use `locations`.', 'type' => Type::nonNull(Type::boolean()), - 'resolve' => function ($d) { + 'resolve' => static function ($d) { return in_array(DirectiveLocation::FIELD, $d->locations); }, ], @@ -694,7 +697,7 @@ EOD; 'type' => Type::nonNull(self::_schema()), 'description' => 'Access the current type schema of this server.', 'args' => [], - 'resolve' => function ( + 'resolve' => static function ( $source, $args, $context, @@ -718,7 +721,7 @@ EOD; 'args' => [ ['name' => 'name', 'type' => Type::nonNull(Type::string())], ], - 'resolve' => function ($source, $args, $context, ResolveInfo $info) { + 'resolve' => static function ($source, $args, $context, ResolveInfo $info) { return $info->schema->getType($args['name']); }, ]); @@ -735,7 +738,7 @@ EOD; 'type' => Type::nonNull(Type::string()), 'description' => 'The name of the current Object type at runtime.', 'args' => [], - 'resolve' => function ( + 'resolve' => static function ( $source, $args, $context, diff --git a/src/Type/LazyResolution.php b/src/Type/LazyResolution.php index 08f5028..8404888 100644 --- a/src/Type/LazyResolution.php +++ b/src/Type/LazyResolution.php @@ -42,7 +42,6 @@ class LazyResolution implements Resolution private $loadedPossibleTypes; /** - * * @param mixed[] $descriptor */ public function __construct(array $descriptor, callable $typeLoader) diff --git a/src/Type/Resolution.php b/src/Type/Resolution.php index 177e50e..da15b9f 100644 --- a/src/Type/Resolution.php +++ b/src/Type/Resolution.php @@ -20,6 +20,7 @@ interface Resolution * Returns instance of type with given $name for GraphQL Schema * * @param string $name + * * @return Type */ public function resolveType($name); diff --git a/src/Type/Schema.php b/src/Type/Schema.php index 9d37c71..019d5c1 100644 --- a/src/Type/Schema.php +++ b/src/Type/Schema.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Type; +use Generator; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\GraphQL; @@ -17,6 +18,7 @@ use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; use GraphQL\Utils\TypeInfo; use GraphQL\Utils\Utils; +use Traversable; use function array_values; use function implode; use function is_array; @@ -72,8 +74,9 @@ class Schema public $extensionASTNodes; /** - * @api * @param mixed[]|SchemaConfig $config + * + * @api */ public function __construct($config) { @@ -151,7 +154,7 @@ class Schema } /** - * @return \Generator + * @return Generator */ private function resolveAdditionalTypes() { @@ -161,7 +164,7 @@ class Schema $types = $types(); } - if (! is_array($types) && ! $types instanceof \Traversable) { + if (! is_array($types) && ! $types instanceof Traversable) { throw new InvariantViolation(sprintf( 'Schema types callable must return array or instance of Traversable but got: %s', Utils::getVariableType($types) @@ -186,8 +189,9 @@ class Schema * * This operation requires full schema scan. Do not use in production environment. * - * @api * @return Type[] + * + * @api */ public function getTypeMap() { @@ -228,8 +232,9 @@ class Schema /** * Returns a list of directives supported by this schema * - * @api * @return Directive[] + * + * @api */ public function getDirectives() { @@ -239,8 +244,9 @@ class Schema /** * Returns schema query type * - * @api * @return ObjectType + * + * @api */ public function getQueryType() { @@ -250,8 +256,9 @@ class Schema /** * Returns schema mutation type * - * @api * @return ObjectType|null + * + * @api */ public function getMutationType() { @@ -261,8 +268,9 @@ class Schema /** * Returns schema subscription * - * @api * @return ObjectType|null + * + * @api */ public function getSubscriptionType() { @@ -270,8 +278,9 @@ class Schema } /** - * @api * @return SchemaConfig + * + * @api */ public function getConfig() { @@ -281,9 +290,11 @@ class Schema /** * Returns type by it's name * - * @api * @param string $name + * * @return Type|null + * + * @api */ public function getType($name) { @@ -300,6 +311,7 @@ class Schema /** * @param string $typeName + * * @return Type */ private function loadType($typeName) @@ -332,6 +344,7 @@ class Schema /** * @param string $typeName + * * @return Type */ private function defaultTypeLoader($typeName) @@ -348,8 +361,9 @@ class Schema * * This operation requires full schema scan. Do not use in production environment. * - * @api * @return ObjectType[] + * + * @api */ public function getPossibleTypes(AbstractType $abstractType) { @@ -389,8 +403,9 @@ class Schema * Returns true if object type is concrete type of given abstract type * (implementation for interfaces and members of union type for unions) * - * @api * @return bool + * + * @api */ public function isPossibleType(AbstractType $abstractType, ObjectType $possibleType) { @@ -405,9 +420,11 @@ class Schema /** * Returns instance of directive by name * - * @api * @param string $name + * * @return Directive + * + * @api */ public function getDirective($name) { @@ -433,8 +450,9 @@ class Schema * * This operation requires full schema scan. Do not use in production environment. * - * @api * @throws InvariantViolation + * + * @api */ public function assertValid() { @@ -472,8 +490,9 @@ class Schema * * This operation requires full schema scan. Do not use in production environment. * - * @api * @return InvariantViolation[]|Error[] + * + * @api */ public function validate() { diff --git a/src/Type/SchemaConfig.php b/src/Type/SchemaConfig.php index f2e7138..9f33626 100644 --- a/src/Type/SchemaConfig.php +++ b/src/Type/SchemaConfig.php @@ -24,7 +24,6 @@ use function is_callable; * ->setTypeLoader($myTypeLoader); * * $schema = new Schema($config); - * */ class SchemaConfig { @@ -59,9 +58,11 @@ class SchemaConfig * Converts an array of options to instance of SchemaConfig * (or just returns empty config when array is not passed). * - * @api * @param mixed[] $options + * * @return SchemaConfig + * + * @api */ public static function create(array $options = []) { @@ -132,8 +133,9 @@ class SchemaConfig } /** - * @api * @return ObjectType + * + * @api */ public function getQuery() { @@ -141,9 +143,11 @@ class SchemaConfig } /** - * @api * @param ObjectType $query + * * @return SchemaConfig + * + * @api */ public function setQuery($query) { @@ -153,8 +157,9 @@ class SchemaConfig } /** - * @api * @return ObjectType + * + * @api */ public function getMutation() { @@ -162,9 +167,11 @@ class SchemaConfig } /** - * @api * @param ObjectType $mutation + * * @return SchemaConfig + * + * @api */ public function setMutation($mutation) { @@ -174,8 +181,9 @@ class SchemaConfig } /** - * @api * @return ObjectType + * + * @api */ public function getSubscription() { @@ -183,9 +191,11 @@ class SchemaConfig } /** - * @api * @param ObjectType $subscription + * * @return SchemaConfig + * + * @api */ public function setSubscription($subscription) { @@ -195,8 +205,9 @@ class SchemaConfig } /** - * @api * @return Type[] + * + * @api */ public function getTypes() { @@ -204,9 +215,11 @@ class SchemaConfig } /** - * @api * @param Type[]|callable $types + * * @return SchemaConfig + * + * @api */ public function setTypes($types) { @@ -216,8 +229,9 @@ class SchemaConfig } /** - * @api * @return Directive[] + * + * @api */ public function getDirectives() { @@ -225,9 +239,11 @@ class SchemaConfig } /** - * @api * @param Directive[] $directives + * * @return SchemaConfig + * + * @api */ public function setDirectives(array $directives) { @@ -237,8 +253,9 @@ class SchemaConfig } /** - * @api * @return callable + * + * @api */ public function getTypeLoader() { @@ -246,8 +263,9 @@ class SchemaConfig } /** - * @api * @return SchemaConfig + * + * @api */ public function setTypeLoader(callable $typeLoader) { @@ -266,6 +284,7 @@ class SchemaConfig /** * @param bool $assumeValid + * * @return SchemaConfig */ public function setAssumeValid($assumeValid) diff --git a/src/Type/SchemaValidationContext.php b/src/Type/SchemaValidationContext.php index 53b7020..3762f50 100644 --- a/src/Type/SchemaValidationContext.php +++ b/src/Type/SchemaValidationContext.php @@ -207,6 +207,7 @@ class SchemaValidationContext /** * @param string $argName + * * @return InputValueDefinitionNode[] */ private function getAllDirectiveArgNodes(Directive $directive, $argName) @@ -228,6 +229,7 @@ class SchemaValidationContext /** * @param string $argName + * * @return TypeNode|null */ private function getDirectiveArgTypeNode(Directive $directive, $argName) @@ -358,6 +360,7 @@ class SchemaValidationContext /** * @param ObjectType|InterfaceType $type + * * @return ObjectTypeDefinitionNode[]|ObjectTypeExtensionNode[]|InterfaceTypeDefinitionNode[]|InterfaceTypeExtensionNode[] */ private function getAllObjectOrInterfaceNodes($type) @@ -372,6 +375,7 @@ class SchemaValidationContext /** * @param ObjectType|InterfaceType $type * @param string $fieldName + * * @return FieldDefinitionNode[] */ private function getAllFieldNodes($type, $fieldName) @@ -398,6 +402,7 @@ class SchemaValidationContext /** * @param ObjectType|InterfaceType $type * @param string $fieldName + * * @return TypeNode|null */ private function getFieldTypeNode($type, $fieldName) @@ -410,6 +415,7 @@ class SchemaValidationContext /** * @param ObjectType|InterfaceType $type * @param string $fieldName + * * @return FieldDefinitionNode|null */ private function getFieldNode($type, $fieldName) @@ -423,6 +429,7 @@ class SchemaValidationContext * @param ObjectType|InterfaceType $type * @param string $fieldName * @param string $argName + * * @return InputValueDefinitionNode[] */ private function getAllFieldArgNodes($type, $fieldName, $argName) @@ -446,6 +453,7 @@ class SchemaValidationContext * @param ObjectType|InterfaceType $type * @param string $fieldName * @param string $argName + * * @return TypeNode|null */ private function getFieldArgTypeNode($type, $fieldName, $argName) @@ -459,6 +467,7 @@ class SchemaValidationContext * @param ObjectType|InterfaceType $type * @param string $fieldName * @param string $argName + * * @return InputValueDefinitionNode|null */ private function getFieldArgNode($type, $fieldName, $argName) @@ -497,6 +506,7 @@ class SchemaValidationContext /** * @param InterfaceType $iface + * * @return NamedTypeNode|null */ private function getImplementsInterfaceNode(ObjectType $type, $iface) @@ -508,6 +518,7 @@ class SchemaValidationContext /** * @param InterfaceType $iface + * * @return NamedTypeNode[] */ private function getAllImplementsInterfaceNodes(ObjectType $type, $iface) @@ -715,6 +726,7 @@ class SchemaValidationContext /** * @param string $typeName + * * @return NamedTypeNode[] */ private function getUnionMemberTypeNodes(UnionType $union, $typeName) @@ -722,7 +734,7 @@ class SchemaValidationContext if ($union->astNode && $union->astNode->types) { return array_filter( $union->astNode->types, - function (NamedTypeNode $value) use ($typeName) { + static function (NamedTypeNode $value) use ($typeName) { return $value->name->value === $typeName; } ); @@ -770,6 +782,7 @@ class SchemaValidationContext /** * @param string $valueName + * * @return EnumValueDefinitionNode[] */ private function getEnumValueNodes(EnumType $enum, $valueName) @@ -777,7 +790,7 @@ class SchemaValidationContext if ($enum->astNode && $enum->astNode->values) { return array_filter( iterator_to_array($enum->astNode->values), - function (EnumValueDefinitionNode $value) use ($valueName) { + static function (EnumValueDefinitionNode $value) use ($valueName) { return $value->name->value === $valueName; } ); From e664c4455e2b4bafef9cf4e83633a15193f0fbb9 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 10:55:09 +0200 Subject: [PATCH 09/10] Fix CS in src/Utils --- src/Utils/AST.php | 70 +++++++++++++++--------- src/Utils/ASTDefinitionBuilder.php | 25 ++++++--- src/Utils/BreakingChangesFinder.php | 23 ++++---- src/Utils/BuildSchema.php | 30 ++++++----- src/Utils/MixedStore.php | 23 ++++++-- src/Utils/PairSet.php | 3 +- src/Utils/SchemaPrinter.php | 31 ++++++----- src/Utils/TypeComparators.php | 1 + src/Utils/TypeInfo.php | 9 ++-- src/Utils/Utils.php | 83 ++++++++++++++++++++--------- src/Utils/Value.php | 28 ++++++---- 11 files changed, 213 insertions(+), 113 deletions(-) diff --git a/src/Utils/AST.php b/src/Utils/AST.php index ca61a94..aa3d421 100644 --- a/src/Utils/AST.php +++ b/src/Utils/AST.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Utils; +use ArrayAccess; +use Exception; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\BooleanValueNode; @@ -36,6 +38,9 @@ use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; +use stdClass; +use Throwable; +use Traversable; use function array_combine; use function array_key_exists; use function array_map; @@ -77,8 +82,9 @@ class AST * * This is a reverse operation for AST::toArray($node) * - * @api * @param mixed[] $node + * + * @api */ public static function fromArray(array $node) : Node { @@ -114,8 +120,9 @@ class AST /** * Convert AST node to serializable array * - * @api * @return mixed[] + * + * @api */ public static function toArray(Node $node) { @@ -140,9 +147,11 @@ class AST * | Mixed | Enum Value | * | null | NullValue | * - * @api * @param Type|mixed|null $value + * * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode + * + * @api */ public static function astFromValue($value, InputType $type) { @@ -163,7 +172,7 @@ class AST // the value is not an array, convert the value using the list's item type. if ($type instanceof ListOfType) { $itemType = $type->getWrappedType(); - if (is_array($value) || ($value instanceof \Traversable)) { + if (is_array($value) || ($value instanceof Traversable)) { $valuesNodes = []; foreach ($value as $item) { $itemNode = self::astFromValue($item, $itemType); @@ -184,7 +193,7 @@ class AST // in the PHP object according to the fields in the input type. if ($type instanceof InputObjectType) { $isArray = is_array($value); - $isArrayLike = $isArray || $value instanceof \ArrayAccess; + $isArrayLike = $isArray || $value instanceof ArrayAccess; if ($value === null || (! $isArrayLike && ! is_object($value))) { return null; } @@ -204,7 +213,7 @@ class AST } elseif ($isArray) { $fieldExists = array_key_exists($fieldName, $value); } elseif ($isArrayLike) { - /** @var \ArrayAccess $value */ + /** @var ArrayAccess $value */ $fieldExists = $value->offsetExists($fieldName); } else { $fieldExists = property_exists($value, $fieldName); @@ -234,12 +243,12 @@ class AST // to an externally represented value before converting into an AST. try { $serialized = $type->serialize($value); - } catch (\Exception $error) { + } catch (Exception $error) { if ($error instanceof Error && $type instanceof EnumType) { return null; } throw $error; - } catch (\Throwable $error) { + } catch (Throwable $error) { if ($error instanceof Error && $type instanceof EnumType) { return null; } @@ -304,13 +313,16 @@ class AST * | Enum Value | Mixed | * | Null Value | null | * - * @api * @param ValueNode|null $valueNode * @param mixed[]|null $variables - * @return mixed[]|null|\stdClass - * @throws \Exception + * + * @return mixed[]|stdClass|null + * + * @throws Exception + * + * @api */ - public static function valueFromAST($valueNode, InputType $type, $variables = null) + public static function valueFromAST($valueNode, InputType $type, ?array $variables = null) { $undefined = Utils::undefined(); @@ -393,7 +405,7 @@ class AST $fields = $type->getFields(); $fieldNodes = Utils::keyMap( $valueNode->fields, - function ($field) { + static function ($field) { return $field->name->value; } ); @@ -442,9 +454,9 @@ class AST // no value is returned. try { return $type->parseLiteral($valueNode, $variables); - } catch (\Exception $error) { + } catch (Exception $error) { return $undefined; - } catch (\Throwable $error) { + } catch (Throwable $error) { return $undefined; } } @@ -455,8 +467,10 @@ class AST /** * Returns true if the provided valueNode is a variable which is not defined * in the set of variables. + * * @param ValueNode $valueNode * @param mixed[] $variables + * * @return bool */ private static function isMissingVariable($valueNode, $variables) @@ -481,11 +495,14 @@ class AST * | Enum | Mixed | * | Null | null | * - * @api * @param Node $valueNode * @param mixed[]|null $variables + * * @return mixed - * @throws \Exception + * + * @throws Exception + * + * @api */ public static function valueFromASTUntyped($valueNode, ?array $variables = null) { @@ -502,7 +519,7 @@ class AST return $valueNode->value; case $valueNode instanceof ListValueNode: return array_map( - function ($node) use ($variables) { + static function ($node) use ($variables) { return self::valueFromASTUntyped($node, $variables); }, iterator_to_array($valueNode->values) @@ -510,13 +527,13 @@ class AST case $valueNode instanceof ObjectValueNode: return array_combine( array_map( - function ($field) { + static function ($field) { return $field->name->value; }, iterator_to_array($valueNode->fields) ), array_map( - function ($field) use ($variables) { + static function ($field) use ($variables) { return self::valueFromASTUntyped($field->value, $variables); }, iterator_to_array($valueNode->fields) @@ -525,7 +542,7 @@ class AST case $valueNode instanceof VariableNode: $variableName = $valueNode->name->value; - return ($variables && isset($variables[$variableName])) + return $variables && isset($variables[$variableName]) ? $variables[$variableName] : null; } @@ -536,10 +553,13 @@ class AST /** * Returns type definition for given AST Type node * - * @api * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode + * * @return Type|null - * @throws \Exception + * + * @throws Exception + * + * @api */ public static function typeFromAST(Schema $schema, $inputTypeNode) { @@ -563,9 +583,11 @@ class AST /** * Returns operation type ("query", "mutation" or "subscription") given a document and operation name * - * @api * @param string $operationName + * * @return bool + * + * @api */ public static function getOperation(DocumentNode $document, $operationName = null) { diff --git a/src/Utils/ASTDefinitionBuilder.php b/src/Utils/ASTDefinitionBuilder.php index 5112851..50a8e47 100644 --- a/src/Utils/ASTDefinitionBuilder.php +++ b/src/Utils/ASTDefinitionBuilder.php @@ -34,6 +34,7 @@ use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; +use Throwable; use function array_reverse; use function implode; use function is_array; @@ -82,7 +83,7 @@ class ASTDefinitionBuilder 'description' => $this->getDescription($directiveNode), 'locations' => Utils::map( $directiveNode->locations, - function ($node) { + static function ($node) { return $node->value; } ), @@ -135,7 +136,7 @@ class ASTDefinitionBuilder { return Utils::keyValMap( $values, - function ($value) { + static function ($value) { return $value->name->value; }, function ($value) { @@ -160,6 +161,7 @@ class ASTDefinitionBuilder /** * @return Type|InputType + * * @throws Error */ private function internalBuildWrappedType(TypeNode $typeNode) @@ -171,7 +173,9 @@ class ASTDefinitionBuilder /** * @param string|NamedTypeNode $ref + * * @return Type + * * @throws Error */ public function buildType($ref) @@ -186,7 +190,9 @@ class ASTDefinitionBuilder /** * @param string $typeName * @param NamedTypeNode|null $typeNode + * * @return Type + * * @throws Error */ private function internalBuildType($typeName, $typeNode = null) @@ -198,7 +204,7 @@ class ASTDefinitionBuilder $fn = $this->typeConfigDecorator; try { $config = $fn($type->config, $this->typeDefintionsMap[$typeName], $this->typeDefintionsMap); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new Error( sprintf('Type config decorator passed to %s threw an error ', static::class) . sprintf('when building %s type: %s', $typeName, $e->getMessage()), @@ -232,7 +238,9 @@ class ASTDefinitionBuilder /** * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeDefinitionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode|UnionTypeDefinitionNode $def + * * @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType + * * @throws Error */ private function makeSchemaDef($def) @@ -280,7 +288,7 @@ class ASTDefinitionBuilder return $def->fields ? Utils::keyValMap( $def->fields, - function ($field) { + static function ($field) { return $field->name->value; }, function ($field) { @@ -309,6 +317,7 @@ class ASTDefinitionBuilder * deprecation reason. * * @param EnumValueDefinitionNode | FieldDefinitionNode $node + * * @return string */ private function getDeprecationReason($node) @@ -357,7 +366,7 @@ class ASTDefinitionBuilder 'values' => $def->values ? Utils::keyValMap( $def->values, - function ($enumValue) { + static function ($enumValue) { return $enumValue->name->value; }, function ($enumValue) { @@ -399,7 +408,7 @@ class ASTDefinitionBuilder 'name' => $def->name->value, 'description' => $this->getDescription($def), 'astNode' => $def, - 'serialize' => function ($value) { + 'serialize' => static function ($value) { return $value; }, ]); @@ -422,7 +431,9 @@ class ASTDefinitionBuilder /** * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeExtensionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode $def * @param mixed[] $config + * * @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType + * * @throws Error */ private function makeSchemaDefFromConfig($def, array $config) @@ -450,6 +461,7 @@ class ASTDefinitionBuilder /** * @param TypeNode|ListTypeNode|NonNullTypeNode $typeNode + * * @return TypeNode */ private function getNamedTypeNode(TypeNode $typeNode) @@ -464,6 +476,7 @@ class ASTDefinitionBuilder /** * @param TypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode + * * @return Type */ private function buildWrappedType(Type $innerType, TypeNode $inputTypeNode) diff --git a/src/Utils/BreakingChangesFinder.php b/src/Utils/BreakingChangesFinder.php index 5e17e23..885ee32 100644 --- a/src/Utils/BreakingChangesFinder.php +++ b/src/Utils/BreakingChangesFinder.php @@ -21,6 +21,7 @@ use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Schema; +use TypeError; use function array_flip; use function array_key_exists; use function array_keys; @@ -141,7 +142,7 @@ class BreakingChangesFinder /** * @return string * - * @throws \TypeError + * @throws TypeError */ private static function typeKindName(Type $type) { @@ -169,7 +170,7 @@ class BreakingChangesFinder return 'an Input type'; } - throw new \TypeError('unknown type ' . $type->name); + throw new TypeError('unknown type ' . $type->name); } /** @@ -340,7 +341,6 @@ class BreakingChangesFinder } /** - * * @return bool */ private static function isChangeSafeForInputObjectFieldOrFieldArg( @@ -370,8 +370,8 @@ class BreakingChangesFinder $newType->getWrappedType() )) || // moving from non-null to nullable of the same underlying type is safe - (! ($newType instanceof NonNull) && - self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType)); + ! ($newType instanceof NonNull) && + self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType); } return false; @@ -492,7 +492,7 @@ class BreakingChangesFinder $newArgs = $newTypeFields[$fieldName]->args; $newArgDef = Utils::find( $newArgs, - function ($arg) use ($oldArgDef) { + static function ($arg) use ($oldArgDef) { return $arg->name === $oldArgDef->name; } ); @@ -531,7 +531,7 @@ class BreakingChangesFinder $oldArgs = $oldTypeFields[$fieldName]->args; $oldArgDef = Utils::find( $oldArgs, - function ($arg) use ($newArgDef) { + static function ($arg) use ($newArgDef) { return $arg->name === $newArgDef->name; } ); @@ -586,7 +586,7 @@ class BreakingChangesFinder foreach ($oldInterfaces as $oldInterface) { if (Utils::find( $newInterfaces, - function (InterfaceType $interface) use ($oldInterface) { + static function (InterfaceType $interface) use ($oldInterface) { return $interface->name === $oldInterface->name; } )) { @@ -629,7 +629,7 @@ class BreakingChangesFinder { return Utils::keyMap( $schema->getDirectives(), - function ($dir) { + static function ($dir) { return $dir->name; } ); @@ -678,7 +678,7 @@ class BreakingChangesFinder { return Utils::keyMap( $directive->args ?: [], - function ($arg) { + static function ($arg) { return $arg->name; } ); @@ -831,7 +831,6 @@ class BreakingChangesFinder } /** - * * @return string[][] */ public static function findInterfacesAddedToObjectTypes( @@ -853,7 +852,7 @@ class BreakingChangesFinder foreach ($newInterfaces as $newInterface) { if (Utils::find( $oldInterfaces, - function (InterfaceType $interface) use ($newInterface) { + static function (InterfaceType $interface) use ($newInterface) { return $interface->name === $newInterface->name; } )) { diff --git a/src/Utils/BuildSchema.php b/src/Utils/BuildSchema.php index 94d4dcf..ae79c01 100644 --- a/src/Utils/BuildSchema.php +++ b/src/Utils/BuildSchema.php @@ -49,10 +49,12 @@ class BuildSchema * A helper function to build a GraphQLSchema directly from a source * document. * - * @api * @param DocumentNode|Source|string $source * @param bool[] $options + * * @return Schema + * + * @api */ public static function build($source, ?callable $typeConfigDecorator = null, array $options = []) { @@ -76,11 +78,13 @@ class BuildSchema * - commentDescriptions: * Provide true to use preceding comments as the description. * + * @param bool[] $options + * + * @return Schema + * + * @throws Error * * @api - * @param bool[] $options - * @return Schema - * @throws Error */ public static function buildAST(DocumentNode $ast, ?callable $typeConfigDecorator = null, array $options = []) { @@ -134,14 +138,14 @@ class BuildSchema $defintionBuilder = new ASTDefinitionBuilder( $this->nodeMap, $this->options, - function ($typeName) { + static function ($typeName) { throw new Error('Type "' . $typeName . '" not found in document.'); }, $this->typeConfigDecorator ); $directives = array_map( - function ($def) use ($defintionBuilder) { + static function ($def) use ($defintionBuilder) { return $defintionBuilder->buildDirective($def); }, $directiveDefs @@ -150,7 +154,7 @@ class BuildSchema // If specified directives were not explicitly declared, add them. $skip = array_reduce( $directives, - function ($hasSkip, $directive) { + static function ($hasSkip, $directive) { return $hasSkip || $directive->name === 'skip'; } ); @@ -160,7 +164,7 @@ class BuildSchema $include = array_reduce( $directives, - function ($hasInclude, $directive) { + static function ($hasInclude, $directive) { return $hasInclude || $directive->name === 'include'; } ); @@ -170,7 +174,7 @@ class BuildSchema $deprecated = array_reduce( $directives, - function ($hasDeprecated, $directive) { + static function ($hasDeprecated, $directive) { return $hasDeprecated || $directive->name === 'deprecated'; } ); @@ -182,7 +186,7 @@ class BuildSchema // typed values below, that would throw immediately while type system // validation with validateSchema() will produce more actionable results. - $schema = new Schema([ + return new Schema([ 'query' => isset($operationTypes['query']) ? $defintionBuilder->buildType($operationTypes['query']) : null, @@ -192,7 +196,7 @@ class BuildSchema 'subscription' => isset($operationTypes['subscription']) ? $defintionBuilder->buildType($operationTypes['subscription']) : null, - 'typeLoader' => function ($name) use ($defintionBuilder) { + 'typeLoader' => static function ($name) use ($defintionBuilder) { return $defintionBuilder->buildType($name); }, 'directives' => $directives, @@ -206,13 +210,13 @@ class BuildSchema return $types; }, ]); - - return $schema; } /** * @param SchemaDefinitionNode $schemaDef + * * @return string[] + * * @throws Error */ private function getOperationTypes($schemaDef) diff --git a/src/Utils/MixedStore.php b/src/Utils/MixedStore.php index a3201a3..2ee1918 100644 --- a/src/Utils/MixedStore.php +++ b/src/Utils/MixedStore.php @@ -4,7 +4,10 @@ declare(strict_types=1); namespace GraphQL\Utils; +use ArrayAccess; use GraphQL\Type\Definition\EnumValueDefinition; +use InvalidArgumentException; +use SplObjectStorage; use function array_key_exists; use function array_search; use function array_splice; @@ -22,7 +25,7 @@ use function is_string; * * Class MixedStore */ -class MixedStore implements \ArrayAccess +class MixedStore implements ArrayAccess { /** @var EnumValueDefinition[] */ private $standardStore; @@ -30,7 +33,7 @@ class MixedStore implements \ArrayAccess /** @var mixed[] */ private $floatStore; - /** @var \SplObjectStorage */ + /** @var SplObjectStorage */ private $objectStore; /** @var callable[] */ @@ -67,7 +70,7 @@ class MixedStore implements \ArrayAccess { $this->standardStore = []; $this->floatStore = []; - $this->objectStore = new \SplObjectStorage(); + $this->objectStore = new SplObjectStorage(); $this->arrayKeys = []; $this->arrayValues = []; $this->nullValueIsSet = false; @@ -77,10 +80,13 @@ class MixedStore implements \ArrayAccess /** * Whether a offset exists + * * @link http://php.net/manual/en/arrayaccess.offsetexists.php + * * @param mixed $offset

* An offset to check for. *

+ * * @return bool true on success or false on failure. *

*

@@ -122,10 +128,13 @@ class MixedStore implements \ArrayAccess /** * Offset to retrieve + * * @link http://php.net/manual/en/arrayaccess.offsetget.php + * * @param mixed $offset

* The offset to retrieve. *

+ * * @return mixed Can return all value types. */ public function offsetGet($offset) @@ -165,13 +174,16 @@ class MixedStore implements \ArrayAccess /** * Offset to set + * * @link http://php.net/manual/en/arrayaccess.offsetset.php + * * @param mixed $offset

* The offset to assign the value to. *

* @param mixed $value

* The value to set. *

+ * * @return void */ public function offsetSet($offset, $value) @@ -195,16 +207,19 @@ class MixedStore implements \ArrayAccess $this->nullValue = $value; $this->nullValueIsSet = true; } else { - throw new \InvalidArgumentException('Unexpected offset type: ' . Utils::printSafe($offset)); + throw new InvalidArgumentException('Unexpected offset type: ' . Utils::printSafe($offset)); } } /** * Offset to unset + * * @link http://php.net/manual/en/arrayaccess.offsetunset.php + * * @param mixed $offset

* The offset to unset. *

+ * * @return void */ public function offsetUnset($offset) diff --git a/src/Utils/PairSet.php b/src/Utils/PairSet.php index e910a4b..fe3a514 100644 --- a/src/Utils/PairSet.php +++ b/src/Utils/PairSet.php @@ -22,12 +22,13 @@ class PairSet * @param string $a * @param string $b * @param bool $areMutuallyExclusive + * * @return bool */ public function has($a, $b, $areMutuallyExclusive) { $first = $this->data[$a] ?? null; - $result = ($first && isset($first[$b])) ? $first[$b] : null; + $result = $first && isset($first[$b]) ? $first[$b] : null; if ($result === null) { return false; } diff --git a/src/Utils/SchemaPrinter.php b/src/Utils/SchemaPrinter.php index aba3e45..023ecb9 100644 --- a/src/Utils/SchemaPrinter.php +++ b/src/Utils/SchemaPrinter.php @@ -42,17 +42,19 @@ class SchemaPrinter * * - commentDescriptions: * Provide true to use preceding comments as the description. - * @api + * * @param bool[] $options + * + * @api */ public static function doPrint(Schema $schema, array $options = []) : string { return self::printFilteredSchema( $schema, - function ($type) { + static function ($type) { return ! Directive::isSpecifiedDirective($type); }, - function ($type) { + static function ($type) { return ! Type::isBuiltInType($type); }, $options @@ -66,7 +68,7 @@ class SchemaPrinter { $directives = array_filter( $schema->getDirectives(), - function ($directive) use ($directiveFilter) { + static function ($directive) use ($directiveFilter) { return $directiveFilter($directive); } ); @@ -83,13 +85,13 @@ class SchemaPrinter array_merge( [self::printSchemaDefinition($schema)], array_map( - function ($directive) use ($options) { + static function ($directive) use ($options) { return self::printDirective($directive, $options); }, $directives ), array_map( - function ($type) use ($options) { + static function ($type) use ($options) { return self::printType($type, $options); }, $types @@ -175,7 +177,7 @@ class SchemaPrinter return self::printDescriptionWithComments($lines, $indentation, $firstInBlock); } - $description = ($indentation && ! $firstInBlock) + $description = $indentation && ! $firstInBlock ? "\n" . $indentation . '"""' : $indentation . '"""'; @@ -274,7 +276,7 @@ class SchemaPrinter // If every arg does not have a description, print them on one line. if (Utils::every( $args, - function ($arg) { + static function ($arg) { return empty($arg->description); } )) { @@ -286,7 +288,7 @@ class SchemaPrinter implode( "\n", array_map( - function ($arg, $i) use ($indentation, $options) { + static function ($arg, $i) use ($indentation, $options) { return self::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation . self::printInputValue($arg); }, @@ -358,7 +360,7 @@ class SchemaPrinter ' implements ' . implode( ' & ', array_map( - function ($i) { + static function ($i) { return $i->name; }, $interfaces @@ -379,7 +381,7 @@ class SchemaPrinter return implode( "\n", array_map( - function ($f, $i) use ($options) { + static function ($f, $i) use ($options) { return self::printDescription($options, $f, ' ', ! $i) . ' ' . $f->name . self::printArgs($options, $f->args, ' ') . ': ' . (string) $f->getType() . self::printDeprecated($f); @@ -439,7 +441,7 @@ class SchemaPrinter return implode( "\n", array_map( - function ($value, $i) use ($options) { + static function ($value, $i) use ($options) { return self::printDescription($options, $value, ' ', ! $i) . ' ' . $value->name . self::printDeprecated($value); }, @@ -463,7 +465,7 @@ class SchemaPrinter implode( "\n", array_map( - function ($f, $i) use ($options) { + static function ($f, $i) use ($options) { return self::printDescription($options, $f, ' ', ! $i) . ' ' . self::printInputValue($f); }, $fields, @@ -474,8 +476,9 @@ class SchemaPrinter } /** - * @api * @param bool[] $options + * + * @api */ public static function printIntrospectionSchema(Schema $schema, array $options = []) : string { diff --git a/src/Utils/TypeComparators.php b/src/Utils/TypeComparators.php index c66b266..24e4b00 100644 --- a/src/Utils/TypeComparators.php +++ b/src/Utils/TypeComparators.php @@ -46,6 +46,7 @@ class TypeComparators * * @param AbstractType $maybeSubType * @param AbstractType $superType + * * @return bool */ public static function isTypeSubTypeOf(Schema $schema, $maybeSubType, $superType) diff --git a/src/Utils/TypeInfo.php b/src/Utils/TypeInfo.php index e27bf5a..76b8019 100644 --- a/src/Utils/TypeInfo.php +++ b/src/Utils/TypeInfo.php @@ -64,7 +64,6 @@ class TypeInfo private $enumValue; /** - * * @param Type|null $initialType */ public function __construct(Schema $schema, $initialType = null) @@ -128,6 +127,7 @@ class TypeInfo * * @param Type|null $type * @param Type[]|null $typeMap + * * @return Type[]|null */ public static function extractTypes($type, ?array $typeMap = null) @@ -175,7 +175,7 @@ class TypeInfo foreach ((array) $type->getFields() as $fieldName => $field) { if (! empty($field->args)) { $fieldArgTypes = array_map( - function (FieldArgument $arg) { + static function (FieldArgument $arg) { return $arg->getType(); }, $field->args @@ -200,6 +200,7 @@ class TypeInfo /** * @param Type[] $typeMap + * * @return Type[] */ public static function extractTypesFromDirectives(Directive $directive, array $typeMap = []) @@ -304,7 +305,7 @@ class TypeInfo if ($fieldOrDirective) { $argDef = Utils::find( $fieldOrDirective->args, - function ($arg) use ($node) { + static function ($arg) use ($node) { return $arg->name === $node->name->value; } ); @@ -406,7 +407,9 @@ class TypeInfo /** * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode + * * @return Type|null + * * @throws InvariantViolation */ public static function typeFromAST(Schema $schema, $inputTypeNode) diff --git a/src/Utils/Utils.php b/src/Utils/Utils.php index e1cfcef..be0bdda 100644 --- a/src/Utils/Utils.php +++ b/src/Utils/Utils.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Utils; +use ErrorException; +use Exception; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\Error\Warning; @@ -11,6 +13,8 @@ use GraphQL\Language\AST\Node; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\WrappingType; use InvalidArgumentException; +use LogicException; +use stdClass; use Traversable; use function array_keys; use function array_map; @@ -55,13 +59,14 @@ class Utils { static $undefined; - return $undefined ?: $undefined = new \stdClass(); + return $undefined ?: $undefined = new stdClass(); } /** * Check if the value is invalid * * @param mixed $value + * * @return bool */ public static function isInvalid($value) @@ -100,12 +105,13 @@ class Utils /** * @param mixed|Traversable $traversable + * * @return mixed|null */ public static function find($traversable, callable $predicate) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -120,13 +126,15 @@ class Utils /** * @param mixed|Traversable $traversable + * * @return mixed[] - * @throws \Exception + * + * @throws Exception */ public static function filter($traversable, callable $predicate) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -147,14 +155,16 @@ class Utils } /** - * @param mixed|\Traversable $traversable + * @param mixed|Traversable $traversable + * * @return int[][] - * @throws \Exception + * + * @throws Exception */ public static function map($traversable, callable $fn) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -168,20 +178,22 @@ class Utils /** * @param mixed|Traversable $traversable + * * @return mixed[] - * @throws \Exception + * + * @throws Exception */ public static function mapKeyValue($traversable, callable $fn) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $map = []; foreach ($traversable as $key => $value) { - list($newKey, $newValue) = $fn($value, $key); - $map[$newKey] = $newValue; + [$newKey, $newValue] = $fn($value, $key); + $map[$newKey] = $newValue; } return $map; @@ -189,13 +201,15 @@ class Utils /** * @param mixed|Traversable $traversable + * * @return mixed[] - * @throws \Exception + * + * @throws Exception */ public static function keyMap($traversable, callable $keyFn) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -215,7 +229,7 @@ class Utils public static function each($traversable, callable $fn) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -237,12 +251,13 @@ class Utils * $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys * * @param mixed[]|Traversable $traversable + * * @return mixed[] */ public static function groupBy($traversable, callable $keyFn) { self::invariant( - is_array($traversable) || $traversable instanceof \Traversable, + is_array($traversable) || $traversable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); @@ -259,6 +274,7 @@ class Utils /** * @param mixed[]|Traversable $traversable + * * @return mixed[][] */ public static function keyValMap($traversable, callable $keyFn, callable $valFn) @@ -273,6 +289,7 @@ class Utils /** * @param mixed[] $traversable + * * @return bool */ public static function every($traversable, callable $predicate) @@ -305,6 +322,7 @@ class Utils /** * @param Type|mixed $var + * * @return string */ public static function getVariableType($var) @@ -323,11 +341,12 @@ class Utils /** * @param mixed $var + * * @return string */ public static function printSafeJson($var) { - if ($var instanceof \stdClass) { + if ($var instanceof stdClass) { $var = (array) $var; } if (is_array($var)) { @@ -357,6 +376,7 @@ class Utils /** * @param Type|mixed $var + * * @return string */ public static function printSafe($var) @@ -401,6 +421,7 @@ class Utils * * @param string $ord * @param string $encoding + * * @return string */ public static function chr($ord, $encoding = 'UTF-8') @@ -420,6 +441,7 @@ class Utils * * @param string $char * @param string $encoding + * * @return mixed */ public static function ord($char, $encoding = 'UTF-8') @@ -442,6 +464,7 @@ class Utils * * @param string $string * @param int $position + * * @return mixed */ public static function charCodeAt($string, $position) @@ -453,6 +476,7 @@ class Utils /** * @param int|null $code + * * @return string */ public static function printCharCode($code) @@ -472,6 +496,7 @@ class Utils * Upholds the spec rules about naming. * * @param string $name + * * @throws Error */ public static function assertValidName($name) @@ -487,6 +512,7 @@ class Utils * * @param string $name * @param Node|null $node + * * @return Error|null */ public static function isValidNameError($name, $node = null) @@ -512,18 +538,19 @@ class Utils } /** - * Wraps original closure with PHP error handling (using set_error_handler). - * Resulting closure will collect all PHP errors that occur during the call in $errors array. + * Wraps original callable with PHP error handling (using set_error_handler). + * Resulting callable will collect all PHP errors that occur during the call in $errors array. * - * @param \ErrorException[] $errors - * @return \Closure + * @param ErrorException[] $errors + * + * @return callable */ public static function withErrorHandling(callable $fn, array &$errors) { - return function () use ($fn, &$errors) { + return static function () use ($fn, &$errors) { // Catch custom errors (to report them in query results) - set_error_handler(function ($severity, $message, $file, $line) use (&$errors) { - $errors[] = new \ErrorException($message, 0, $severity, $file, $line); + set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) { + $errors[] = new ErrorException($message, 0, $severity, $file, $line); }); try { @@ -536,12 +563,13 @@ class Utils /** * @param string[] $items + * * @return string */ public static function quotedOrList(array $items) { $items = array_map( - function ($item) { + static function ($item) { return sprintf('"%s"', $item); }, $items @@ -552,12 +580,13 @@ class Utils /** * @param string[] $items + * * @return string */ public static function orList(array $items) { if (count($items) === 0) { - throw new \LogicException('items must not need to be empty.'); + throw new LogicException('items must not need to be empty.'); } $selected = array_slice($items, 0, 5); $selectedLength = count($selected); @@ -569,7 +598,7 @@ class Utils return array_reduce( range(1, $selectedLength - 1), - function ($list, $index) use ($selected, $selectedLength) { + static function ($list, $index) use ($selected, $selectedLength) { return $list . ($selectedLength > 2 ? ', ' : ' ') . ($index === $selectedLength - 1 ? 'or ' : '') . @@ -586,8 +615,10 @@ class Utils * Includes a custom alteration from Damerau-Levenshtein to treat case changes * as a single edit which helps identify mis-cased values with an edit distance * of 1 + * * @param string $input * @param string[] $options + * * @return string[] */ public static function suggestionList($input, array $options) diff --git a/src/Utils/Value.php b/src/Utils/Value.php index 9541291..2bb053c 100644 --- a/src/Utils/Value.php +++ b/src/Utils/Value.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Utils; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\Node; use GraphQL\Type\Definition\EnumType; @@ -12,6 +13,8 @@ use GraphQL\Type\Definition\InputType; use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ScalarType; +use Throwable; +use Traversable; use function array_key_exists; use function array_keys; use function array_map; @@ -61,7 +64,7 @@ class Value // the original error. try { return self::ofValue($type->parseValue($value)); - } catch (\Exception $error) { + } catch (Exception $error) { return self::ofErrors([ self::coercionError( sprintf('Expected type %s', $type->name), @@ -71,7 +74,7 @@ class Value $error ), ]); - } catch (\Throwable $error) { + } catch (Throwable $error) { return self::ofErrors([ self::coercionError( sprintf('Expected type %s', $type->name), @@ -95,7 +98,7 @@ class Value $suggestions = Utils::suggestionList( Utils::printSafe($value), array_map( - function ($enumValue) { + static function ($enumValue) { return $enumValue->name; }, $type->getValues() @@ -118,7 +121,7 @@ class Value if ($type instanceof ListOfType) { $itemType = $type->getWrappedType(); - if (is_array($value) || $value instanceof \Traversable) { + if (is_array($value) || $value instanceof Traversable) { $errors = []; $coercedValue = []; foreach ($value as $index => $itemValue) { @@ -144,7 +147,7 @@ class Value } if ($type instanceof InputObjectType) { - if (! is_object($value) && ! is_array($value) && ! $value instanceof \Traversable) { + if (! is_object($value) && ! is_array($value) && ! $value instanceof Traversable) { return self::ofErrors([ self::coercionError( sprintf('Expected type %s to be an object', $type->name), @@ -225,11 +228,12 @@ class Value } /** - * @param string $message - * @param Node $blameNode - * @param mixed[]|null $path - * @param string $subMessage - * @param \Exception|\Throwable|null $originalError + * @param string $message + * @param Node $blameNode + * @param mixed[]|null $path + * @param string $subMessage + * @param Exception|Throwable|null $originalError + * * @return Error */ private static function coercionError( @@ -258,6 +262,7 @@ class Value * Build a string describing the path into the value where the error was found * * @param mixed[]|null $path + * * @return string */ private static function printPath(?array $path = null) @@ -277,6 +282,7 @@ class Value /** * @param mixed $value + * * @return (mixed|null)[] */ private static function ofValue($value) @@ -287,6 +293,7 @@ class Value /** * @param mixed|null $prev * @param mixed|null $key + * * @return (mixed|null)[] */ private static function atPath($prev, $key) @@ -297,6 +304,7 @@ class Value /** * @param Error[] $errors * @param Error|Error[] $moreErrors + * * @return Error[] */ private static function add($errors, $moreErrors) From dd4a5076f6d5e72ed3afee7315e9e8bc69a7397e Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 26 Sep 2018 11:01:29 +0200 Subject: [PATCH 10/10] Fix CS in src/Validator --- src/Validator/DocumentValidator.php | 21 +++++++++++----- src/Validator/Rules/DisableIntrospection.php | 2 +- src/Validator/Rules/ExecutableDefinitions.php | 2 +- src/Validator/Rules/FieldsOnCorrectType.php | 3 +++ .../Rules/FragmentsOnCompositeTypes.php | 4 ++-- src/Validator/Rules/KnownArgumentNames.php | 6 ++--- src/Validator/Rules/KnownDirectives.php | 2 +- src/Validator/Rules/KnownFragmentNames.php | 2 +- src/Validator/Rules/KnownTypeNames.php | 4 ++-- .../Rules/LoneAnonymousOperation.php | 6 ++--- src/Validator/Rules/NoFragmentCycles.php | 4 ++-- src/Validator/Rules/NoUndefinedVariables.php | 6 ++--- .../Rules/OverlappingFieldsCanBeMerged.php | 24 ++++++++++++------- .../Rules/ProvidedNonNullArguments.php | 4 ++-- src/Validator/Rules/QueryComplexity.php | 13 +++++----- src/Validator/Rules/QuerySecurityRule.php | 23 ++++++++++-------- src/Validator/Rules/ScalarLeafs.php | 2 +- .../Rules/UniqueDirectivesPerLocation.php | 2 +- src/Validator/Rules/UniqueFragmentNames.php | 2 +- src/Validator/Rules/UniqueOperationNames.php | 2 +- src/Validator/Rules/ValidationRule.php | 4 ++-- src/Validator/Rules/ValuesOfCorrectType.php | 14 ++++++----- .../Rules/VariablesAreInputTypes.php | 2 +- .../Rules/VariablesDefaultValueAllowed.php | 6 ++--- .../Rules/VariablesInAllowedPosition.php | 2 +- src/Validator/ValidationContext.php | 5 ++-- 26 files changed, 96 insertions(+), 71 deletions(-) diff --git a/src/Validator/DocumentValidator.php b/src/Validator/DocumentValidator.php index 5e5540a..a3cde92 100644 --- a/src/Validator/DocumentValidator.php +++ b/src/Validator/DocumentValidator.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Validator; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\DocumentNode; use GraphQL\Language\Visitor; @@ -41,6 +42,7 @@ use GraphQL\Validator\Rules\ValuesOfCorrectType; use GraphQL\Validator\Rules\VariablesAreInputTypes; use GraphQL\Validator\Rules\VariablesDefaultValueAllowed; use GraphQL\Validator\Rules\VariablesInAllowedPosition; +use Throwable; use function array_filter; use function array_merge; use function count; @@ -82,9 +84,11 @@ class DocumentValidator /** * Primary method for query validation. See class description for details. * - * @api * @param ValidationRule[]|null $rules + * * @return Error[] + * + * @api */ public static function validate( Schema $schema, @@ -109,8 +113,9 @@ class DocumentValidator /** * Returns all global validation rules. * - * @api * @return ValidationRule[] + * + * @api */ public static function allRules() { @@ -183,6 +188,7 @@ class DocumentValidator * while maintaining the visitor skip and break API. * * @param ValidationRule[] $rules + * * @return Error[] */ public static function visitUsingRules(Schema $schema, TypeInfo $typeInfo, DocumentNode $documentNode, array $rules) @@ -203,9 +209,11 @@ class DocumentValidator * * $rule = DocumentValidator::getRule(GraphQL\Validator\Rules\QueryComplexity::class); * - * @api * @param string $name + * * @return ValidationRule + * + * @api */ public static function getRule($name) { @@ -235,11 +243,11 @@ class DocumentValidator return is_array($value) ? count(array_filter( $value, - function ($item) { - return $item instanceof \Exception || $item instanceof \Throwable; + static function ($item) { + return $item instanceof Exception || $item instanceof Throwable; } )) === count($value) - : ($value instanceof \Exception || $value instanceof \Throwable); + : ($value instanceof Exception || $value instanceof Throwable); } public static function append(&$arr, $items) @@ -259,6 +267,7 @@ class DocumentValidator * Deprecated. Rely on validation for documents containing literal values. * * @deprecated + * * @return Error[] */ public static function isValidLiteralValue(Type $type, $valueNode) diff --git a/src/Validator/Rules/DisableIntrospection.php b/src/Validator/Rules/DisableIntrospection.php index bdb7a7c..bb2dc3e 100644 --- a/src/Validator/Rules/DisableIntrospection.php +++ b/src/Validator/Rules/DisableIntrospection.php @@ -31,7 +31,7 @@ class DisableIntrospection extends QuerySecurityRule return $this->invokeIfNeeded( $context, [ - NodeKind::FIELD => function (FieldNode $node) use ($context) { + NodeKind::FIELD => static function (FieldNode $node) use ($context) { if ($node->name->value !== '__type' && $node->name->value !== '__schema') { return; } diff --git a/src/Validator/Rules/ExecutableDefinitions.php b/src/Validator/Rules/ExecutableDefinitions.php index 325b320..e626861 100644 --- a/src/Validator/Rules/ExecutableDefinitions.php +++ b/src/Validator/Rules/ExecutableDefinitions.php @@ -25,7 +25,7 @@ class ExecutableDefinitions extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::DOCUMENT => function (DocumentNode $node) use ($context) { + NodeKind::DOCUMENT => static function (DocumentNode $node) use ($context) { /** @var Node $definition */ foreach ($node->definitions as $definition) { if ($definition instanceof OperationDefinitionNode || diff --git a/src/Validator/Rules/FieldsOnCorrectType.php b/src/Validator/Rules/FieldsOnCorrectType.php index 104849c..1053255 100644 --- a/src/Validator/Rules/FieldsOnCorrectType.php +++ b/src/Validator/Rules/FieldsOnCorrectType.php @@ -74,6 +74,7 @@ class FieldsOnCorrectType extends ValidationRule * * @param ObjectType|InterfaceType $type * @param string $fieldName + * * @return string[] */ private function getSuggestedTypeNames(Schema $schema, $type, $fieldName) @@ -120,6 +121,7 @@ class FieldsOnCorrectType extends ValidationRule * * @param ObjectType|InterfaceType $type * @param string $fieldName + * * @return array|string[] */ private function getSuggestedFieldNames(Schema $schema, $type, $fieldName) @@ -139,6 +141,7 @@ class FieldsOnCorrectType extends ValidationRule * @param string $type * @param string[] $suggestedTypeNames * @param string[] $suggestedFieldNames + * * @return string */ public static function undefinedFieldMessage( diff --git a/src/Validator/Rules/FragmentsOnCompositeTypes.php b/src/Validator/Rules/FragmentsOnCompositeTypes.php index e6f8f16..c5ca807 100644 --- a/src/Validator/Rules/FragmentsOnCompositeTypes.php +++ b/src/Validator/Rules/FragmentsOnCompositeTypes.php @@ -19,7 +19,7 @@ class FragmentsOnCompositeTypes extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) use ($context) { + NodeKind::INLINE_FRAGMENT => static function (InlineFragmentNode $node) use ($context) { if (! $node->typeCondition) { return; } @@ -34,7 +34,7 @@ class FragmentsOnCompositeTypes extends ValidationRule [$node->typeCondition] )); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) { + NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) use ($context) { $type = TypeInfo::typeFromAST($context->getSchema(), $node->typeCondition); if (! $type || Type::isCompositeType($type)) { diff --git a/src/Validator/Rules/KnownArgumentNames.php b/src/Validator/Rules/KnownArgumentNames.php index 05a52ef..96fd800 100644 --- a/src/Validator/Rules/KnownArgumentNames.php +++ b/src/Validator/Rules/KnownArgumentNames.php @@ -26,7 +26,7 @@ class KnownArgumentNames extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::ARGUMENT => function (ArgumentNode $node, $key, $parent, $path, $ancestors) use ($context) { + NodeKind::ARGUMENT => static function (ArgumentNode $node, $key, $parent, $path, $ancestors) use ($context) { /** @var NodeList|Node[] $ancestors */ $argDef = $context->getArgument(); if ($argDef !== null) { @@ -46,7 +46,7 @@ class KnownArgumentNames extends ValidationRule Utils::suggestionList( $node->name->value, array_map( - function ($arg) { + static function ($arg) { return $arg->name; }, $fieldDef->args @@ -66,7 +66,7 @@ class KnownArgumentNames extends ValidationRule Utils::suggestionList( $node->name->value, array_map( - function ($arg) { + static function ($arg) { return $arg->name; }, $directive->args diff --git a/src/Validator/Rules/KnownDirectives.php b/src/Validator/Rules/KnownDirectives.php index c0c220b..da233a4 100644 --- a/src/Validator/Rules/KnownDirectives.php +++ b/src/Validator/Rules/KnownDirectives.php @@ -37,7 +37,7 @@ class KnownDirectives extends ValidationRule continue; } - $locationsMap[$def->name->value] = array_map(function ($name) { + $locationsMap[$def->name->value] = array_map(static function ($name) { return $name->value; }, $def->locations); } diff --git a/src/Validator/Rules/KnownFragmentNames.php b/src/Validator/Rules/KnownFragmentNames.php index 1b2b4e1..e26e233 100644 --- a/src/Validator/Rules/KnownFragmentNames.php +++ b/src/Validator/Rules/KnownFragmentNames.php @@ -15,7 +15,7 @@ class KnownFragmentNames extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) use ($context) { + NodeKind::FRAGMENT_SPREAD => static function (FragmentSpreadNode $node) use ($context) { $fragmentName = $node->name->value; $fragment = $context->getFragment($fragmentName); if ($fragment) { diff --git a/src/Validator/Rules/KnownTypeNames.php b/src/Validator/Rules/KnownTypeNames.php index 4700103..9abaf0a 100644 --- a/src/Validator/Rules/KnownTypeNames.php +++ b/src/Validator/Rules/KnownTypeNames.php @@ -23,7 +23,7 @@ class KnownTypeNames extends ValidationRule { public function getVisitor(ValidationContext $context) { - $skip = function () { + $skip = static function () { return Visitor::skipNode(); }; @@ -35,7 +35,7 @@ class KnownTypeNames extends ValidationRule NodeKind::INTERFACE_TYPE_DEFINITION => $skip, NodeKind::UNION_TYPE_DEFINITION => $skip, NodeKind::INPUT_OBJECT_TYPE_DEFINITION => $skip, - NodeKind::NAMED_TYPE => function (NamedTypeNode $node) use ($context) { + NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) use ($context) { $schema = $context->getSchema(); $typeName = $node->name->value; $type = $schema->getType($typeName); diff --git a/src/Validator/Rules/LoneAnonymousOperation.php b/src/Validator/Rules/LoneAnonymousOperation.php index 06730f7..40ff821 100644 --- a/src/Validator/Rules/LoneAnonymousOperation.php +++ b/src/Validator/Rules/LoneAnonymousOperation.php @@ -26,17 +26,17 @@ class LoneAnonymousOperation extends ValidationRule $operationCount = 0; return [ - NodeKind::DOCUMENT => function (DocumentNode $node) use (&$operationCount) { + NodeKind::DOCUMENT => static function (DocumentNode $node) use (&$operationCount) { $tmp = Utils::filter( $node->definitions, - function (Node $definition) { + static function (Node $definition) { return $definition->kind === NodeKind::OPERATION_DEFINITION; } ); $operationCount = count($tmp); }, - NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) use ( + NodeKind::OPERATION_DEFINITION => static function (OperationDefinitionNode $node) use ( &$operationCount, $context ) { diff --git a/src/Validator/Rules/NoFragmentCycles.php b/src/Validator/Rules/NoFragmentCycles.php index 0b0a1e6..1180a4e 100644 --- a/src/Validator/Rules/NoFragmentCycles.php +++ b/src/Validator/Rules/NoFragmentCycles.php @@ -43,7 +43,7 @@ class NoFragmentCycles extends ValidationRule $this->spreadPathIndexByName = []; return [ - NodeKind::OPERATION_DEFINITION => function () { + NodeKind::OPERATION_DEFINITION => static function () { return Visitor::skipNode(); }, NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) { @@ -98,7 +98,7 @@ class NoFragmentCycles extends ValidationRule $spreadName, Utils::map( $cyclePath, - function ($s) { + static function ($s) { return $s->name->value; } ) diff --git a/src/Validator/Rules/NoUndefinedVariables.php b/src/Validator/Rules/NoUndefinedVariables.php index af7bfd4..5c2d4a5 100644 --- a/src/Validator/Rules/NoUndefinedVariables.php +++ b/src/Validator/Rules/NoUndefinedVariables.php @@ -25,10 +25,10 @@ class NoUndefinedVariables extends ValidationRule return [ NodeKind::OPERATION_DEFINITION => [ - 'enter' => function () use (&$variableNameDefined) { + 'enter' => static function () use (&$variableNameDefined) { $variableNameDefined = []; }, - 'leave' => function (OperationDefinitionNode $operation) use (&$variableNameDefined, $context) { + 'leave' => static function (OperationDefinitionNode $operation) use (&$variableNameDefined, $context) { $usages = $context->getRecursiveVariableUsages($operation); foreach ($usages as $usage) { @@ -49,7 +49,7 @@ class NoUndefinedVariables extends ValidationRule } }, ], - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $def) use (&$variableNameDefined) { + NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $def) use (&$variableNameDefined) { $variableNameDefined[$def->variable->name->value] = true; }, ]; diff --git a/src/Validator/Rules/OverlappingFieldsCanBeMerged.php b/src/Validator/Rules/OverlappingFieldsCanBeMerged.php index 9a4c56b..d872245 100644 --- a/src/Validator/Rules/OverlappingFieldsCanBeMerged.php +++ b/src/Validator/Rules/OverlappingFieldsCanBeMerged.php @@ -24,6 +24,7 @@ use GraphQL\Type\Definition\Type; use GraphQL\Utils\PairSet; use GraphQL\Utils\TypeInfo; use GraphQL\Validator\ValidationContext; +use SplObjectStorage; use function array_keys; use function array_map; use function array_merge; @@ -39,6 +40,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * A memoization for when two fragments are compared "between" each other for * conflicts. Two fragments may be compared many times, so memoizing this can * dramatically improve the performance of this validator. + * * @var PairSet */ private $comparedFragmentPairs; @@ -48,14 +50,14 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * selection set. Selection sets may be asked for this information multiple * times, so this improves the performance of this validator. * - * @var \SplObjectStorage + * @var SplObjectStorage */ private $cachedFieldsAndFragmentNames; public function getVisitor(ValidationContext $context) { $this->comparedFragmentPairs = new PairSet(); - $this->cachedFieldsAndFragmentNames = new \SplObjectStorage(); + $this->cachedFieldsAndFragmentNames = new SplObjectStorage(); return [ NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context) { @@ -83,6 +85,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * GraphQL Document. * * @param CompositeType $parentType + * * @return mixed[] */ private function findConflictsWithinSelectionSet( @@ -145,7 +148,8 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * referenced via fragment spreads. * * @param CompositeType $parentType - * @return mixed[]|\SplObjectStorage + * + * @return mixed[]|SplObjectStorage */ private function getFieldsAndFragmentNames( ValidationContext $context, @@ -224,7 +228,6 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * * J) Also, if two fragments are referenced in both selection sets, then a * comparison is made "between" the two fragments. - * */ /** @@ -333,6 +336,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * @param string $responseName * @param mixed[] $field1 * @param mixed[] $field2 + * * @return mixed[]|null */ private function findConflict( @@ -503,6 +507,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * @param bool $areMutuallyExclusive * @param CompositeType $parentType1 * @param CompositeType $parentType2 + * * @return mixed[][] */ private function findConflictsBetweenSubSelectionSets( @@ -704,7 +709,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * Given a reference to a fragment, return the represented collection of fields * as well as a list of nested fragment names referenced via fragment spreads. * - * @return mixed[]|\SplObjectStorage + * @return mixed[]|SplObjectStorage */ private function getReferencedFieldsAndFragmentNames( ValidationContext $context, @@ -818,6 +823,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * * @param mixed[][] $conflicts * @param string $responseName + * * @return mixed[]|null */ private function subfieldConflicts( @@ -834,7 +840,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule [ $responseName, array_map( - function ($conflict) { + static function ($conflict) { return $conflict[0]; }, $conflicts @@ -842,14 +848,14 @@ class OverlappingFieldsCanBeMerged extends ValidationRule ], array_reduce( $conflicts, - function ($allFields, $conflict) { + static function ($allFields, $conflict) { return array_merge($allFields, $conflict[1]); }, [$ast1] ), array_reduce( $conflicts, - function ($allFields, $conflict) { + static function ($allFields, $conflict) { return array_merge($allFields, $conflict[2]); }, [$ast2] @@ -876,7 +882,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule { if (is_array($reason)) { $tmp = array_map( - function ($tmp) { + static function ($tmp) { [$responseName, $subReason] = $tmp; $reasonMessage = self::reasonMessage($subReason); diff --git a/src/Validator/Rules/ProvidedNonNullArguments.php b/src/Validator/Rules/ProvidedNonNullArguments.php index 56254af..976f38b 100644 --- a/src/Validator/Rules/ProvidedNonNullArguments.php +++ b/src/Validator/Rules/ProvidedNonNullArguments.php @@ -19,7 +19,7 @@ class ProvidedNonNullArguments extends ValidationRule { return [ NodeKind::FIELD => [ - 'leave' => function (FieldNode $fieldNode) use ($context) { + 'leave' => static function (FieldNode $fieldNode) use ($context) { $fieldDef = $context->getFieldDef(); if (! $fieldDef) { @@ -45,7 +45,7 @@ class ProvidedNonNullArguments extends ValidationRule }, ], NodeKind::DIRECTIVE => [ - 'leave' => function (DirectiveNode $directiveNode) use ($context) { + 'leave' => static function (DirectiveNode $directiveNode) use ($context) { $directiveDef = $context->getDirective(); if (! $directiveDef) { return Visitor::skipNode(); diff --git a/src/Validator/Rules/QueryComplexity.php b/src/Validator/Rules/QueryComplexity.php index f126238..990fcbb 100644 --- a/src/Validator/Rules/QueryComplexity.php +++ b/src/Validator/Rules/QueryComplexity.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; +use ArrayObject; use GraphQL\Error\Error; use GraphQL\Executor\Values; use GraphQL\Language\AST\FieldNode; @@ -31,10 +32,10 @@ class QueryComplexity extends QuerySecurityRule /** @var mixed[]|null */ private $rawVariableValues = []; - /** @var \ArrayObject */ + /** @var ArrayObject */ private $variableDefs; - /** @var \ArrayObject */ + /** @var ArrayObject */ private $fieldNodeAndDefs; /** @var ValidationContext */ @@ -49,8 +50,8 @@ class QueryComplexity extends QuerySecurityRule { $this->context = $context; - $this->variableDefs = new \ArrayObject(); - $this->fieldNodeAndDefs = new \ArrayObject(); + $this->variableDefs = new ArrayObject(); + $this->fieldNodeAndDefs = new ArrayObject(); $complexity = 0; return $this->invokeIfNeeded( @@ -196,7 +197,7 @@ class QueryComplexity extends QuerySecurityRule throw new Error(implode( "\n\n", array_map( - function ($error) { + static function ($error) { return $error->getMessage(); }, $variableValuesResult['errors'] @@ -251,7 +252,7 @@ class QueryComplexity extends QuerySecurityRule throw new Error(implode( "\n\n", array_map( - function ($error) { + static function ($error) { return $error->getMessage(); }, $variableValuesResult['errors'] diff --git a/src/Validator/Rules/QuerySecurityRule.php b/src/Validator/Rules/QuerySecurityRule.php index 810a4d0..c5f0260 100644 --- a/src/Validator/Rules/QuerySecurityRule.php +++ b/src/Validator/Rules/QuerySecurityRule.php @@ -4,16 +4,18 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; -use Closure; +use ArrayObject; use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; +use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Type\Definition\Type; use GraphQL\Type\Introspection; use GraphQL\Utils\TypeInfo; use GraphQL\Validator\ValidationContext; +use InvalidArgumentException; use function class_alias; use function method_exists; use function sprintf; @@ -34,7 +36,7 @@ abstract class QuerySecurityRule extends ValidationRule protected function checkIfGreaterOrEqualToZero($name, $value) { if ($value < 0) { - throw new \InvalidArgumentException(sprintf('$%s argument must be greater or equal to 0.', $name)); + throw new InvalidArgumentException(sprintf('$%s argument must be greater or equal to 0.', $name)); } } @@ -55,8 +57,9 @@ abstract class QuerySecurityRule extends ValidationRule } /** - * @param Closure[] $validators - * @return Closure[] + * @param callable[] $validators + * + * @return callable[] */ protected function invokeIfNeeded(ValidationContext $context, array $validators) { @@ -98,17 +101,17 @@ abstract class QuerySecurityRule extends ValidationRule * * @param Type|null $parentType * - * @return \ArrayObject + * @return ArrayObject */ protected function collectFieldASTsAndDefs( ValidationContext $context, $parentType, SelectionSetNode $selectionSet, - ?\ArrayObject $visitedFragmentNames = null, - ?\ArrayObject $astAndDefs = null + ?ArrayObject $visitedFragmentNames = null, + ?ArrayObject $astAndDefs = null ) { - $_visitedFragmentNames = $visitedFragmentNames ?: new \ArrayObject(); - $_astAndDefs = $astAndDefs ?: new \ArrayObject(); + $_visitedFragmentNames = $visitedFragmentNames ?: new ArrayObject(); + $_astAndDefs = $astAndDefs ?: new ArrayObject(); foreach ($selectionSet->selections as $selection) { switch ($selection->kind) { @@ -134,7 +137,7 @@ abstract class QuerySecurityRule extends ValidationRule } $responseName = $this->getFieldName($selection); if (! isset($_astAndDefs[$responseName])) { - $_astAndDefs[$responseName] = new \ArrayObject(); + $_astAndDefs[$responseName] = new ArrayObject(); } // create field context $_astAndDefs[$responseName][] = [$selection, $fieldDef]; diff --git a/src/Validator/Rules/ScalarLeafs.php b/src/Validator/Rules/ScalarLeafs.php index a96b5d8..1bd2515 100644 --- a/src/Validator/Rules/ScalarLeafs.php +++ b/src/Validator/Rules/ScalarLeafs.php @@ -16,7 +16,7 @@ class ScalarLeafs extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::FIELD => function (FieldNode $node) use ($context) { + NodeKind::FIELD => static function (FieldNode $node) use ($context) { $type = $context->getType(); if (! $type) { return; diff --git a/src/Validator/Rules/UniqueDirectivesPerLocation.php b/src/Validator/Rules/UniqueDirectivesPerLocation.php index c049c82..f0e8c45 100644 --- a/src/Validator/Rules/UniqueDirectivesPerLocation.php +++ b/src/Validator/Rules/UniqueDirectivesPerLocation.php @@ -15,7 +15,7 @@ class UniqueDirectivesPerLocation extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - 'enter' => function (Node $node) use ($context) { + 'enter' => static function (Node $node) use ($context) { if (! isset($node->directives)) { return; } diff --git a/src/Validator/Rules/UniqueFragmentNames.php b/src/Validator/Rules/UniqueFragmentNames.php index e29de7b..475e6b3 100644 --- a/src/Validator/Rules/UniqueFragmentNames.php +++ b/src/Validator/Rules/UniqueFragmentNames.php @@ -22,7 +22,7 @@ class UniqueFragmentNames extends ValidationRule $this->knownFragmentNames = []; return [ - NodeKind::OPERATION_DEFINITION => function () { + NodeKind::OPERATION_DEFINITION => static function () { return Visitor::skipNode(); }, NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) { diff --git a/src/Validator/Rules/UniqueOperationNames.php b/src/Validator/Rules/UniqueOperationNames.php index 232380d..969b90e 100644 --- a/src/Validator/Rules/UniqueOperationNames.php +++ b/src/Validator/Rules/UniqueOperationNames.php @@ -38,7 +38,7 @@ class UniqueOperationNames extends ValidationRule return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => function () { + NodeKind::FRAGMENT_DEFINITION => static function () { return Visitor::skipNode(); }, ]; diff --git a/src/Validator/Rules/ValidationRule.php b/src/Validator/Rules/ValidationRule.php index c35388f..fe8504d 100644 --- a/src/Validator/Rules/ValidationRule.php +++ b/src/Validator/Rules/ValidationRule.php @@ -6,7 +6,6 @@ namespace GraphQL\Validator\Rules; use GraphQL\Validator\ValidationContext; use function class_alias; -use function get_class; abstract class ValidationRule { @@ -15,7 +14,7 @@ abstract class ValidationRule public function getName() { - return $this->name ?: get_class($this); + return $this->name ?: static::class; } public function __invoke(ValidationContext $context) @@ -27,6 +26,7 @@ abstract class ValidationRule * Returns structure suitable for GraphQL\Language\Visitor * * @see \GraphQL\Language\Visitor + * * @return mixed[] */ abstract public function getVisitor(ValidationContext $context); diff --git a/src/Validator/Rules/ValuesOfCorrectType.php b/src/Validator/Rules/ValuesOfCorrectType.php index 2eadf6d..a08d99b 100644 --- a/src/Validator/Rules/ValuesOfCorrectType.php +++ b/src/Validator/Rules/ValuesOfCorrectType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\EnumValueNode; @@ -27,6 +28,7 @@ use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Utils\Utils; use GraphQL\Validator\ValidationContext; +use Throwable; use function array_combine; use function array_keys; use function array_map; @@ -45,7 +47,7 @@ class ValuesOfCorrectType extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::NULL => function (NullValueNode $node) use ($context) { + NodeKind::NULL => static function (NullValueNode $node) use ($context) { $type = $context->getInputType(); if (! ($type instanceof NonNull)) { return; @@ -82,7 +84,7 @@ class ValuesOfCorrectType extends ValidationRule $nodeFields = iterator_to_array($node->fields); $fieldNodeMap = array_combine( array_map( - function ($field) { + static function ($field) { return $field->name->value; }, $nodeFields @@ -103,7 +105,7 @@ class ValuesOfCorrectType extends ValidationRule ); } }, - NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) { + NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) use ($context) { $parentType = Type::getNamedType($context->getParentInputType()); $fieldType = $context->getInputType(); if ($fieldType || ! ($parentType instanceof InputObjectType)) { @@ -193,7 +195,7 @@ class ValuesOfCorrectType extends ValidationRule // may throw to indicate failure. try { $type->parseLiteral($node); - } catch (\Exception $error) { + } catch (Exception $error) { // Ensure a reference to the original error is maintained. $context->reportError( new Error( @@ -209,7 +211,7 @@ class ValuesOfCorrectType extends ValidationRule $error ) ); - } catch (\Throwable $error) { + } catch (Throwable $error) { // Ensure a reference to the original error is maintained. $context->reportError( new Error( @@ -234,7 +236,7 @@ class ValuesOfCorrectType extends ValidationRule $suggestions = Utils::suggestionList( Printer::doPrint($node), array_map( - function (EnumValueDefinition $value) { + static function (EnumValueDefinition $value) { return $value->name; }, $type->getValues() diff --git a/src/Validator/Rules/VariablesAreInputTypes.php b/src/Validator/Rules/VariablesAreInputTypes.php index 4abc2e5..5dc27b4 100644 --- a/src/Validator/Rules/VariablesAreInputTypes.php +++ b/src/Validator/Rules/VariablesAreInputTypes.php @@ -18,7 +18,7 @@ class VariablesAreInputTypes extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) use ($context) { + NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $node) use ($context) { $type = TypeInfo::typeFromAST($context->getSchema(), $node->type); // If the variable type is not an input type, return an error. diff --git a/src/Validator/Rules/VariablesDefaultValueAllowed.php b/src/Validator/Rules/VariablesDefaultValueAllowed.php index 4f2b5cf..a19c14d 100644 --- a/src/Validator/Rules/VariablesDefaultValueAllowed.php +++ b/src/Validator/Rules/VariablesDefaultValueAllowed.php @@ -25,7 +25,7 @@ class VariablesDefaultValueAllowed extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) use ($context) { + NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $node) use ($context) { $name = $node->variable->name->value; $defaultValue = $node->defaultValue; $type = $context->getInputType(); @@ -44,10 +44,10 @@ class VariablesDefaultValueAllowed extends ValidationRule return Visitor::skipNode(); }, - NodeKind::SELECTION_SET => function (SelectionSetNode $node) { + NodeKind::SELECTION_SET => static function (SelectionSetNode $node) { return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) { + NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) { return Visitor::skipNode(); }, ]; diff --git a/src/Validator/Rules/VariablesInAllowedPosition.php b/src/Validator/Rules/VariablesInAllowedPosition.php index a593610..4fa3d46 100644 --- a/src/Validator/Rules/VariablesInAllowedPosition.php +++ b/src/Validator/Rules/VariablesInAllowedPosition.php @@ -71,7 +71,7 @@ class VariablesInAllowedPosition extends ValidationRule private function effectiveType($varType, $varDef) { - return (! $varDef->defaultValue || $varType instanceof NonNull) ? $varType : new NonNull($varType); + return ! $varDef->defaultValue || $varType instanceof NonNull ? $varType : new NonNull($varType); } /** diff --git a/src/Validator/ValidationContext.php b/src/Validator/ValidationContext.php index 2f44734..8ef75e3 100644 --- a/src/Validator/ValidationContext.php +++ b/src/Validator/ValidationContext.php @@ -128,10 +128,10 @@ class ValidationContext Visitor::visitWithTypeInfo( $typeInfo, [ - NodeKind::VARIABLE_DEFINITION => function () { + NodeKind::VARIABLE_DEFINITION => static function () { return false; }, - NodeKind::VARIABLE => function (VariableNode $variable) use ( + NodeKind::VARIABLE => static function (VariableNode $variable) use ( &$newUsages, $typeInfo ) { @@ -214,6 +214,7 @@ class ValidationContext /** * @param string $name + * * @return FragmentDefinitionNode|null */ public function getFragment($name)