graphql-php/search/search_index.json
2018-07-08 00:31:16 +07:00

624 lines
272 KiB
JSON
Executable File

{
"docs": [
{
"location": "/",
"text": "About GraphQL\n\n\nGraphQL is a modern way to build HTTP APIs consumed by the web and mobile clients.\nIt is intended to be a replacement for REST and SOAP APIs (even for \nexisting applications\n).\n\n\nGraphQL itself is a \nspecification\n designed by Facebook\nengineers. Various implementations of this specification were written \n\nin different languages and environments\n.\n\n\nGreat overview of GraphQL features and benefits is presented on \nthe official website\n. \nAll of them equally apply to this PHP implementation. \n\n\nAbout graphql-php\n\n\ngraphql-php\n is a feature-complete implementation of GraphQL specification in PHP (5.5+, 7.0+). \nIt was originally inspired by \nreference JavaScript implementation\n \npublished by Facebook.\n\n\nThis library is a thin wrapper around your existing data layer and business logic. \nIt doesn't dictate how these layers are implemented or which storage engines \nare used. Instead, it provides tools for creating rich API for your existing app.\n\n\nLibrary features include:\n\n\n\n\nPrimitives to express your app as a \nType System\n\n\nValidation and introspection of this Type System (for compatibility with tools like \nGraphiQL\n)\n\n\nParsing, validating and \nexecuting GraphQL queries\n against this Type System\n\n\nRich \nerror reporting\n, including query validation and execution errors\n\n\nOptional tools for \nparsing GraphQL Type language\n\n\nTools for \nbatching requests\n to backend storage\n\n\nAsync PHP platforms support\n via promises\n\n\nStandard HTTP server\n\n\n\n\nAlso, several \ncomplementary tools\n are available which provide integrations with \nexisting PHP frameworks, add support for Relay, etc.\n\n\nCurrent Status\n\n\nThe first version of this library (v0.1) was released on August 10th 2015.\n\n\nThe current version (v0.10) supports all features described by GraphQL specification \n(including April 2016 add-ons) as well as some experimental features like \n\nSchema Language parser\n and \n\nSchema printer\n.\n\n\nReady for real-world usage. \n\n\nGitHub\n\n\nProject source code is \nhosted on GitHub\n.",
"title": "About"
},
{
"location": "/#about-graphql",
"text": "GraphQL is a modern way to build HTTP APIs consumed by the web and mobile clients.\nIt is intended to be a replacement for REST and SOAP APIs (even for existing applications ). GraphQL itself is a specification designed by Facebook\nengineers. Various implementations of this specification were written in different languages and environments . Great overview of GraphQL features and benefits is presented on the official website . \nAll of them equally apply to this PHP implementation.",
"title": "About GraphQL"
},
{
"location": "/#about-graphql-php",
"text": "graphql-php is a feature-complete implementation of GraphQL specification in PHP (5.5+, 7.0+). \nIt was originally inspired by reference JavaScript implementation \npublished by Facebook. This library is a thin wrapper around your existing data layer and business logic. \nIt doesn't dictate how these layers are implemented or which storage engines \nare used. Instead, it provides tools for creating rich API for your existing app. Library features include: Primitives to express your app as a Type System Validation and introspection of this Type System (for compatibility with tools like GraphiQL ) Parsing, validating and executing GraphQL queries against this Type System Rich error reporting , including query validation and execution errors Optional tools for parsing GraphQL Type language Tools for batching requests to backend storage Async PHP platforms support via promises Standard HTTP server Also, several complementary tools are available which provide integrations with \nexisting PHP frameworks, add support for Relay, etc.",
"title": "About graphql-php"
},
{
"location": "/#current-status",
"text": "The first version of this library (v0.1) was released on August 10th 2015. The current version (v0.10) supports all features described by GraphQL specification \n(including April 2016 add-ons) as well as some experimental features like Schema Language parser and Schema printer . Ready for real-world usage.",
"title": "Current Status"
},
{
"location": "/#github",
"text": "Project source code is hosted on GitHub .",
"title": "GitHub"
},
{
"location": "/getting-started/",
"text": "Prerequisites\n\n\nThis documentation assumes your familiarity with GraphQL concepts. If it is not the case - \nfirst learn about GraphQL on \nthe official website\n.\n\n\nInstallation\n\n\nUsing \ncomposer\n, simply run:\n\n\ncomposer require webonyx/graphql-php\n\n\n\n\nUpgrading\n\n\nWe try to keep library releases backwards compatible. But when breaking changes are inevitable \nthey are explained in \nupgrade instructions\n.\n\n\nInstall Tools (optional)\n\n\nWhile it is possible to communicate with GraphQL API using regular HTTP tools it is way \nmore convenient for humans to use \nGraphiQL\n - an in-browser \nIDE for exploring GraphQL APIs.\n\n\nIt provides syntax-highlighting, auto-completion and auto-generated documentation for \nGraphQL API.\n\n\nThe easiest way to use it is to install one of the existing Google Chrome extensions:\n\n\n\n\nChromeiQL\n\n\nGraphiQL Feen\n\n\n\n\nAlternatively, you can follow instructions on \nthe GraphiQL\n\npage and install it locally.\n\n\nHello World\n\n\nLet's create a type system that will be capable to process following simple query:\n\n\nquery {\n echo(message: \"Hello World\")\n}\n\n\n\n\nTo do so we need an object type with field \necho\n:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'echo' => [\n 'type' => Type::string(),\n 'args' => [\n 'message' => Type::nonNull(Type::string()),\n ],\n 'resolve' => function ($root, $args) {\n return $root['prefix'] . $args['message'];\n }\n ],\n ],\n]);\n\n\n\n\n\n(Note: type definition can be expressed in \ndifferent styles\n, \nbut this example uses \ninline\n style for simplicity)\n\n\nThe interesting piece here is \nresolve\n option of field definition. It is responsible for returning \na value of our field. Values of \nscalar\n fields will be directly included in response while values of \n\ncomposite\n fields (objects, interfaces, unions) will be passed down to nested field resolvers \n(not in this example though).\n\n\nNow when our type is ready, let's create GraphQL endpoint file for it \ngraphql.php\n:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Type\\Schema;\n\n$schema = new Schema([\n 'query' => $queryType\n]);\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\ntry {\n $rootValue = ['prefix' => 'You said: '];\n $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);\n $output = $result->toArray();\n} catch (\\Exception $e) {\n $output = [\n 'errors' => [\n [\n 'message' => $e->getMessage()\n ]\n ]\n ];\n}\nheader('Content-Type: application/json');\necho json_encode($output);\n\n\n\n\nOur example is finished. Try it by running:\n\n\nphp -S localhost:8080 graphql.php\ncurl http://localhost:8080 -d '{\"query\": \"query { echo(message: \\\"Hello World\\\") }\" }'\n\n\n\n\nCheck out the full \nsource code\n of this example\nwhich also includes simple mutation.\n\n\nObviously hello world only scratches the surface of what is possible. \nSo check out next example, which is closer to real-world apps.\nOr keep reading about \nschema definition\n.\n\n\nBlog example\n\n\nIt is often easier to start with a full-featured example and then get back to documentation\nfor your own work. \n\n\nCheck out \nBlog example of GraphQL API\n.\nIt is quite close to real-world GraphQL hierarchies. Follow instructions and try it yourself in ~10 minutes.",
"title": "Getting Started"
},
{
"location": "/getting-started/#prerequisites",
"text": "This documentation assumes your familiarity with GraphQL concepts. If it is not the case - \nfirst learn about GraphQL on the official website .",
"title": "Prerequisites"
},
{
"location": "/getting-started/#installation",
"text": "Using composer , simply run: composer require webonyx/graphql-php",
"title": "Installation"
},
{
"location": "/getting-started/#upgrading",
"text": "We try to keep library releases backwards compatible. But when breaking changes are inevitable \nthey are explained in upgrade instructions .",
"title": "Upgrading"
},
{
"location": "/getting-started/#install-tools-optional",
"text": "While it is possible to communicate with GraphQL API using regular HTTP tools it is way \nmore convenient for humans to use GraphiQL - an in-browser \nIDE for exploring GraphQL APIs. It provides syntax-highlighting, auto-completion and auto-generated documentation for \nGraphQL API. The easiest way to use it is to install one of the existing Google Chrome extensions: ChromeiQL GraphiQL Feen Alternatively, you can follow instructions on the GraphiQL \npage and install it locally.",
"title": "Install Tools (optional)"
},
{
"location": "/getting-started/#hello-world",
"text": "Let's create a type system that will be capable to process following simple query: query {\n echo(message: \"Hello World\")\n} To do so we need an object type with field echo : <?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'echo' => [\n 'type' => Type::string(),\n 'args' => [\n 'message' => Type::nonNull(Type::string()),\n ],\n 'resolve' => function ($root, $args) {\n return $root['prefix'] . $args['message'];\n }\n ],\n ],\n]); (Note: type definition can be expressed in different styles , \nbut this example uses inline style for simplicity) The interesting piece here is resolve option of field definition. It is responsible for returning \na value of our field. Values of scalar fields will be directly included in response while values of composite fields (objects, interfaces, unions) will be passed down to nested field resolvers \n(not in this example though). Now when our type is ready, let's create GraphQL endpoint file for it graphql.php : <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Type\\Schema;\n\n$schema = new Schema([\n 'query' => $queryType\n]);\n\n$rawInput = file_get_contents('php://input');\n$input = json_decode($rawInput, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\ntry {\n $rootValue = ['prefix' => 'You said: '];\n $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);\n $output = $result->toArray();\n} catch (\\Exception $e) {\n $output = [\n 'errors' => [\n [\n 'message' => $e->getMessage()\n ]\n ]\n ];\n}\nheader('Content-Type: application/json');\necho json_encode($output); Our example is finished. Try it by running: php -S localhost:8080 graphql.php\ncurl http://localhost:8080 -d '{\"query\": \"query { echo(message: \\\"Hello World\\\") }\" }' Check out the full source code of this example\nwhich also includes simple mutation. Obviously hello world only scratches the surface of what is possible. \nSo check out next example, which is closer to real-world apps.\nOr keep reading about schema definition .",
"title": "Hello World"
},
{
"location": "/getting-started/#blog-example",
"text": "It is often easier to start with a full-featured example and then get back to documentation\nfor your own work. Check out Blog example of GraphQL API .\nIt is quite close to real-world GraphQL hierarchies. Follow instructions and try it yourself in ~10 minutes.",
"title": "Blog example"
},
{
"location": "/complementary-tools/",
"text": "Integrations\n\n\n\n\nIntegration with Relay\n\n\nIntegration with Laravel 5\n + \nRelay Helpers for Laravel\n + \nNuwave Lighthouse\n\n\nSymfony Bundle\n by Overblog\n\n\nOut of the box integration with any PSR-7 compatible framework (like \nSlim\n or \nZend Expressive\n) via \nStandard Server\n\n\n\n\nGraphQL PHP Tools\n\n\n\n\nDefine types with Doctrine ORM annotations (\nfor PHP7.1\n, for \nearlier PHP versions\n)\n\n\nDataLoader PHP\n - as a ready implementation for \ndeferred resolvers\n\n\nPSR 15 compliant middleware\n for the Standard Server (experimental)\n\n\nGraphQL Uploads\n for the Standard Server\n\n\nGraphQL Batch Processor\n - Simple library that provides a builder interface for defining collection, querying, filtering, and post-processing logic of batched data fetches. \n\n\n\n\nGeneral GraphQL Tools\n\n\n\n\nGraphiQL\n - An in-browser IDE for exploring GraphQL\n\n\nChromeiQL\n\n or \nGraphiQL Feen\n -\n GraphiQL as Google Chrome extension",
"title": "Complementary Tools"
},
{
"location": "/complementary-tools/#integrations",
"text": "Integration with Relay Integration with Laravel 5 + Relay Helpers for Laravel + Nuwave Lighthouse Symfony Bundle by Overblog Out of the box integration with any PSR-7 compatible framework (like Slim or Zend Expressive ) via Standard Server",
"title": "Integrations"
},
{
"location": "/complementary-tools/#graphql-php-tools",
"text": "Define types with Doctrine ORM annotations ( for PHP7.1 , for earlier PHP versions ) DataLoader PHP - as a ready implementation for deferred resolvers PSR 15 compliant middleware for the Standard Server (experimental) GraphQL Uploads for the Standard Server GraphQL Batch Processor - Simple library that provides a builder interface for defining collection, querying, filtering, and post-processing logic of batched data fetches.",
"title": "GraphQL PHP Tools"
},
{
"location": "/complementary-tools/#general-graphql-tools",
"text": "GraphiQL - An in-browser IDE for exploring GraphQL ChromeiQL \n or GraphiQL Feen -\n GraphiQL as Google Chrome extension",
"title": "General GraphQL Tools"
},
{
"location": "/type-system/",
"text": "Type System\n\n\nTo start using GraphQL you are expected to implement a type hierarchy and expose it as \nSchema\n. \n\n\nIn graphql-php \ntype\n is an instance of internal class from \n\nGraphQL\\Type\\Definition\n namespace: \nObjectType\n, \n\nInterfaceType\n, \nUnionType\n, \nInputObjectType\n, \n\nScalarType\n, \nEnumType\n (or one of subclasses).\n\n\nBut most of the types in your schema will be \nobject types\n.\n\n\nType Definition Styles\n\n\nSeveral styles of type definitions are supported depending on your preferences.\n\n\nInline definitions:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$myType = new ObjectType([\n 'name' => 'MyType',\n 'fields' => [\n 'id' => Type::id()\n ]\n]);\n\n\n\n\nClass per type:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\nclass MyType extends ObjectType\n{\n public function __construct()\n {\n $config = [\n // Note: 'name' is not needed in this form:\n // it will be inferred from class name by omitting namespace and dropping \"Type\" suffix\n 'fields' => [\n 'id' => Type::id()\n ]\n ];\n parent::__construct($config);\n }\n}\n\n\n\n\nUsing \nGraphQL Type language\n:\n\n\nschema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n greetings(input: HelloInput!): String!\n}\n\ninput HelloInput {\n firstName: String!\n lastName: String\n}\n\n\n\n\nRead more about type language definitions in a \ndedicated docs section\n.\n\n\nType Registry\n\n\nEvery type must be presented in Schema by a single instance (\ngraphql-php\n \nthrows when it discovers several instances with the same \nname\n in the schema).\n\n\nTherefore if you define your type as separate PHP class you must ensure that only one \ninstance of that class is added to the schema.\n\n\nThe typical way to do this is to create a registry of your types:\n\n\n<?php\nnamespace MyApp;\n\nclass TypeRegistry\n{\n private $myAType;\n private $myBType;\n\n public function myAType()\n {\n return $this->myAType ?: ($this->myAType = new MyAType($this));\n }\n\n public function myBType()\n {\n return $this->myBType ?: ($this->myBType = new MyBType($this));\n }\n}\n\n\n\n\nAnd use this registry in type definition:\n\n\n<?php\nnamespace MyApp;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\nclass MyAType extends ObjectType\n{\n public function __construct(TypeRegistry $types) \n {\n parent::__construct([\n 'fields' => [\n 'b' => $types->myBType() \n ]\n ]);\n }\n}\n\n\n\n\nObviously, you can automate this registry as you wish to reduce boilerplate or even \nintroduce Dependency Injection Container if your types have other dependencies.\n\n\nAlternatively, all methods of the registry could be static - then there is no need\nto pass it in constructor - instead just use use \nTypeRegistry::myAType()\n in your \ntype definitions.",
"title": "Introduction"
},
{
"location": "/type-system/#type-system",
"text": "To start using GraphQL you are expected to implement a type hierarchy and expose it as Schema . In graphql-php type is an instance of internal class from GraphQL\\Type\\Definition namespace: ObjectType , InterfaceType , UnionType , InputObjectType , ScalarType , EnumType (or one of subclasses). But most of the types in your schema will be object types .",
"title": "Type System"
},
{
"location": "/type-system/#type-definition-styles",
"text": "Several styles of type definitions are supported depending on your preferences. Inline definitions: <?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$myType = new ObjectType([\n 'name' => 'MyType',\n 'fields' => [\n 'id' => Type::id()\n ]\n]); Class per type: <?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\nclass MyType extends ObjectType\n{\n public function __construct()\n {\n $config = [\n // Note: 'name' is not needed in this form:\n // it will be inferred from class name by omitting namespace and dropping \"Type\" suffix\n 'fields' => [\n 'id' => Type::id()\n ]\n ];\n parent::__construct($config);\n }\n} Using GraphQL Type language : schema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n greetings(input: HelloInput!): String!\n}\n\ninput HelloInput {\n firstName: String!\n lastName: String\n} Read more about type language definitions in a dedicated docs section .",
"title": "Type Definition Styles"
},
{
"location": "/type-system/#type-registry",
"text": "Every type must be presented in Schema by a single instance ( graphql-php \nthrows when it discovers several instances with the same name in the schema). Therefore if you define your type as separate PHP class you must ensure that only one \ninstance of that class is added to the schema. The typical way to do this is to create a registry of your types: <?php\nnamespace MyApp;\n\nclass TypeRegistry\n{\n private $myAType;\n private $myBType;\n\n public function myAType()\n {\n return $this->myAType ?: ($this->myAType = new MyAType($this));\n }\n\n public function myBType()\n {\n return $this->myBType ?: ($this->myBType = new MyBType($this));\n }\n} And use this registry in type definition: <?php\nnamespace MyApp;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\nclass MyAType extends ObjectType\n{\n public function __construct(TypeRegistry $types) \n {\n parent::__construct([\n 'fields' => [\n 'b' => $types->myBType() \n ]\n ]);\n }\n} Obviously, you can automate this registry as you wish to reduce boilerplate or even \nintroduce Dependency Injection Container if your types have other dependencies. Alternatively, all methods of the registry could be static - then there is no need\nto pass it in constructor - instead just use use TypeRegistry::myAType() in your \ntype definitions.",
"title": "Type Registry"
},
{
"location": "/type-system/object-types/",
"text": "Object Type Definition\n\n\nObject Type is the most frequently used primitive in a typical GraphQL application.\n\n\nConceptually Object Type is a collection of Fields. Each field, in turn,\nhas its own type which allows building complex hierarchies.\n\n\nIn \ngraphql-php\n object type is an instance of \nGraphQL\\Type\\Definition\\ObjectType\n \n(or one of it subclasses) which accepts configuration array in constructor:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Examples\\Blog\\Data\\DataSource;\nuse GraphQL\\Examples\\Blog\\Data\\Story;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'description' => 'Our blog visitor',\n 'fields' => [\n 'firstName' => [\n 'type' => Type::string(),\n 'description' => 'User first name'\n ],\n 'email' => Type::string()\n ]\n]);\n\n$blogStory = new ObjectType([\n 'name' => 'Story',\n 'fields' => [\n 'body' => Type::string(),\n 'author' => [\n 'type' => $userType,\n 'description' => 'Story author',\n 'resolve' => function(Story $blogStory) {\n return DataSource::findUser($blogStory->authorId);\n }\n ],\n 'likes' => [\n 'type' => Type::listOf($userType),\n 'description' => 'List of users who liked the story',\n 'args' => [\n 'limit' => [\n 'type' => Type::int(),\n 'description' => 'Limit the number of recent likes returned',\n 'defaultValue' => 10\n ]\n ],\n 'resolve' => function(Story $blogStory, $args) {\n return DataSource::findLikes($blogStory->id, $args['limit']);\n }\n ]\n ]\n]);\n\n\n\n\nThis example uses \ninline\n style for Object Type definitions, but you can also use\n\n\ninheritance or type language\n.\n\n\nConfiguration options\n\n\nObject type constructor expects configuration array. Below is a full list of available options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Unique name of this object type within Schema\n\n\n\n\n\n\nfields\n\n\narray\n or \ncallable\n\n\nRequired\n. An array describing object fields or callable returning such an array. See \nFields\n section below for expected structure of each array entry. See also the section on \nCircular types\n for an explanation of when to use callable for this option.\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this type for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\ninterfaces\n\n\narray\n or \ncallable\n\n\nList of interfaces implemented by this type or callable returning such a list. See \nInterface Types\n for details. See also the section on \nCircular types\n for an explanation of when to use callable for this option.\n\n\n\n\n\n\nisTypeOf\n\n\ncallable\n\n\nfunction($value, $context, \nResolveInfo\n $info)\n Expected to return \ntrue\n if \n$value\n qualifies for this type (see section about \nAbstract Type Resolution\n for explanation).\n\n\n\n\n\n\nresolveField\n\n\ncallable\n\n\nfunction($value, $args, $context, \nResolveInfo\n $info)\n Given the \n$value\n of this type, it is expected to return value for a field defined in \n$info->fieldName\n. A good place to define a type-specific strategy for field resolution. See section on \nData Fetching\n for details.\n\n\n\n\n\n\n\n\nField configuration options\n\n\nBelow is a full list of available field configuration options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Name of the field. When not set - inferred from \nfields\n array key (read about \nshorthand field definition\n below)\n\n\n\n\n\n\ntype\n\n\nType\n\n\nRequired.\n An instance of internal or custom type. Note: type must be represented by a single instance within one schema (see also \nType Registry\n)\n\n\n\n\n\n\nargs\n\n\narray\n\n\nAn array of possible type arguments. Each entry is expected to be an array with keys: \nname\n, \ntype\n, \ndescription\n, \ndefaultValue\n. See \nField Arguments\n section below.\n\n\n\n\n\n\nresolve\n\n\ncallable\n\n\nfunction($value, $args, $context, \nResolveInfo\n $info)\n Given the \n$value\n of this type, it is expected to return actual value of the current field. See section on \nData Fetching\n for details\n\n\n\n\n\n\ncomplexity\n\n\ncallable\n\n\nfunction($childrenComplexity, $args)\n Used to restrict query complexity. The feature is disabled by default, read about \nSecurity\n to use it.\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this field for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\ndeprecationReason\n\n\nstring\n\n\nText describing why this field is deprecated. When not empty - field will not be returned by introspection queries (unless forced)\n\n\n\n\n\n\n\n\nField arguments\n\n\nEvery field on a GraphQL object type can have zero or more arguments, defined in \nargs\n option of field definition.\nEach argument is an array with following options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Name of the argument. When not set - inferred from \nargs\n array key\n\n\n\n\n\n\ntype\n\n\nType\n\n\nRequired.\n Instance of one of \nInput Types\n (\nscalar\n, \nenum\n, \nInputObjectType\n + any combination of those with \nnonNull\n and \nlistOf\n modifiers)\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this argument for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\ndefaultValue\n\n\nscalar\n\n\nDefault value for this argument\n\n\n\n\n\n\n\n\nShorthand field definitions\n\n\nFields can be also defined in \nshorthand\n notation (with only \nname\n and \ntype\n options):\n\n\n'fields' => [\n 'id' => Type::id(),\n 'fieldName' => $fieldType\n]\n\n\n\n\nwhich is equivalent of:\n\n\n'fields' => [\n 'id' => ['type' => Type::id()],\n 'fieldName' => ['type' => $fieldName]\n]\n\n\n\n\nwhich is in turn equivalent of the full form:\n\n\n'fields' => [\n ['name' => 'id', 'type' => Type::id()],\n ['name' => 'fieldName', 'type' => $fieldName]\n]\n\n\n\n\nSame shorthand notation applies to field arguments as well.\n\n\nRecurring and circular types\n\n\nAlmost all real-world applications contain recurring or circular types. \nThink user friends or nested comments for example. \n\n\ngraphql-php\n allows such types, but you have to use \ncallable\n in \noption \nfields\n (and/or \ninterfaces\n).\n\n\nFor example:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$userType = null;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => function() use (&$userType) {\n return [\n 'email' => [\n 'type' => Type::string()\n ],\n 'friends' => [\n 'type' => Type::listOf($userType)\n ]\n ];\n }\n]);\n\n\n\n\nSame example for \ninheritance style of type definitions\n using \nTypeRegistry\n:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\nclass UserType extends ObjectType\n{\n public function __construct()\n {\n $config = [\n 'fields' => function() {\n return [\n 'email' => MyTypes::string(),\n 'friends' => MyTypes::listOf(MyTypes::user())\n ];\n }\n ];\n parent::__construct($config);\n }\n}\n\nclass MyTypes \n{\n private static $user;\n\n public static function user()\n {\n return self::$user ?: (self::$user = new UserType());\n }\n\n public static function string()\n {\n return Type::string();\n }\n\n public static function listOf($type)\n {\n return Type::listOf($type);\n }\n}\n\n\n\n\nField Resolution\n\n\nField resolution is the primary mechanism in \ngraphql-php\n for returning actual data for your fields.\nIt is implemented using \nresolveField\n callable in type definition or \nresolve\n\ncallable in field definition (which has precedence).\n\n\nRead the section on \nData Fetching\n for a complete description of this process.\n\n\nCustom Metadata\n\n\nAll types in \ngraphql-php\n accept configuration array. In some cases, you may be interested in \npassing your own metadata for type or field definition.\n\n\ngraphql-php\n preserves original configuration array in every type or field instance in \npublic property \n$config\n. Use it to implement app-level mappings and definitions.",
"title": "Object Types"
},
{
"location": "/type-system/object-types/#object-type-definition",
"text": "Object Type is the most frequently used primitive in a typical GraphQL application. Conceptually Object Type is a collection of Fields. Each field, in turn,\nhas its own type which allows building complex hierarchies. In graphql-php object type is an instance of GraphQL\\Type\\Definition\\ObjectType \n(or one of it subclasses) which accepts configuration array in constructor: <?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Examples\\Blog\\Data\\DataSource;\nuse GraphQL\\Examples\\Blog\\Data\\Story;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'description' => 'Our blog visitor',\n 'fields' => [\n 'firstName' => [\n 'type' => Type::string(),\n 'description' => 'User first name'\n ],\n 'email' => Type::string()\n ]\n]);\n\n$blogStory = new ObjectType([\n 'name' => 'Story',\n 'fields' => [\n 'body' => Type::string(),\n 'author' => [\n 'type' => $userType,\n 'description' => 'Story author',\n 'resolve' => function(Story $blogStory) {\n return DataSource::findUser($blogStory->authorId);\n }\n ],\n 'likes' => [\n 'type' => Type::listOf($userType),\n 'description' => 'List of users who liked the story',\n 'args' => [\n 'limit' => [\n 'type' => Type::int(),\n 'description' => 'Limit the number of recent likes returned',\n 'defaultValue' => 10\n ]\n ],\n 'resolve' => function(Story $blogStory, $args) {\n return DataSource::findLikes($blogStory->id, $args['limit']);\n }\n ]\n ]\n]); This example uses inline style for Object Type definitions, but you can also use inheritance or type language .",
"title": "Object Type Definition"
},
{
"location": "/type-system/object-types/#configuration-options",
"text": "Object type constructor expects configuration array. Below is a full list of available options: Option Type Notes name string Required. Unique name of this object type within Schema fields array or callable Required . An array describing object fields or callable returning such an array. See Fields section below for expected structure of each array entry. See also the section on Circular types for an explanation of when to use callable for this option. description string Plain-text description of this type for clients (e.g. used by GraphiQL for auto-generated documentation) interfaces array or callable List of interfaces implemented by this type or callable returning such a list. See Interface Types for details. See also the section on Circular types for an explanation of when to use callable for this option. isTypeOf callable function($value, $context, ResolveInfo $info) Expected to return true if $value qualifies for this type (see section about Abstract Type Resolution for explanation). resolveField callable function($value, $args, $context, ResolveInfo $info) Given the $value of this type, it is expected to return value for a field defined in $info->fieldName . A good place to define a type-specific strategy for field resolution. See section on Data Fetching for details.",
"title": "Configuration options"
},
{
"location": "/type-system/object-types/#field-configuration-options",
"text": "Below is a full list of available field configuration options: Option Type Notes name string Required. Name of the field. When not set - inferred from fields array key (read about shorthand field definition below) type Type Required. An instance of internal or custom type. Note: type must be represented by a single instance within one schema (see also Type Registry ) args array An array of possible type arguments. Each entry is expected to be an array with keys: name , type , description , defaultValue . See Field Arguments section below. resolve callable function($value, $args, $context, ResolveInfo $info) Given the $value of this type, it is expected to return actual value of the current field. See section on Data Fetching for details complexity callable function($childrenComplexity, $args) Used to restrict query complexity. The feature is disabled by default, read about Security to use it. description string Plain-text description of this field for clients (e.g. used by GraphiQL for auto-generated documentation) deprecationReason string Text describing why this field is deprecated. When not empty - field will not be returned by introspection queries (unless forced)",
"title": "Field configuration options"
},
{
"location": "/type-system/object-types/#field-arguments",
"text": "Every field on a GraphQL object type can have zero or more arguments, defined in args option of field definition.\nEach argument is an array with following options: Option Type Notes name string Required. Name of the argument. When not set - inferred from args array key type Type Required. Instance of one of Input Types ( scalar , enum , InputObjectType + any combination of those with nonNull and listOf modifiers) description string Plain-text description of this argument for clients (e.g. used by GraphiQL for auto-generated documentation) defaultValue scalar Default value for this argument",
"title": "Field arguments"
},
{
"location": "/type-system/object-types/#shorthand-field-definitions",
"text": "Fields can be also defined in shorthand notation (with only name and type options): 'fields' => [\n 'id' => Type::id(),\n 'fieldName' => $fieldType\n] which is equivalent of: 'fields' => [\n 'id' => ['type' => Type::id()],\n 'fieldName' => ['type' => $fieldName]\n] which is in turn equivalent of the full form: 'fields' => [\n ['name' => 'id', 'type' => Type::id()],\n ['name' => 'fieldName', 'type' => $fieldName]\n] Same shorthand notation applies to field arguments as well.",
"title": "Shorthand field definitions"
},
{
"location": "/type-system/object-types/#recurring-and-circular-types",
"text": "Almost all real-world applications contain recurring or circular types. \nThink user friends or nested comments for example. graphql-php allows such types, but you have to use callable in \noption fields (and/or interfaces ). For example: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$userType = null;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => function() use (&$userType) {\n return [\n 'email' => [\n 'type' => Type::string()\n ],\n 'friends' => [\n 'type' => Type::listOf($userType)\n ]\n ];\n }\n]); Same example for inheritance style of type definitions using TypeRegistry : <?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\nclass UserType extends ObjectType\n{\n public function __construct()\n {\n $config = [\n 'fields' => function() {\n return [\n 'email' => MyTypes::string(),\n 'friends' => MyTypes::listOf(MyTypes::user())\n ];\n }\n ];\n parent::__construct($config);\n }\n}\n\nclass MyTypes \n{\n private static $user;\n\n public static function user()\n {\n return self::$user ?: (self::$user = new UserType());\n }\n\n public static function string()\n {\n return Type::string();\n }\n\n public static function listOf($type)\n {\n return Type::listOf($type);\n }\n}",
"title": "Recurring and circular types"
},
{
"location": "/type-system/object-types/#field-resolution",
"text": "Field resolution is the primary mechanism in graphql-php for returning actual data for your fields.\nIt is implemented using resolveField callable in type definition or resolve \ncallable in field definition (which has precedence). Read the section on Data Fetching for a complete description of this process.",
"title": "Field Resolution"
},
{
"location": "/type-system/object-types/#custom-metadata",
"text": "All types in graphql-php accept configuration array. In some cases, you may be interested in \npassing your own metadata for type or field definition. graphql-php preserves original configuration array in every type or field instance in \npublic property $config . Use it to implement app-level mappings and definitions.",
"title": "Custom Metadata"
},
{
"location": "/type-system/scalar-types/",
"text": "Built-in Scalar Types\n\n\nGraphQL specification describes several built-in scalar types. In \ngraphql-php\n they are \nexposed as static methods of \nGraphQL\\Type\\Definition\\Type\n class:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\n\n// Built-in Scalar types:\nType::string(); // String type\nType::int(); // Int type\nType::float(); // Float type\nType::boolean(); // Boolean type\nType::id(); // ID type\n\n\n\n\nThose methods return instances of \nGraphQL\\Type\\Definition\\ScalarType\n (actually one of subclasses).\nUse them directly in type definitions, or wrap in your \nTypeRegistry\n \n(if you use one).\n\n\nWriting Custom Scalar Types\n\n\nIn addition to built-in scalars, you can define your own scalar types with additional validation. \nTypical examples of such types are \nEmail\n, \nDate\n, \nUrl\n, etc.\n\n\nIn order to implement your own type, you must understand how scalars are presented in GraphQL.\nGraphQL deals with scalars in following cases:\n\n\n\n\n\n\nWhen converting \ninternal representation\n of value returned by your app (e.g. stored in a database \nor hardcoded in the source code) to \nserialized\n representation included in the response.\n\n\n\n\n\n\nWhen converting \ninput value\n passed by a client in variables along with GraphQL query to \n\ninternal representation\n of your app.\n\n\n\n\n\n\nWhen converting \ninput literal value\n hardcoded in GraphQL query (e.g. field argument value) to \nthe \ninternal representation\n of your app.\n\n\n\n\n\n\nThose cases are covered by methods \nserialize\n, \nparseValue\n and \nparseLiteral\n of abstract \nScalarType\n \nclass respectively.\n\n\nHere is an example of a simple \nEmail\n type:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Error\\Error;\nuse GraphQL\\Error\\InvariantViolation;\nuse GraphQL\\Language\\AST\\StringValueNode;\nuse GraphQL\\Type\\Definition\\ScalarType;\nuse GraphQL\\Utils\\Utils;\n\nclass EmailType extends ScalarType\n{\n // Note: name can be omitted. In this case it will be inferred from class name \n // (suffix \"Type\" will be dropped)\n public $name = 'Email';\n\n /**\n * Serializes an internal value to include in a response.\n *\n * @param string $value\n * @return string\n */\n public function serialize($value)\n {\n // Assuming internal representation of email is always correct:\n return $value;\n\n // If it might be incorrect and you want to make sure that only correct values are included\n // in response - use following line instead:\n // if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {\n // throw new InvariantViolation(\"Could not serialize following value as email: \" . Utils::printSafe($value));\n // }\n // return $this->parseValue($value);\n }\n\n /**\n * Parses an externally provided value (query variable) to use as an input\n *\n * @param mixed $value\n * @return mixed\n */\n public function parseValue($value)\n {\n if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {\n throw new Error(\"Cannot represent following value as email: \" . Utils::printSafeJson($value));\n }\n return $value;\n }\n\n /**\n * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input.\n * \n * E.g. \n * {\n * user(email: \"user@example.com\") \n * }\n *\n * @param \\GraphQL\\Language\\AST\\Node $valueNode\n * @return string\n * @throws Error\n */\n public function parseLiteral($valueNode)\n {\n // Note: throwing GraphQL\\Error\\Error vs \\UnexpectedValueException to benefit from GraphQL\n // error location in query:\n if (!$valueNode instanceof StringValueNode) {\n throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]);\n }\n if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) {\n throw new Error(\"Not a valid email\", [$valueNode]);\n }\n return $valueNode->value;\n }\n}\n\n\n\n\nOr with inline style:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\CustomScalarType;\n\n$emailType = new CustomScalarType([\n 'name' => 'Email',\n 'serialize' => function($value) {/* See function body above */},\n 'parseValue' => function($value) {/* See function body above */},\n 'parseLiteral' => function($valueNode) {/* See function body above */},\n]);",
"title": "Scalar Types"
},
{
"location": "/type-system/scalar-types/#built-in-scalar-types",
"text": "GraphQL specification describes several built-in scalar types. In graphql-php they are \nexposed as static methods of GraphQL\\Type\\Definition\\Type class: <?php\nuse GraphQL\\Type\\Definition\\Type;\n\n// Built-in Scalar types:\nType::string(); // String type\nType::int(); // Int type\nType::float(); // Float type\nType::boolean(); // Boolean type\nType::id(); // ID type Those methods return instances of GraphQL\\Type\\Definition\\ScalarType (actually one of subclasses).\nUse them directly in type definitions, or wrap in your TypeRegistry \n(if you use one).",
"title": "Built-in Scalar Types"
},
{
"location": "/type-system/scalar-types/#writing-custom-scalar-types",
"text": "In addition to built-in scalars, you can define your own scalar types with additional validation. \nTypical examples of such types are Email , Date , Url , etc. In order to implement your own type, you must understand how scalars are presented in GraphQL.\nGraphQL deals with scalars in following cases: When converting internal representation of value returned by your app (e.g. stored in a database \nor hardcoded in the source code) to serialized representation included in the response. When converting input value passed by a client in variables along with GraphQL query to internal representation of your app. When converting input literal value hardcoded in GraphQL query (e.g. field argument value) to \nthe internal representation of your app. Those cases are covered by methods serialize , parseValue and parseLiteral of abstract ScalarType \nclass respectively. Here is an example of a simple Email type: <?php\nnamespace MyApp;\n\nuse GraphQL\\Error\\Error;\nuse GraphQL\\Error\\InvariantViolation;\nuse GraphQL\\Language\\AST\\StringValueNode;\nuse GraphQL\\Type\\Definition\\ScalarType;\nuse GraphQL\\Utils\\Utils;\n\nclass EmailType extends ScalarType\n{\n // Note: name can be omitted. In this case it will be inferred from class name \n // (suffix \"Type\" will be dropped)\n public $name = 'Email';\n\n /**\n * Serializes an internal value to include in a response.\n *\n * @param string $value\n * @return string\n */\n public function serialize($value)\n {\n // Assuming internal representation of email is always correct:\n return $value;\n\n // If it might be incorrect and you want to make sure that only correct values are included\n // in response - use following line instead:\n // if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {\n // throw new InvariantViolation(\"Could not serialize following value as email: \" . Utils::printSafe($value));\n // }\n // return $this->parseValue($value);\n }\n\n /**\n * Parses an externally provided value (query variable) to use as an input\n *\n * @param mixed $value\n * @return mixed\n */\n public function parseValue($value)\n {\n if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {\n throw new Error(\"Cannot represent following value as email: \" . Utils::printSafeJson($value));\n }\n return $value;\n }\n\n /**\n * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input.\n * \n * E.g. \n * {\n * user(email: \"user@example.com\") \n * }\n *\n * @param \\GraphQL\\Language\\AST\\Node $valueNode\n * @return string\n * @throws Error\n */\n public function parseLiteral($valueNode)\n {\n // Note: throwing GraphQL\\Error\\Error vs \\UnexpectedValueException to benefit from GraphQL\n // error location in query:\n if (!$valueNode instanceof StringValueNode) {\n throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]);\n }\n if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) {\n throw new Error(\"Not a valid email\", [$valueNode]);\n }\n return $valueNode->value;\n }\n} Or with inline style: <?php\nuse GraphQL\\Type\\Definition\\CustomScalarType;\n\n$emailType = new CustomScalarType([\n 'name' => 'Email',\n 'serialize' => function($value) {/* See function body above */},\n 'parseValue' => function($value) {/* See function body above */},\n 'parseLiteral' => function($valueNode) {/* See function body above */},\n]);",
"title": "Writing Custom Scalar Types"
},
{
"location": "/type-system/enum-types/",
"text": "Enum Type Definition\n\n\nEnumeration types are a special kind of scalar that is restricted to a particular set \nof allowed values. \n\n\nIn \ngraphql-php\n enum type is an instance of \nGraphQL\\Type\\Definition\\EnumType\n \nwhich accepts configuration array in constructor:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => [\n 'value' => 4,\n 'description' => 'Released in 1977.'\n ],\n 'EMPIRE' => [\n 'value' => 5,\n 'description' => 'Released in 1980.'\n ],\n 'JEDI' => [\n 'value' => 6,\n 'description' => 'Released in 1983.'\n ],\n ]\n]);\n\n\n\n\nThis example uses an \ninline\n style for Enum Type definition, but you can also use\n\ninheritance or type language\n.\n\n\nConfiguration options\n\n\nEnum Type constructor accepts an array with following options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Name of the type. When not set - inferred from array key (read about \nshorthand field definition\n below)\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of the type for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\nvalues\n\n\narray\n\n\nList of enumerated items, see below for expected structure of each entry\n\n\n\n\n\n\n\n\nEach entry of \nvalues\n array in turn accepts following options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Name of the item. When not set - inferred from array key (read about \nshorthand field definition\n below)\n\n\n\n\n\n\nvalue\n\n\nmixed\n\n\nInternal representation of enum item in your application (could be any value, including complex objects or callbacks)\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of enum value for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\ndeprecationReason\n\n\nstring\n\n\nText describing why this enum value is deprecated. When not empty - item will not be returned by introspection queries (unless forced)\n\n\n\n\n\n\n\n\nShorthand definitions\n\n\nIf internal representation of enumerated item is the same as item name, then you can use\nfollowing shorthand for definition:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => ['NEWHOPE', 'EMPIRE', 'JEDI']\n]);\n\n\n\n\nwhich is equivalent of:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => ['value' => 'NEWHOPE'], \n 'EMPIRE' => ['value' => 'EMPIRE'], \n 'JEDI' => ['value' => 'JEDI']\n ]\n]);\n\n\n\n\nwhich is in turn equivalent of the full form:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n ['name' => 'NEWHOPE', 'value' => 'NEWHOPE'], \n ['name' => 'EMPIRE', 'value' => 'EMPIRE'], \n ['name' => 'JEDI', 'value' => 'JEDI']\n ]\n]);\n\n\n\n\nField Resolution\n\n\nWhen object field is of Enum Type, field resolver is expected to return an internal \nrepresentation of corresponding Enum item (\nvalue\n in config). \ngraphql-php\n will \nthen serialize this \nvalue\n to \nname\n to include in response:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\EnumType;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => [\n 'value' => 4,\n 'description' => 'Released in 1977.'\n ],\n 'EMPIRE' => [\n 'value' => 5,\n 'description' => 'Released in 1980.'\n ],\n 'JEDI' => [\n 'value' => 6,\n 'description' => 'Released in 1983.'\n ],\n ]\n]);\n\n$heroType = new ObjectType([\n 'name' => 'Hero',\n 'fields' => [\n 'appearsIn' => [\n 'type' => $episodeEnum,\n 'resolve' => function() {\n return 5; // Actual entry in response will be 'appearsIn' => 'EMPIRE'\n }\n ]\n ]\n]);\n\n\n\n\nThe Reverse is true when the enum is used as input type (e.g. as field argument). \nGraphQL will treat enum input as \nname\n and convert it into \nvalue\n before passing to your app.\n\n\nFor example, given object type definition:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$heroType = new ObjectType([\n 'name' => 'Hero',\n 'fields' => [\n 'appearsIn' => [\n 'type' => Type::boolean(),\n 'args' => [\n 'episode' => Type::nonNull($enumType)\n ],\n 'resolve' => function($_value, $args) {\n return $args['episode'] === 5 ? true : false; \n }\n ]\n ]\n]);\n\n\n\n\nThen following query:\n\n\nfragment on Hero {\n appearsInNewHope: appearsIn(NEWHOPE)\n appearsInEmpire: appearsIn(EMPIRE)\n}\n\n\n\n\nwill return:\n\n\n[\n 'appearsInNewHope' => false,\n 'appearsInEmpire' => true\n]",
"title": "Enumeration Types"
},
{
"location": "/type-system/enum-types/#enum-type-definition",
"text": "Enumeration types are a special kind of scalar that is restricted to a particular set \nof allowed values. In graphql-php enum type is an instance of GraphQL\\Type\\Definition\\EnumType \nwhich accepts configuration array in constructor: <?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => [\n 'value' => 4,\n 'description' => 'Released in 1977.'\n ],\n 'EMPIRE' => [\n 'value' => 5,\n 'description' => 'Released in 1980.'\n ],\n 'JEDI' => [\n 'value' => 6,\n 'description' => 'Released in 1983.'\n ],\n ]\n]); This example uses an inline style for Enum Type definition, but you can also use inheritance or type language .",
"title": "Enum Type Definition"
},
{
"location": "/type-system/enum-types/#configuration-options",
"text": "Enum Type constructor accepts an array with following options: Option Type Notes name string Required. Name of the type. When not set - inferred from array key (read about shorthand field definition below) description string Plain-text description of the type for clients (e.g. used by GraphiQL for auto-generated documentation) values array List of enumerated items, see below for expected structure of each entry Each entry of values array in turn accepts following options: Option Type Notes name string Required. Name of the item. When not set - inferred from array key (read about shorthand field definition below) value mixed Internal representation of enum item in your application (could be any value, including complex objects or callbacks) description string Plain-text description of enum value for clients (e.g. used by GraphiQL for auto-generated documentation) deprecationReason string Text describing why this enum value is deprecated. When not empty - item will not be returned by introspection queries (unless forced)",
"title": "Configuration options"
},
{
"location": "/type-system/enum-types/#shorthand-definitions",
"text": "If internal representation of enumerated item is the same as item name, then you can use\nfollowing shorthand for definition: <?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => ['NEWHOPE', 'EMPIRE', 'JEDI']\n]); which is equivalent of: <?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => ['value' => 'NEWHOPE'], \n 'EMPIRE' => ['value' => 'EMPIRE'], \n 'JEDI' => ['value' => 'JEDI']\n ]\n]); which is in turn equivalent of the full form: <?php\nuse GraphQL\\Type\\Definition\\EnumType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n ['name' => 'NEWHOPE', 'value' => 'NEWHOPE'], \n ['name' => 'EMPIRE', 'value' => 'EMPIRE'], \n ['name' => 'JEDI', 'value' => 'JEDI']\n ]\n]);",
"title": "Shorthand definitions"
},
{
"location": "/type-system/enum-types/#field-resolution",
"text": "When object field is of Enum Type, field resolver is expected to return an internal \nrepresentation of corresponding Enum item ( value in config). graphql-php will \nthen serialize this value to name to include in response: <?php\nuse GraphQL\\Type\\Definition\\EnumType;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$episodeEnum = new EnumType([\n 'name' => 'Episode',\n 'description' => 'One of the films in the Star Wars Trilogy',\n 'values' => [\n 'NEWHOPE' => [\n 'value' => 4,\n 'description' => 'Released in 1977.'\n ],\n 'EMPIRE' => [\n 'value' => 5,\n 'description' => 'Released in 1980.'\n ],\n 'JEDI' => [\n 'value' => 6,\n 'description' => 'Released in 1983.'\n ],\n ]\n]);\n\n$heroType = new ObjectType([\n 'name' => 'Hero',\n 'fields' => [\n 'appearsIn' => [\n 'type' => $episodeEnum,\n 'resolve' => function() {\n return 5; // Actual entry in response will be 'appearsIn' => 'EMPIRE'\n }\n ]\n ]\n]); The Reverse is true when the enum is used as input type (e.g. as field argument). \nGraphQL will treat enum input as name and convert it into value before passing to your app. For example, given object type definition: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$heroType = new ObjectType([\n 'name' => 'Hero',\n 'fields' => [\n 'appearsIn' => [\n 'type' => Type::boolean(),\n 'args' => [\n 'episode' => Type::nonNull($enumType)\n ],\n 'resolve' => function($_value, $args) {\n return $args['episode'] === 5 ? true : false; \n }\n ]\n ]\n]); Then following query: fragment on Hero {\n appearsInNewHope: appearsIn(NEWHOPE)\n appearsInEmpire: appearsIn(EMPIRE)\n} will return: [\n 'appearsInNewHope' => false,\n 'appearsInEmpire' => true\n]",
"title": "Field Resolution"
},
{
"location": "/type-system/lists-and-nonnulls/",
"text": "Lists\n\n\ngraphql-php\n provides built-in support for lists. In order to create list type - wrap \nexisting type with \nGraphQL\\Type\\Definition\\Type::listOf()\n modifier:\n\n\n<?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n 'emails' => [\n 'type' => Type::listOf(Type::string()),\n 'resolve' => function() {\n return ['jon@example.com', 'jonny@example.com'];\n }\n ]\n ]\n]);\n\n\n\n\nResolvers for such fields are expected to return \narray\n or instance of PHP's built-in \nTraversable\n \ninterface (\nnull\n is allowed by default too). \n\n\nIf returned value is not of one of these types - \ngraphql-php\n will add an error to result \nand set the field value to \nnull\n (only if the field is nullable, see below for non-null fields).\n\n\nNon-Null fields\n\n\nBy default in GraphQL, every field can have a \nnull\n value. To indicate that some field always \nreturns \nnon-null\n value - use \nGraphQL\\Type\\Definition\\Type::nonNull()\n modifier:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::id()),\n 'resolve' => function() {\n return uniqid();\n }\n ],\n 'emails' => [\n 'type' => Type::nonNull(Type::listOf(Type::string())),\n 'resolve' => function() {\n return ['jon@example.com', 'jonny@example.com'];\n }\n ]\n ]\n]);\n\n\n\n\nIf resolver of non-null field returns \nnull\n, graphql-php will add an error to \nresult and exclude the whole object from the output (an error will bubble to first \nnullable parent field which will be set to \nnull\n).\n\n\nRead the section on \nData Fetching\n for details.",
"title": "Lists and Non-Null"
},
{
"location": "/type-system/lists-and-nonnulls/#lists",
"text": "graphql-php provides built-in support for lists. In order to create list type - wrap \nexisting type with GraphQL\\Type\\Definition\\Type::listOf() modifier: <?php\nnamespace MyApp;\n\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n 'emails' => [\n 'type' => Type::listOf(Type::string()),\n 'resolve' => function() {\n return ['jon@example.com', 'jonny@example.com'];\n }\n ]\n ]\n]); Resolvers for such fields are expected to return array or instance of PHP's built-in Traversable \ninterface ( null is allowed by default too). If returned value is not of one of these types - graphql-php will add an error to result \nand set the field value to null (only if the field is nullable, see below for non-null fields).",
"title": "Lists"
},
{
"location": "/type-system/lists-and-nonnulls/#non-null-fields",
"text": "By default in GraphQL, every field can have a null value. To indicate that some field always \nreturns non-null value - use GraphQL\\Type\\Definition\\Type::nonNull() modifier: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::id()),\n 'resolve' => function() {\n return uniqid();\n }\n ],\n 'emails' => [\n 'type' => Type::nonNull(Type::listOf(Type::string())),\n 'resolve' => function() {\n return ['jon@example.com', 'jonny@example.com'];\n }\n ]\n ]\n]); If resolver of non-null field returns null , graphql-php will add an error to \nresult and exclude the whole object from the output (an error will bubble to first \nnullable parent field which will be set to null ). Read the section on Data Fetching for details.",
"title": "Non-Null fields"
},
{
"location": "/type-system/interfaces/",
"text": "Interface Type Definition\n\n\nAn Interface is an abstract type that includes a certain set of fields that a \ntype must include to implement the interface.\n\n\nIn \ngraphql-php\n interface type is an instance of \nGraphQL\\Type\\Definition\\InterfaceType\n \n(or one of its subclasses) which accepts configuration array in a constructor:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\InterfaceType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$character = new InterfaceType([\n 'name' => 'Character',\n 'description' => 'A character in the Star Wars Trilogy',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the character.',\n ],\n 'name' => [\n 'type' => Type::string(),\n 'description' => 'The name of the character.'\n ]\n ],\n 'resolveType' => function ($value) {\n if ($value->type === 'human') {\n return MyTypes::human(); \n } else {\n return MyTypes::droid();\n }\n }\n]);\n\n\n\n\nThis example uses \ninline\n style for Interface definition, but you can also use\n\n\ninheritance or type language\n.\n\n\nConfiguration options\n\n\nThe constructor of InterfaceType accepts an array. Below is a full list of allowed options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Unique name of this interface type within Schema\n\n\n\n\n\n\nfields\n\n\narray\n\n\nRequired.\n List of fields required to be defined by interface implementors. Same as \nFields for Object Type\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this type for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\nresolveType\n\n\ncallback\n\n\nfunction($value, $context, \nResolveInfo\n $info)\n Receives \n$value\n from resolver of the parent field and returns concrete interface implementor for this \n$value\n.\n\n\n\n\n\n\n\n\nImplementing interface\n\n\nTo implement the Interface simply add it to \ninterfaces\n array of Object Type definition:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'Human',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the character.',\n ],\n 'name' => [\n 'type' => Type::string(),\n 'description' => 'The name of the character.'\n ]\n ],\n 'interfaces' => [\n $character\n ]\n]);\n\n\n\n\nNote that Object Type must include all fields of interface with exact same types \n(including \nnonNull\n specification) and arguments.\n\n\nThe only exception is when object's field type is more specific than the type of this field defined in interface \n(see \nCovariant return types for interface fields\n below)\n\n\nCovariant return types for interface fields\n\n\nObject types implementing interface may change the field type to more specific.\nExample:\n\n\ninterface A {\n field1: A\n}\n\ntype B implements A {\n field1: B\n}\n\n\n\n\nSharing Interface fields\n\n\nSince every Object Type implementing an Interface must have the same set of fields - it often makes \nsense to reuse field definitions of Interface in Object Types:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'Human',\n 'interfaces' => [\n $character\n ],\n 'fields' => [\n 'height' => Type::float(),\n $character->getField('id'),\n $character->getField('name')\n ] \n]);\n\n\n\n\nIn this case, field definitions are created only once (as a part of Interface Type) and then \nreused by all interface implementors. It can save several microseconds and kilobytes + ensures that \nfield definitions of Interface and implementors are always in sync.\n\n\nYet it creates a problem with the resolution of such fields. There are two ways how shared fields could \nbe resolved:\n\n\n\n\n\n\nIf field resolution algorithm is the same for all Interface implementors - you can simply add \n\nresolve\n option to field definition in Interface itself.\n\n\n\n\n\n\nIf field resolution varies for different implementations - you can specify \nresolveField\n \noption in \nObject Type config\n and handle field \nresolutions there \n(Note: \nresolve\n option in field definition has precedence over \nresolveField\n option in object type definition)\n\n\n\n\n\n\nInterface role in data fetching\n\n\nThe only responsibility of interface in Data Fetching process is to return concrete Object Type \nfor given \n$value\n in \nresolveType\n. Then resolution of fields is delegated to resolvers of this \nconcrete Object Type.\n\n\nIf a \nresolveType\n option is omitted, graphql-php will loop through all interface implementors and \nuse their \nisTypeOf\n callback to pick the first suitable one. This is obviously less efficient \nthan single \nresolveType\n call. So it is recommended to define \nresolveType\n whenever possible.",
"title": "Interfaces"
},
{
"location": "/type-system/interfaces/#interface-type-definition",
"text": "An Interface is an abstract type that includes a certain set of fields that a \ntype must include to implement the interface. In graphql-php interface type is an instance of GraphQL\\Type\\Definition\\InterfaceType \n(or one of its subclasses) which accepts configuration array in a constructor: <?php\nuse GraphQL\\Type\\Definition\\InterfaceType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$character = new InterfaceType([\n 'name' => 'Character',\n 'description' => 'A character in the Star Wars Trilogy',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the character.',\n ],\n 'name' => [\n 'type' => Type::string(),\n 'description' => 'The name of the character.'\n ]\n ],\n 'resolveType' => function ($value) {\n if ($value->type === 'human') {\n return MyTypes::human(); \n } else {\n return MyTypes::droid();\n }\n }\n]); This example uses inline style for Interface definition, but you can also use inheritance or type language .",
"title": "Interface Type Definition"
},
{
"location": "/type-system/interfaces/#configuration-options",
"text": "The constructor of InterfaceType accepts an array. Below is a full list of allowed options: Option Type Notes name string Required. Unique name of this interface type within Schema fields array Required. List of fields required to be defined by interface implementors. Same as Fields for Object Type description string Plain-text description of this type for clients (e.g. used by GraphiQL for auto-generated documentation) resolveType callback function($value, $context, ResolveInfo $info) Receives $value from resolver of the parent field and returns concrete interface implementor for this $value .",
"title": "Configuration options"
},
{
"location": "/type-system/interfaces/#implementing-interface",
"text": "To implement the Interface simply add it to interfaces array of Object Type definition: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'Human',\n 'fields' => [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the character.',\n ],\n 'name' => [\n 'type' => Type::string(),\n 'description' => 'The name of the character.'\n ]\n ],\n 'interfaces' => [\n $character\n ]\n]); Note that Object Type must include all fields of interface with exact same types \n(including nonNull specification) and arguments. The only exception is when object's field type is more specific than the type of this field defined in interface \n(see Covariant return types for interface fields below)",
"title": "Implementing interface"
},
{
"location": "/type-system/interfaces/#covariant-return-types-for-interface-fields",
"text": "Object types implementing interface may change the field type to more specific.\nExample: interface A {\n field1: A\n}\n\ntype B implements A {\n field1: B\n}",
"title": "Covariant return types for interface fields"
},
{
"location": "/type-system/interfaces/#sharing-interface-fields",
"text": "Since every Object Type implementing an Interface must have the same set of fields - it often makes \nsense to reuse field definitions of Interface in Object Types: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$humanType = new ObjectType([\n 'name' => 'Human',\n 'interfaces' => [\n $character\n ],\n 'fields' => [\n 'height' => Type::float(),\n $character->getField('id'),\n $character->getField('name')\n ] \n]); In this case, field definitions are created only once (as a part of Interface Type) and then \nreused by all interface implementors. It can save several microseconds and kilobytes + ensures that \nfield definitions of Interface and implementors are always in sync. Yet it creates a problem with the resolution of such fields. There are two ways how shared fields could \nbe resolved: If field resolution algorithm is the same for all Interface implementors - you can simply add resolve option to field definition in Interface itself. If field resolution varies for different implementations - you can specify resolveField \noption in Object Type config and handle field \nresolutions there \n(Note: resolve option in field definition has precedence over resolveField option in object type definition)",
"title": "Sharing Interface fields"
},
{
"location": "/type-system/interfaces/#interface-role-in-data-fetching",
"text": "The only responsibility of interface in Data Fetching process is to return concrete Object Type \nfor given $value in resolveType . Then resolution of fields is delegated to resolvers of this \nconcrete Object Type. If a resolveType option is omitted, graphql-php will loop through all interface implementors and \nuse their isTypeOf callback to pick the first suitable one. This is obviously less efficient \nthan single resolveType call. So it is recommended to define resolveType whenever possible.",
"title": "Interface role in data fetching"
},
{
"location": "/type-system/unions/",
"text": "Union Type Definition\n\n\nA Union is an abstract type that simply enumerates other Object Types. \nThe value of Union Type is actually a value of one of included Object Types.\n\n\nIn \ngraphql-php\n union type is an instance of \nGraphQL\\Type\\Definition\\UnionType\n \n(or one of its subclasses) which accepts configuration array in a constructor:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\UnionType;\n\n$searchResultType = new UnionType([\n 'name' => 'SearchResult',\n 'types' => [\n MyTypes::story(),\n MyTypes::user()\n ],\n 'resolveType' => function($value) {\n if ($value->type === 'story') {\n return MyTypes::story(); \n } else {\n return MyTypes::user();\n }\n }\n]);\n\n\n\n\nThis example uses \ninline\n style for Union definition, but you can also use\n\n\ninheritance or type language\n.\n\n\nConfiguration options\n\n\nThe constructor of UnionType accepts an array. Below is a full list of allowed options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Unique name of this interface type within Schema\n\n\n\n\n\n\ntypes\n\n\narray\n\n\nRequired.\n List of Object Types included in this Union. Note that you can't create a Union type out of Interfaces or other Unions.\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this type for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\nresolveType\n\n\ncallback\n\n\nfunction($value, $context, \nResolveInfo\n $info)\n Receives \n$value\n from resolver of the parent field and returns concrete Object Type for this \n$value\n.",
"title": "Unions"
},
{
"location": "/type-system/unions/#union-type-definition",
"text": "A Union is an abstract type that simply enumerates other Object Types. \nThe value of Union Type is actually a value of one of included Object Types. In graphql-php union type is an instance of GraphQL\\Type\\Definition\\UnionType \n(or one of its subclasses) which accepts configuration array in a constructor: <?php\nuse GraphQL\\Type\\Definition\\UnionType;\n\n$searchResultType = new UnionType([\n 'name' => 'SearchResult',\n 'types' => [\n MyTypes::story(),\n MyTypes::user()\n ],\n 'resolveType' => function($value) {\n if ($value->type === 'story') {\n return MyTypes::story(); \n } else {\n return MyTypes::user();\n }\n }\n]); This example uses inline style for Union definition, but you can also use inheritance or type language .",
"title": "Union Type Definition"
},
{
"location": "/type-system/unions/#configuration-options",
"text": "The constructor of UnionType accepts an array. Below is a full list of allowed options: Option Type Notes name string Required. Unique name of this interface type within Schema types array Required. List of Object Types included in this Union. Note that you can't create a Union type out of Interfaces or other Unions. description string Plain-text description of this type for clients (e.g. used by GraphiQL for auto-generated documentation) resolveType callback function($value, $context, ResolveInfo $info) Receives $value from resolver of the parent field and returns concrete Object Type for this $value .",
"title": "Configuration options"
},
{
"location": "/type-system/input-types/",
"text": "Mutations\n\n\nMutation is just a field of a regular \nObject Type\n with arguments.\nFor GraphQL PHP runtime there is no difference between query fields with arguments and mutations.\nThey are executed \nalmost\n identically. \nTo some extent, Mutation is just a convention described in the GraphQL spec.\n\n\nHere is an example of a mutation operation:\n\n\nmutation CreateReviewForEpisode($ep: EpisodeInput!, $review: ReviewInput!) {\n createReview(episode: $ep, review: $review) {\n stars\n commentary\n }\n}\n\n\n\n\nTo execute such a mutation, you need \nMutation\n type \nat the root of your schema\n:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$myMutationType = new ObjectType([\n 'name' => 'Mutation',\n 'fields' => [\n // List of mutations:\n 'createReview' => [\n 'args' => [\n 'episode' => Type::nonNull($episodeInputType),\n 'review' => Type::nonNull($reviewInputType)\n ],\n 'type' => new ObjectType([\n 'name' => 'CreateReviewOutput',\n 'fields' => [\n 'stars' => ['type' => Type::int()],\n 'commentary' => ['type' => Type::string()]\n ]\n ]),\n ],\n // ... other mutations\n ]\n]);\n\n\n\n\nAs you can see, the only difference from regular object type is the semantics of field names\n(verbs vs nouns).\n\n\nAlso as we see arguments can be of complex types. To leverage the full power of mutations \n(and field arguments in general) you must learn how to create complex input types.\n\n\nAbout Input and Output Types\n\n\nAll types in GraphQL are of two categories: \ninput\n and \noutput\n.\n\n\n\n\n\n\nOutput\n types (or field types) are: \nScalar\n, \nEnum\n, \nObject\n, \n\nInterface\n, \nUnion\n\n\n\n\n\n\nInput\n types (or argument types) are: \nScalar\n, \nEnum\n, InputObject\n\n\n\n\n\n\nObviously, \nNonNull and List\n types belong to both categories depending on their \ninner type.\n\n\nUntil now all examples of field \narguments\n in this documentation were of \nScalar\n or \n\nEnum\n types. But you can also pass complex objects. \n\n\nThis is particularly valuable in case of mutations, where input data might be rather complex.\n\n\nInput Object Type\n\n\nGraphQL specification defines Input Object Type for complex inputs. It is similar to ObjectType\nexcept that it's fields have no \nargs\n or \nresolve\n options and their \ntype\n must be input type.\n\n\nIn graphql-php \nInput Object Type\n is an instance of \nGraphQL\\Type\\Definition\\InputObjectType\n \n(or one of it subclasses) which accepts configuration array in constructor:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\InputObjectType;\n\n$filters = new InputObjectType([\n 'name' => 'StoryFiltersInput',\n 'fields' => [\n 'author' => [\n 'type' => Type::id(),\n 'description' => 'Only show stories with this author id'\n ],\n 'popular' => [\n 'type' => Type::boolean(),\n 'description' => 'Only show popular stories (liked by several people)'\n ],\n 'tags' => [\n 'type' => Type::listOf(Type::string()),\n 'description' => 'Only show stories which contain all of those tags'\n ]\n ]\n]);\n\n\n\n\nEvery field may be of other InputObjectType (thus complex hierarchies of inputs are possible)\n\n\nConfiguration options\n\n\nThe constructor of InputObjectType accepts array with only 3 options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Unique name of this object type within Schema\n\n\n\n\n\n\nfields\n\n\narray\n or \ncallable\n\n\nRequired\n. An array describing object fields or callable returning such an array (see below).\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this type for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\n\n\nEvery field is an array with following entries:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nname\n\n\nstring\n\n\nRequired.\n Name of the input field. When not set - inferred from \nfields\n array key\n\n\n\n\n\n\ntype\n\n\nType\n\n\nRequired.\n Instance of one of \nInput Types\n (\nScalar\n, \nEnum\n, \nInputObjectType\n + any combination of those with \nnonNull\n and \nlistOf\n modifiers)\n\n\n\n\n\n\ndescription\n\n\nstring\n\n\nPlain-text description of this input field for clients (e.g. used by \nGraphiQL\n for auto-generated documentation)\n\n\n\n\n\n\ndefaultValue\n\n\nscalar\n\n\nDefault value of this input field\n\n\n\n\n\n\n\n\nUsing Input Object Type\n\n\nIn the example above we defined our InputObjectType. Now let's use it in one of field arguments:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'stories' => [\n 'type' => Type::listOf($storyType),\n 'args' => [\n 'filters' => [\n 'type' => Type::nonNull($filters),\n 'defaultValue' => [\n 'popular' => true\n ]\n ]\n ],\n 'resolve' => function($rootValue, $args) {\n return DataSource::filterStories($args['filters']);\n }\n ]\n ]\n]);\n\n\n\n\n(note that you can define \ndefaultValue\n for fields with complex inputs as associative array).\n\n\nThen GraphQL query could include filters as literal value:\n\n\n{\n stories(filters: {author: \"1\", popular: false})\n}\n\n\n\n\nOr as query variable:\n\n\nquery($filters: StoryFiltersInput!) {\n stories(filters: $filters)\n}\n\n\n\n\n$variables = [\n 'filters' => [\n \"author\" => \"1\",\n \"popular\" => false\n ]\n];\n\n\n\n\ngraphql-php\n will validate the input against your InputObjectType definition and pass it to your \nresolver as \n$args['filters']",
"title": "Mutations and Input Types"
},
{
"location": "/type-system/input-types/#mutations",
"text": "Mutation is just a field of a regular Object Type with arguments.\nFor GraphQL PHP runtime there is no difference between query fields with arguments and mutations.\nThey are executed almost identically. \nTo some extent, Mutation is just a convention described in the GraphQL spec. Here is an example of a mutation operation: mutation CreateReviewForEpisode($ep: EpisodeInput!, $review: ReviewInput!) {\n createReview(episode: $ep, review: $review) {\n stars\n commentary\n }\n} To execute such a mutation, you need Mutation type at the root of your schema : <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$myMutationType = new ObjectType([\n 'name' => 'Mutation',\n 'fields' => [\n // List of mutations:\n 'createReview' => [\n 'args' => [\n 'episode' => Type::nonNull($episodeInputType),\n 'review' => Type::nonNull($reviewInputType)\n ],\n 'type' => new ObjectType([\n 'name' => 'CreateReviewOutput',\n 'fields' => [\n 'stars' => ['type' => Type::int()],\n 'commentary' => ['type' => Type::string()]\n ]\n ]),\n ],\n // ... other mutations\n ]\n]); As you can see, the only difference from regular object type is the semantics of field names\n(verbs vs nouns). Also as we see arguments can be of complex types. To leverage the full power of mutations \n(and field arguments in general) you must learn how to create complex input types.",
"title": "Mutations"
},
{
"location": "/type-system/input-types/#about-input-and-output-types",
"text": "All types in GraphQL are of two categories: input and output . Output types (or field types) are: Scalar , Enum , Object , Interface , Union Input types (or argument types) are: Scalar , Enum , InputObject Obviously, NonNull and List types belong to both categories depending on their \ninner type. Until now all examples of field arguments in this documentation were of Scalar or Enum types. But you can also pass complex objects. This is particularly valuable in case of mutations, where input data might be rather complex.",
"title": "About Input and Output Types"
},
{
"location": "/type-system/input-types/#input-object-type",
"text": "GraphQL specification defines Input Object Type for complex inputs. It is similar to ObjectType\nexcept that it's fields have no args or resolve options and their type must be input type. In graphql-php Input Object Type is an instance of GraphQL\\Type\\Definition\\InputObjectType \n(or one of it subclasses) which accepts configuration array in constructor: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\InputObjectType;\n\n$filters = new InputObjectType([\n 'name' => 'StoryFiltersInput',\n 'fields' => [\n 'author' => [\n 'type' => Type::id(),\n 'description' => 'Only show stories with this author id'\n ],\n 'popular' => [\n 'type' => Type::boolean(),\n 'description' => 'Only show popular stories (liked by several people)'\n ],\n 'tags' => [\n 'type' => Type::listOf(Type::string()),\n 'description' => 'Only show stories which contain all of those tags'\n ]\n ]\n]); Every field may be of other InputObjectType (thus complex hierarchies of inputs are possible)",
"title": "Input Object Type"
},
{
"location": "/type-system/input-types/#configuration-options",
"text": "The constructor of InputObjectType accepts array with only 3 options: Option Type Notes name string Required. Unique name of this object type within Schema fields array or callable Required . An array describing object fields or callable returning such an array (see below). description string Plain-text description of this type for clients (e.g. used by GraphiQL for auto-generated documentation) Every field is an array with following entries: Option Type Notes name string Required. Name of the input field. When not set - inferred from fields array key type Type Required. Instance of one of Input Types ( Scalar , Enum , InputObjectType + any combination of those with nonNull and listOf modifiers) description string Plain-text description of this input field for clients (e.g. used by GraphiQL for auto-generated documentation) defaultValue scalar Default value of this input field",
"title": "Configuration options"
},
{
"location": "/type-system/input-types/#using-input-object-type",
"text": "In the example above we defined our InputObjectType. Now let's use it in one of field arguments: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'stories' => [\n 'type' => Type::listOf($storyType),\n 'args' => [\n 'filters' => [\n 'type' => Type::nonNull($filters),\n 'defaultValue' => [\n 'popular' => true\n ]\n ]\n ],\n 'resolve' => function($rootValue, $args) {\n return DataSource::filterStories($args['filters']);\n }\n ]\n ]\n]); (note that you can define defaultValue for fields with complex inputs as associative array). Then GraphQL query could include filters as literal value: {\n stories(filters: {author: \"1\", popular: false})\n} Or as query variable: query($filters: StoryFiltersInput!) {\n stories(filters: $filters)\n} $variables = [\n 'filters' => [\n \"author\" => \"1\",\n \"popular\" => false\n ]\n]; graphql-php will validate the input against your InputObjectType definition and pass it to your \nresolver as $args['filters']",
"title": "Using Input Object Type"
},
{
"location": "/type-system/directives/",
"text": "Built-in directives\n\n\nThe directive is a way for a client to give GraphQL server additional context and hints on how to execute\nthe query. The directive can be attached to a field or fragment and can affect the execution of the \nquery in any way the server desires.\n\n\nGraphQL specification includes two built-in directives:\n\n\n\n\n@include(if: Boolean)\n Only include this field or fragment in the result if the argument is \ntrue\n \n\n\n@skip(if: Boolean)\n Skip this field or fragment if the argument is \ntrue\n\n\n\n\nFor example:\n\n\nquery Hero($episode: Episode, $withFriends: Boolean!) {\n hero(episode: $episode) {\n name\n friends @include(if: $withFriends) {\n name\n }\n }\n}\n\n\n\n\nHere if \n$withFriends\n variable is set to \nfalse\n - friends section will be ignored and excluded \nfrom the response. Important implementation detail: those fields will never be executed \n(not just removed from response after execution).\n\n\nCustom directives\n\n\ngraphql-php\n supports custom directives even though their presence does not affect the execution of fields.\nBut you can use \nGraphQL\\Type\\Definition\\ResolveInfo\n \nin field resolvers to modify the output depending on those directives or perform statistics collection.\n\n\nOther use case is your own query validation rules relying on custom directives.\n\n\nIn \ngraphql-php\n custom directive is an instance of \nGraphQL\\Type\\Definition\\Directive\n\n(or one of its subclasses) which accepts an array of following options:\n\n\n<?php\nuse GraphQL\\Language\\DirectiveLocation;\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\Directive;\nuse GraphQL\\Type\\Definition\\FieldArgument;\n\n$trackDirective = new Directive([\n 'name' => 'track',\n 'description' => 'Instruction to record usage of the field by client',\n 'locations' => [\n DirectiveLocation::FIELD,\n ],\n 'args' => [\n new FieldArgument([\n 'name' => 'details',\n 'type' => Type::string(),\n 'description' => 'String with additional details of field usage scenario',\n 'defaultValue' => ''\n ])\n ]\n]);\n\n\n\n\nSee possible directive locations in \n\nGraphQL\\Language\\DirectiveLocation\n.",
"title": "Directives"
},
{
"location": "/type-system/directives/#built-in-directives",
"text": "The directive is a way for a client to give GraphQL server additional context and hints on how to execute\nthe query. The directive can be attached to a field or fragment and can affect the execution of the \nquery in any way the server desires. GraphQL specification includes two built-in directives: @include(if: Boolean) Only include this field or fragment in the result if the argument is true @skip(if: Boolean) Skip this field or fragment if the argument is true For example: query Hero($episode: Episode, $withFriends: Boolean!) {\n hero(episode: $episode) {\n name\n friends @include(if: $withFriends) {\n name\n }\n }\n} Here if $withFriends variable is set to false - friends section will be ignored and excluded \nfrom the response. Important implementation detail: those fields will never be executed \n(not just removed from response after execution).",
"title": "Built-in directives"
},
{
"location": "/type-system/directives/#custom-directives",
"text": "graphql-php supports custom directives even though their presence does not affect the execution of fields.\nBut you can use GraphQL\\Type\\Definition\\ResolveInfo \nin field resolvers to modify the output depending on those directives or perform statistics collection. Other use case is your own query validation rules relying on custom directives. In graphql-php custom directive is an instance of GraphQL\\Type\\Definition\\Directive \n(or one of its subclasses) which accepts an array of following options: <?php\nuse GraphQL\\Language\\DirectiveLocation;\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\Directive;\nuse GraphQL\\Type\\Definition\\FieldArgument;\n\n$trackDirective = new Directive([\n 'name' => 'track',\n 'description' => 'Instruction to record usage of the field by client',\n 'locations' => [\n DirectiveLocation::FIELD,\n ],\n 'args' => [\n new FieldArgument([\n 'name' => 'details',\n 'type' => Type::string(),\n 'description' => 'String with additional details of field usage scenario',\n 'defaultValue' => ''\n ])\n ]\n]); See possible directive locations in GraphQL\\Language\\DirectiveLocation .",
"title": "Custom directives"
},
{
"location": "/type-system/schema/",
"text": "Schema Definition\n\n\nThe schema is a container of your type hierarchy, which accepts root types in a constructor and provides\nmethods for receiving information about your types to internal GrahpQL tools.\n\n\nIn \ngraphql-php\n schema is an instance of \nGraphQL\\Type\\Schema\n \nwhich accepts configuration array in a constructor:\n\n\n<?php\nuse GraphQL\\Type\\Schema;\n\n$schema = new Schema([\n 'query' => $queryType, \n 'mutation' => $mutationType,\n]);\n\n\n\n\nSee possible constructor options \nbelow\n.\n\n\nQuery and Mutation types\n\n\nThe schema consists of two root types:\n\n\n\n\nQuery\n type is a surface of your read API\n\n\nMutation\n type (optional) exposes write API by declaring all possible mutations in your app. \n\n\n\n\nQuery and Mutation types are regular \nobject types\n containing root-level fields \nof your API:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'hello' => [\n 'type' => Type::string(),\n 'resolve' => function() {\n return 'Hello World!';\n }\n ],\n 'hero' => [\n 'type' => $characterInterface,\n 'args' => [\n 'episode' => [\n 'type' => $episodeEnum\n ]\n ],\n 'resolve' => function ($rootValue, $args) {\n return StarWarsData::getHero(isset($args['episode']) ? $args['episode'] : null);\n },\n ]\n ]\n]);\n\n$mutationType = new ObjectType([\n 'name' => 'Mutation',\n 'fields' => [\n 'createReview' => [\n 'type' => $createReviewOutput,\n 'args' => [\n 'episode' => $episodeEnum,\n 'review' => $reviewInputObject\n ],\n 'resolve' => function($val, $args) {\n // TODOC\n }\n ]\n ]\n]);\n\n\n\n\nKeep in mind that other than the special meaning of declaring a surface area of your API, \nthose types are the same as any other \nobject type\n, and their fields work \nexactly the same way.\n\n\nMutation\n type is also just a regular object type. The difference is in semantics. \nField names of Mutation type are usually verbs and they almost always have arguments - quite often \nwith complex input values (see \nMutations and Input Types\n for details).\n\n\nConfiguration Options\n\n\nSchema constructor expects an instance of \nGraphQL\\Type\\SchemaConfig\n \nor an array with following options:\n\n\n\n\n\n\n\n\nOption\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nquery\n\n\nObjectType\n\n\nRequired.\n Object type (usually named \"Query\") containing root-level fields of your read API\n\n\n\n\n\n\nmutation\n\n\nObjectType\n\n\nObject type (usually named \"Mutation\") containing root-level fields of your write API\n\n\n\n\n\n\nsubscription\n\n\nObjectType\n\n\nReserved for future subscriptions implementation. Currently presented for compatibility with introspection query of \ngraphql-js\n, used by various clients (like Relay or GraphiQL)\n\n\n\n\n\n\ndirectives\n\n\nDirective[]\n\n\nA full list of \ndirectives\n supported by your schema. By default, contains built-in \n@skip\n and \n@include\n directives.\n If you pass your own directives and still want to use built-in directives - add them explicitly. For example:\n \narray_merge(GraphQL::getStandardDirectives(), [$myCustomDirective]);\n\n\n\n\n\n\ntypes\n\n\nObjectType[]\n\n\nList of object types which cannot be detected by \ngraphql-php\n during static schema analysis.\nMost often it happens when the object type is never referenced in fields directly but is still a part of a schema because it implements an interface which resolves to this object type in its \nresolveType\n callable. \n Note that you are not required to pass all of your types here - it is simply a workaround for concrete use-case.\n\n\n\n\n\n\ntypeLoader\n\n\ncallable\n\n\nfunction($name)\n Expected to return type instance given the name. Must always return the same instance if called multiple times. See section below on lazy type loading.\n\n\n\n\n\n\n\n\nUsing config class\n\n\nIf you prefer fluid interface for config with auto-completion in IDE and static time validation, \nuse \nGraphQL\\Type\\SchemaConfig\n instead of an array:\n\n\n<?php\nuse GraphQL\\Type\\SchemaConfig;\nuse GraphQL\\Type\\Schema;\n\n$config = SchemaConfig::create()\n ->setQuery($myQueryType)\n ->setTypeLoader($myTypeLoader);\n\n$schema = new Schema($config);\n\n\n\n\nLazy loading of types\n\n\nBy default, the schema will scan all of your type, field and argument definitions to serve GraphQL queries. \nIt may cause performance overhead when there are many types in the schema. \n\n\nIn this case, it is recommended to pass \ntypeLoader\n option to schema constructor and define all \nof your object \nfields\n as callbacks.\n\n\nType loading concept is very similar to PHP class loading, but keep in mind that \ntypeLoader\n must\nalways return the same instance of a type.\n\n\nUsage example:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Schema;\n\nclass Types\n{\n private $types = [];\n\n public function get($name)\n {\n if (!isset($this->types[$name])) {\n $this->types[$name] = $this->{$name}();\n }\n return $this->types[$name];\n }\n\n private function MyTypeA()\n {\n return new ObjectType([\n 'name' => 'MyTypeA',\n 'fields' => function() {\n return [\n 'b' => ['type' => $this->get('MyTypeB')]\n ];\n }\n ]);\n }\n\n private function MyTypeB()\n {\n // ...\n }\n}\n\n$registry = new Types();\n\n$schema = new Schema([\n 'query' => $registry->get('Query'),\n 'typeLoader' => function($name) use ($registry) {\n return $registry->get($name);\n }\n]);\n\n\n\n\nSchema Validation\n\n\nBy default, the schema is created with only shallow validation of type and field definitions\n\n(because validation requires full schema scan and is very costly on bigger schemas).\n\n\nBut there is a special method \nassertValid()\n on schema instance which throws \n\nGraphQL\\Error\\InvariantViolation\n exception when it encounters any error, like:\n\n\n\n\nInvalid types used for fields/arguments\n\n\nMissing interface implementations\n\n\nInvalid interface implementations\n\n\nOther schema errors...\n\n\n\n\nSchema validation is supposed to be used in CLI commands or during build step of your app.\nDon't call it in web requests in production. \n\n\nUsage example:\n\n\n<?php\ntry {\n $schema = new GraphQL\\Type\\Schema([\n 'query' => $myQueryType\n ]);\n $schema->assertValid();\n} catch (GraphQL\\Error\\InvariantViolation $e) {\n echo $e->getMessage();\n}",
"title": "Schema"
},
{
"location": "/type-system/schema/#schema-definition",
"text": "The schema is a container of your type hierarchy, which accepts root types in a constructor and provides\nmethods for receiving information about your types to internal GrahpQL tools. In graphql-php schema is an instance of GraphQL\\Type\\Schema \nwhich accepts configuration array in a constructor: <?php\nuse GraphQL\\Type\\Schema;\n\n$schema = new Schema([\n 'query' => $queryType, \n 'mutation' => $mutationType,\n]); See possible constructor options below .",
"title": "Schema Definition"
},
{
"location": "/type-system/schema/#query-and-mutation-types",
"text": "The schema consists of two root types: Query type is a surface of your read API Mutation type (optional) exposes write API by declaring all possible mutations in your app. Query and Mutation types are regular object types containing root-level fields \nof your API: <?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n 'hello' => [\n 'type' => Type::string(),\n 'resolve' => function() {\n return 'Hello World!';\n }\n ],\n 'hero' => [\n 'type' => $characterInterface,\n 'args' => [\n 'episode' => [\n 'type' => $episodeEnum\n ]\n ],\n 'resolve' => function ($rootValue, $args) {\n return StarWarsData::getHero(isset($args['episode']) ? $args['episode'] : null);\n },\n ]\n ]\n]);\n\n$mutationType = new ObjectType([\n 'name' => 'Mutation',\n 'fields' => [\n 'createReview' => [\n 'type' => $createReviewOutput,\n 'args' => [\n 'episode' => $episodeEnum,\n 'review' => $reviewInputObject\n ],\n 'resolve' => function($val, $args) {\n // TODOC\n }\n ]\n ]\n]); Keep in mind that other than the special meaning of declaring a surface area of your API, \nthose types are the same as any other object type , and their fields work \nexactly the same way. Mutation type is also just a regular object type. The difference is in semantics. \nField names of Mutation type are usually verbs and they almost always have arguments - quite often \nwith complex input values (see Mutations and Input Types for details).",
"title": "Query and Mutation types"
},
{
"location": "/type-system/schema/#configuration-options",
"text": "Schema constructor expects an instance of GraphQL\\Type\\SchemaConfig \nor an array with following options: Option Type Notes query ObjectType Required. Object type (usually named \"Query\") containing root-level fields of your read API mutation ObjectType Object type (usually named \"Mutation\") containing root-level fields of your write API subscription ObjectType Reserved for future subscriptions implementation. Currently presented for compatibility with introspection query of graphql-js , used by various clients (like Relay or GraphiQL) directives Directive[] A full list of directives supported by your schema. By default, contains built-in @skip and @include directives. If you pass your own directives and still want to use built-in directives - add them explicitly. For example: array_merge(GraphQL::getStandardDirectives(), [$myCustomDirective]); types ObjectType[] List of object types which cannot be detected by graphql-php during static schema analysis. Most often it happens when the object type is never referenced in fields directly but is still a part of a schema because it implements an interface which resolves to this object type in its resolveType callable. Note that you are not required to pass all of your types here - it is simply a workaround for concrete use-case. typeLoader callable function($name) Expected to return type instance given the name. Must always return the same instance if called multiple times. See section below on lazy type loading.",
"title": "Configuration Options"
},
{
"location": "/type-system/schema/#using-config-class",
"text": "If you prefer fluid interface for config with auto-completion in IDE and static time validation, \nuse GraphQL\\Type\\SchemaConfig instead of an array: <?php\nuse GraphQL\\Type\\SchemaConfig;\nuse GraphQL\\Type\\Schema;\n\n$config = SchemaConfig::create()\n ->setQuery($myQueryType)\n ->setTypeLoader($myTypeLoader);\n\n$schema = new Schema($config);",
"title": "Using config class"
},
{
"location": "/type-system/schema/#lazy-loading-of-types",
"text": "By default, the schema will scan all of your type, field and argument definitions to serve GraphQL queries. \nIt may cause performance overhead when there are many types in the schema. In this case, it is recommended to pass typeLoader option to schema constructor and define all \nof your object fields as callbacks. Type loading concept is very similar to PHP class loading, but keep in mind that typeLoader must\nalways return the same instance of a type. Usage example: <?php\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Schema;\n\nclass Types\n{\n private $types = [];\n\n public function get($name)\n {\n if (!isset($this->types[$name])) {\n $this->types[$name] = $this->{$name}();\n }\n return $this->types[$name];\n }\n\n private function MyTypeA()\n {\n return new ObjectType([\n 'name' => 'MyTypeA',\n 'fields' => function() {\n return [\n 'b' => ['type' => $this->get('MyTypeB')]\n ];\n }\n ]);\n }\n\n private function MyTypeB()\n {\n // ...\n }\n}\n\n$registry = new Types();\n\n$schema = new Schema([\n 'query' => $registry->get('Query'),\n 'typeLoader' => function($name) use ($registry) {\n return $registry->get($name);\n }\n]);",
"title": "Lazy loading of types"
},
{
"location": "/type-system/schema/#schema-validation",
"text": "By default, the schema is created with only shallow validation of type and field definitions \n(because validation requires full schema scan and is very costly on bigger schemas). But there is a special method assertValid() on schema instance which throws GraphQL\\Error\\InvariantViolation exception when it encounters any error, like: Invalid types used for fields/arguments Missing interface implementations Invalid interface implementations Other schema errors... Schema validation is supposed to be used in CLI commands or during build step of your app.\nDon't call it in web requests in production. Usage example: <?php\ntry {\n $schema = new GraphQL\\Type\\Schema([\n 'query' => $myQueryType\n ]);\n $schema->assertValid();\n} catch (GraphQL\\Error\\InvariantViolation $e) {\n echo $e->getMessage();\n}",
"title": "Schema Validation"
},
{
"location": "/type-system/type-language/",
"text": "Defining your schema\n\n\nSince 0.9.0\n\n\nType language\n is a convenient way to define your schema,\nespecially with IDE autocompletion and syntax validation.\n\n\nHere is a simple schema defined in GraphQL type language (e.g. in a separate \nschema.graphql\n file):\n\n\nschema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n greetings(input: HelloInput!): String!\n}\n\ninput HelloInput {\n firstName: String!\n lastName: String\n}\n\n\n\n\nIn order to create schema instance out of this file, use \n\nGraphQL\\Utils\\BuildSchema\n:\n\n\n<?php\nuse GraphQL\\Utils\\BuildSchema;\n\n$contents = file_get_contents('schema.graphql');\n$schema = BuildSchema::build($contents);\n\n\n\n\nBy default, such schema is created without any resolvers.\n\n\nWe have to rely on \ndefault field resolver\n and \nroot value\n in \norder to execute a query against this schema.\n\n\nPerformance considerations\n\n\nSince 0.10.0\n\n\nMethod \nbuild()\n produces a \nlazy schema\n\nautomatically, so it works efficiently even with very large schemas.\n\n\nBut parsing type definition file on each request is suboptimal, so it is recommended to cache \nintermediate parsed representation of the schema for the production environment:\n\n\n<?php\nuse GraphQL\\Language\\Parser;\nuse GraphQL\\Utils\\BuildSchema;\nuse GraphQL\\Utils\\AST;\n\n$cacheFilename = 'cached_schema.php';\n\nif (!file_exists($cacheFilename)) {\n $document = Parser::parse(file_get_contents('./schema.graphql'));\n file_put_contents($cacheFilename, \"<?php\\nreturn \" . var_export(AST::toArray($document), true));\n} else {\n $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well\n}\n\n$typeConfigDecorator = function () {};\n$schema = BuildSchema::build($document, $typeConfigDecorator);",
"title": "Using Type Language"
},
{
"location": "/type-system/type-language/#defining-your-schema",
"text": "Since 0.9.0 Type language is a convenient way to define your schema,\nespecially with IDE autocompletion and syntax validation. Here is a simple schema defined in GraphQL type language (e.g. in a separate schema.graphql file): schema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n greetings(input: HelloInput!): String!\n}\n\ninput HelloInput {\n firstName: String!\n lastName: String\n} In order to create schema instance out of this file, use GraphQL\\Utils\\BuildSchema : <?php\nuse GraphQL\\Utils\\BuildSchema;\n\n$contents = file_get_contents('schema.graphql');\n$schema = BuildSchema::build($contents); By default, such schema is created without any resolvers. We have to rely on default field resolver and root value in \norder to execute a query against this schema.",
"title": "Defining your schema"
},
{
"location": "/type-system/type-language/#performance-considerations",
"text": "Since 0.10.0 Method build() produces a lazy schema \nautomatically, so it works efficiently even with very large schemas. But parsing type definition file on each request is suboptimal, so it is recommended to cache \nintermediate parsed representation of the schema for the production environment: <?php\nuse GraphQL\\Language\\Parser;\nuse GraphQL\\Utils\\BuildSchema;\nuse GraphQL\\Utils\\AST;\n\n$cacheFilename = 'cached_schema.php';\n\nif (!file_exists($cacheFilename)) {\n $document = Parser::parse(file_get_contents('./schema.graphql'));\n file_put_contents($cacheFilename, \"<?php\\nreturn \" . var_export(AST::toArray($document), true));\n} else {\n $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well\n}\n\n$typeConfigDecorator = function () {};\n$schema = BuildSchema::build($document, $typeConfigDecorator);",
"title": "Performance considerations"
},
{
"location": "/executing-queries/",
"text": "Using Facade Method\n\n\nQuery execution is a complex process involving multiple steps, including query \nparsing\n, \n\nvalidating\n and finally \nexecuting\n against your \nschema\n.\n\n\ngraphql-php\n provides a convenient facade for this process in class \n\nGraphQL\\GraphQL\n:\n\n\n<?php\nuse GraphQL\\GraphQL;\n\n$result = GraphQL::executeQuery(\n $schema, \n $queryString, \n $rootValue = null, \n $context = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $validationRules = null\n);\n\n\n\n\nIt returns an instance of \nGraphQL\\Executor\\ExecutionResult\n \nwhich can be easily converted to array:\n\n\n$serializableResult = $result->toArray();\n\n\n\n\nReturned array contains \ndata\n and \nerrors\n keys, as described by the \n\nGraphQL spec\n. \nThis array is suitable for further serialization (e.g. using \njson_encode\n).\nSee also the section on \nerror handling and formatting\n.\n\n\nDescription of \nexecuteQuery\n method arguments:\n\n\n\n\n\n\n\n\nArgument\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nschema\n\n\nGraphQL\\Type\\Schema\n\n\nRequired.\n Instance of your application \nSchema\n\n\n\n\n\n\nqueryString\n\n\nstring\n or \nGraphQL\\Language\\AST\\DocumentNode\n\n\nRequired.\n Actual GraphQL query string to be parsed, validated and executed. If you parse query elsewhere before executing - pass corresponding AST document here to avoid new parsing.\n\n\n\n\n\n\nrootValue\n\n\nmixed\n\n\nAny value that represents a root of your data graph. It is passed as the 1st argument to field resolvers of \nQuery type\n. Can be omitted or set to null if actual root values are fetched by Query type itself.\n\n\n\n\n\n\ncontext\n\n\nmixed\n\n\nAny value that holds information shared between all field resolvers. Most often they use it to pass currently logged in user, locale details, etc.\nIt will be available as the 3rd argument in all field resolvers. (see section on \nField Definitions\n for reference) \ngraphql-php\n never modifies this value and passes it \nas is\n to all underlying resolvers.\n\n\n\n\n\n\nvariableValues\n\n\narray\n\n\nMap of variable values passed along with query string. See section on \nquery variables on official GraphQL website\n\n\n\n\n\n\noperationName\n\n\nstring\n\n\nAllows the caller to specify which operation in queryString will be run, in cases where queryString contains multiple top-level operations.\n\n\n\n\n\n\nfieldResolver\n\n\ncallable\n\n\nA resolver function to use when one is not provided by the schema. If not provided, the \ndefault field resolver is used\n.\n\n\n\n\n\n\nvalidationRules\n\n\narray\n\n\nA set of rules for query validation step. The default value is all available rules. Empty array would allow skipping query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution)\n\n\n\n\n\n\n\n\nUsing Server\n\n\nIf you are building HTTP GraphQL API, you may prefer our Standard Server \n(compatible with \nexpress-graphql\n). \nIt supports more features out of the box, including parsing HTTP requests, producing a spec-compliant response; \nbatched queries\n; persisted queries.\n\n\nUsage example (with plain PHP):\n\n\n<?php\nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([/* server options, see below */]);\n$server->handleRequest(); // parses PHP globals and emits response\n\n\n\n\nServer also supports \nPSR-7 request/response interfaces\n:\n\n\n<?php\nuse GraphQL\\Server\\StandardServer;\nuse GraphQL\\Executor\\ExecutionResult;\nuse Psr\\Http\\Message\\ServerRequestInterface;\nuse Psr\\Http\\Message\\ResponseInterface;\nuse Psr\\Http\\Message\\StreamInterface;\n\n/** @var ServerRequestInterface $psrRequest */\n/** @var ResponseInterface $psrResponse */\n/** @var StreamInterface $psrBodyStream */\n$server = new StandardServer([/* server options, see below */]);\n$psrResponse = $server->processPsrRequest($psrRequest, $psrResponse, $psrBodyStream);\n\n\n// Alternatively create PSR-7 response yourself:\n\n/** @var ExecutionResult|ExecutionResult[] $result */\n$result = $server->executePsrRequest($psrRequest);\n$psrResponse = new SomePsr7ResponseImplementation(json_encode($result));\n\n\n\n\nPSR-7 is useful when you want to integrate the server into existing framework:\n\n\n\n\nPSR-7 for Laravel\n\n\nSymfony PSR-7 Bridge\n\n\nSlim\n\n\nZend Expressive\n\n\n\n\nServer configuration options\n\n\n\n\n\n\n\n\nArgument\n\n\nType\n\n\nNotes\n\n\n\n\n\n\n\n\n\n\nschema\n\n\nSchema\n\n\nRequired.\n Instance of your application \nSchema\n\n\n\n\n\n\nrootValue\n\n\nmixed\n\n\nAny value that represents a root of your data graph. It is passed as the 1st argument to field resolvers of \nQuery type\n. Can be omitted or set to null if actual root values are fetched by Query type itself.\n\n\n\n\n\n\ncontext\n\n\nmixed\n\n\nAny value that holds information shared between all field resolvers. Most often they use it to pass currently logged in user, locale details, etc.\nIt will be available as the 3rd argument in all field resolvers. (see section on \nField Definitions\n for reference) \ngraphql-php\n never modifies this value and passes it \nas is\n to all underlying resolvers.\n\n\n\n\n\n\nfieldResolver\n\n\ncallable\n\n\nA resolver function to use when one is not provided by the schema. If not provided, the \ndefault field resolver is used\n.\n\n\n\n\n\n\nvalidationRules\n\n\narray\n or \ncallable\n\n\nA set of rules for query validation step. The default value is all available rules. The empty array would allow skipping query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution).\nPass \ncallable\n to return different validation rules for different queries (e.g. empty array for persisted query and a full list of rules for regular queries). When passed, it is expected to have the following signature: \n \nfunction (\nOperationParams\n $params, DocumentNode $node, $operationType): array\n\n\n\n\n\n\nqueryBatching\n\n\nbool\n\n\nFlag indicating whether this server supports query batching (\napollo-style\n).\n Defaults to \nfalse\n\n\n\n\n\n\ndebug\n\n\nint\n\n\nDebug flags. See \ndocs on error debugging\n (flag values are the same).\n\n\n\n\n\n\npersistentQueryLoader\n\n\ncallable\n\n\nA function which is called to fetch actual query when server encounters \nqueryId\n in request vs \nquery\n.\n The server does not implement persistence part (which you will have to build on your own), but it allows you to execute queries which were persisted previously.\n Expected function signature:\n \nfunction ($queryId, \nOperationParams\n $params)\n \nFunction is expected to return query \nstring\n or parsed \nDocumentNode\n \n \nRead more about persisted queries\n.\n\n\n\n\n\n\nerrorFormatter\n\n\ncallable\n\n\nCustom error formatter. See \nerror handling docs\n.\n\n\n\n\n\n\nerrorsHandler\n\n\ncallable\n\n\nCustom errors handler. See \nerror handling docs\n.\n\n\n\n\n\n\npromiseAdapter\n\n\nPromiseAdapter\n\n\nRequired for \nAsync PHP\n only.\n\n\n\n\n\n\n\n\nServer config instance\n\n\nIf you prefer fluid interface for config with autocomplete in IDE and static time validation, \nuse \nGraphQL\\Server\\ServerConfig\n instead of an array:\n\n\n<?php\nuse GraphQL\\Server\\ServerConfig;\nuse GraphQL\\Server\\StandardServer;\n\n$config = ServerConfig::create()\n ->setSchema($schema)\n ->setErrorFormatter($myFormatter)\n ->setDebug($debug)\n;\n\n$server = new StandardServer($config);\n\n\n\n\nQuery batching\n\n\nStandard Server supports query batching (\napollo-style\n).\n\n\nOne of the major benefits of Server over a sequence of \nexecuteQuery()\n calls is that \n\nDeferred resolvers\n won't be isolated in queries.\nSo for example following batch will require single DB request (if user field is deferred):\n\n\n[\n {\n \"query\": \"{user(id: 1)} { id }\"\n },\n {\n \"query\": \"{user(id: 2)} { id }\"\n },\n {\n \"query\": \"{user(id: 3)} { id }\"\n }\n]\n\n\n\n\nTo enable query batching, pass \nqueryBatching\n option in server config:\n\n\n<?php\nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([\n 'queryBatching' => true\n]);\n\n\n\n\nCustom Validation Rules\n\n\nBefore execution, a query is validated using a set of standard rules defined by the GraphQL spec.\nIt is possible to override standard set of rules globally or per execution.\n\n\nAdd rules globally:\n\n\n<?php\nuse GraphQL\\Validator\\Rules;\nuse GraphQL\\Validator\\DocumentValidator;\n\n// Add to standard set of rules globally:\nDocumentValidator::addRule(new Rules\\DisableIntrospection());\n\n\n\n\nCustom rules per execution:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules;\n\n$myValiationRules = array_merge(\n GraphQL::getStandardValidationRules(),\n [\n new Rules\\QueryComplexity(100),\n new Rules\\DisableIntrospection()\n ]\n);\n\n$result = GraphQL::executeQuery(\n $schema, \n $queryString, \n $rootValue = null, \n $context = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $myValiationRules // <-- this will override global validation rules for this request\n);\n\n\n\n\nOr with a standard server:\n\n\n<?php \nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([\n 'validationRules' => $myValiationRules\n]);",
"title": "Executing Queries"
},
{
"location": "/executing-queries/#using-facade-method",
"text": "Query execution is a complex process involving multiple steps, including query parsing , validating and finally executing against your schema . graphql-php provides a convenient facade for this process in class GraphQL\\GraphQL : <?php\nuse GraphQL\\GraphQL;\n\n$result = GraphQL::executeQuery(\n $schema, \n $queryString, \n $rootValue = null, \n $context = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $validationRules = null\n); It returns an instance of GraphQL\\Executor\\ExecutionResult \nwhich can be easily converted to array: $serializableResult = $result->toArray(); Returned array contains data and errors keys, as described by the GraphQL spec . \nThis array is suitable for further serialization (e.g. using json_encode ).\nSee also the section on error handling and formatting . Description of executeQuery method arguments: Argument Type Notes schema GraphQL\\Type\\Schema Required. Instance of your application Schema queryString string or GraphQL\\Language\\AST\\DocumentNode Required. Actual GraphQL query string to be parsed, validated and executed. If you parse query elsewhere before executing - pass corresponding AST document here to avoid new parsing. rootValue mixed Any value that represents a root of your data graph. It is passed as the 1st argument to field resolvers of Query type . Can be omitted or set to null if actual root values are fetched by Query type itself. context mixed Any value that holds information shared between all field resolvers. Most often they use it to pass currently logged in user, locale details, etc. It will be available as the 3rd argument in all field resolvers. (see section on Field Definitions for reference) graphql-php never modifies this value and passes it as is to all underlying resolvers. variableValues array Map of variable values passed along with query string. See section on query variables on official GraphQL website operationName string Allows the caller to specify which operation in queryString will be run, in cases where queryString contains multiple top-level operations. fieldResolver callable A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used . validationRules array A set of rules for query validation step. The default value is all available rules. Empty array would allow skipping query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution)",
"title": "Using Facade Method"
},
{
"location": "/executing-queries/#using-server",
"text": "If you are building HTTP GraphQL API, you may prefer our Standard Server \n(compatible with express-graphql ). \nIt supports more features out of the box, including parsing HTTP requests, producing a spec-compliant response; batched queries ; persisted queries. Usage example (with plain PHP): <?php\nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([/* server options, see below */]);\n$server->handleRequest(); // parses PHP globals and emits response Server also supports PSR-7 request/response interfaces : <?php\nuse GraphQL\\Server\\StandardServer;\nuse GraphQL\\Executor\\ExecutionResult;\nuse Psr\\Http\\Message\\ServerRequestInterface;\nuse Psr\\Http\\Message\\ResponseInterface;\nuse Psr\\Http\\Message\\StreamInterface;\n\n/** @var ServerRequestInterface $psrRequest */\n/** @var ResponseInterface $psrResponse */\n/** @var StreamInterface $psrBodyStream */\n$server = new StandardServer([/* server options, see below */]);\n$psrResponse = $server->processPsrRequest($psrRequest, $psrResponse, $psrBodyStream);\n\n\n// Alternatively create PSR-7 response yourself:\n\n/** @var ExecutionResult|ExecutionResult[] $result */\n$result = $server->executePsrRequest($psrRequest);\n$psrResponse = new SomePsr7ResponseImplementation(json_encode($result)); PSR-7 is useful when you want to integrate the server into existing framework: PSR-7 for Laravel Symfony PSR-7 Bridge Slim Zend Expressive",
"title": "Using Server"
},
{
"location": "/executing-queries/#server-configuration-options",
"text": "Argument Type Notes schema Schema Required. Instance of your application Schema rootValue mixed Any value that represents a root of your data graph. It is passed as the 1st argument to field resolvers of Query type . Can be omitted or set to null if actual root values are fetched by Query type itself. context mixed Any value that holds information shared between all field resolvers. Most often they use it to pass currently logged in user, locale details, etc. It will be available as the 3rd argument in all field resolvers. (see section on Field Definitions for reference) graphql-php never modifies this value and passes it as is to all underlying resolvers. fieldResolver callable A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used . validationRules array or callable A set of rules for query validation step. The default value is all available rules. The empty array would allow skipping query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution). Pass callable to return different validation rules for different queries (e.g. empty array for persisted query and a full list of rules for regular queries). When passed, it is expected to have the following signature: function ( OperationParams $params, DocumentNode $node, $operationType): array queryBatching bool Flag indicating whether this server supports query batching ( apollo-style ). Defaults to false debug int Debug flags. See docs on error debugging (flag values are the same). persistentQueryLoader callable A function which is called to fetch actual query when server encounters queryId in request vs query . The server does not implement persistence part (which you will have to build on your own), but it allows you to execute queries which were persisted previously. Expected function signature: function ($queryId, OperationParams $params) Function is expected to return query string or parsed DocumentNode Read more about persisted queries . errorFormatter callable Custom error formatter. See error handling docs . errorsHandler callable Custom errors handler. See error handling docs . promiseAdapter PromiseAdapter Required for Async PHP only. Server config instance If you prefer fluid interface for config with autocomplete in IDE and static time validation, \nuse GraphQL\\Server\\ServerConfig instead of an array: <?php\nuse GraphQL\\Server\\ServerConfig;\nuse GraphQL\\Server\\StandardServer;\n\n$config = ServerConfig::create()\n ->setSchema($schema)\n ->setErrorFormatter($myFormatter)\n ->setDebug($debug)\n;\n\n$server = new StandardServer($config);",
"title": "Server configuration options"
},
{
"location": "/executing-queries/#query-batching",
"text": "Standard Server supports query batching ( apollo-style ). One of the major benefits of Server over a sequence of executeQuery() calls is that Deferred resolvers won't be isolated in queries.\nSo for example following batch will require single DB request (if user field is deferred): [\n {\n \"query\": \"{user(id: 1)} { id }\"\n },\n {\n \"query\": \"{user(id: 2)} { id }\"\n },\n {\n \"query\": \"{user(id: 3)} { id }\"\n }\n] To enable query batching, pass queryBatching option in server config: <?php\nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([\n 'queryBatching' => true\n]);",
"title": "Query batching"
},
{
"location": "/executing-queries/#custom-validation-rules",
"text": "Before execution, a query is validated using a set of standard rules defined by the GraphQL spec.\nIt is possible to override standard set of rules globally or per execution. Add rules globally: <?php\nuse GraphQL\\Validator\\Rules;\nuse GraphQL\\Validator\\DocumentValidator;\n\n// Add to standard set of rules globally:\nDocumentValidator::addRule(new Rules\\DisableIntrospection()); Custom rules per execution: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules;\n\n$myValiationRules = array_merge(\n GraphQL::getStandardValidationRules(),\n [\n new Rules\\QueryComplexity(100),\n new Rules\\DisableIntrospection()\n ]\n);\n\n$result = GraphQL::executeQuery(\n $schema, \n $queryString, \n $rootValue = null, \n $context = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $myValiationRules // <-- this will override global validation rules for this request\n); Or with a standard server: <?php \nuse GraphQL\\Server\\StandardServer;\n\n$server = new StandardServer([\n 'validationRules' => $myValiationRules\n]);",
"title": "Custom Validation Rules"
},
{
"location": "/data-fetching/",
"text": "Overview\n\n\nGraphQL is data-storage agnostic. You can use any underlying data storage engine, including SQL or NoSQL database, \nplain files or in-memory data structures.\n\n\nIn order to convert the GraphQL query to PHP array, \ngraphql-php\n traverses query fields (using depth-first algorithm) and \nruns special \nresolve\n function on each field. This \nresolve\n function is provided by you as a part of \n\nfield definition\n or \nquery execution call\n.\n\n\nResult returned by \nresolve\n function is directly included in the response (for scalars and enums)\nor passed down to nested fields (for objects).\n\n\nLet's walk through an example. Consider following GraphQL query:\n\n\n{\n lastStory {\n title\n author {\n name\n }\n }\n}\n\n\n\n\nWe need a Schema that can fulfill it. On the very top level the Schema contains Query type:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n\n 'lastStory' => [\n 'type' => $blogStoryType,\n 'resolve' => function() {\n return [\n 'id' => 1,\n 'title' => 'Example blog post',\n 'authorId' => 1\n ];\n }\n ]\n\n ]\n]);\n\n\n\n\nAs we see field \nlastStory\n has \nresolve\n function that is responsible for fetching data.\n\n\nIn our example, we simply return array value, but in the real-world application you would query\nyour database/cache/search index and return the result.\n\n\nSince \nlastStory\n is of composite type \nBlogStory\n this result is passed down to fields of this type:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$blogStoryType = new ObjectType([\n 'name' => 'BlogStory',\n 'fields' => [\n\n 'author' => [\n 'type' => $userType,\n 'resolve' => function($blogStory) {\n $users = [\n 1 => [\n 'id' => 1,\n 'name' => 'Smith'\n ],\n 2 => [\n 'id' => 2,\n 'name' => 'Anderson'\n ]\n ];\n return $users[$blogStory['authorId']];\n }\n ],\n\n 'title' => [\n 'type' => Type::string()\n ]\n\n ]\n]);\n\n\n\n\nHere \n$blogStory\n is the array returned by \nlastStory\n field above. \n\n\nAgain: in the real-world applications you would fetch user data from data store by \nauthorId\n and return it.\nAlso, note that you don't have to return arrays. You can return any value, \ngraphql-php\n will pass it untouched\nto nested resolvers.\n\n\nBut then the question appears - field \ntitle\n has no \nresolve\n option. How is it resolved?\n\n\nThere is a default resolver for all fields. When you define your own \nresolve\n function\nfor a field you simply override this default resolver.\n\n\nDefault Field Resolver\n\n\ngraphql-php\n provides following default field resolver:\n\n\n<?php\nfunction defaultFieldResolver($source, $args, $context, \\GraphQL\\Type\\Definition\\ResolveInfo $info)\n{\n $fieldName = $info->fieldName;\n $property = null;\n\n if (is_array($source) || $source instanceof \\ArrayAccess) {\n if (isset($source[$fieldName])) {\n $property = $source[$fieldName];\n }\n } else if (is_object($source)) {\n if (isset($source->{$fieldName})) {\n $property = $source->{$fieldName};\n }\n }\n\n return $property instanceof \\Closure ? $property($source, $args, $context) : $property;\n}\n\n\n\n\nAs you see it returns value by key (for arrays) or property (for objects). \nIf the value is not set - it returns \nnull\n.\n\n\nTo override the default resolver, pass it as an argument of \nexecuteQuery\n call.\n\n\nDefault Field Resolver per Type\n\n\nSometimes it might be convenient to set default field resolver per type. You can do so by providing\n\nresolveField option in type config\n. For example:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\ResolveInfo;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n\n 'name' => Type::string(),\n 'email' => Type::string()\n\n ],\n 'resolveField' => function(User $user, $args, $context, ResolveInfo $info) {\n switch ($info->fieldName) {\n case 'name':\n return $user->getName();\n case 'email':\n return $user->getEmail();\n default:\n return null;\n }\n }\n]);\n\n\n\n\nKeep in mind that \nfield resolver\n has precedence over \ndefault field resolver per type\n which in turn\n has precedence over \ndefault field resolver\n.\n\n\nSolving N+1 Problem\n\n\nSince: 0.9.0\n\n\nOne of the most annoying problems with data fetching is a so-called \n\nN+1 problem\n. \n\nConsider following GraphQL query:\n\n\n{\n topStories(limit: 10) {\n title\n author {\n name\n email\n }\n }\n}\n\n\n\n\nNaive field resolution process would require up to 10 calls to the underlying data store to fetch authors for all 10 stories.\n\n\ngraphql-php\n provides tools to mitigate this problem: it allows you to defer actual field resolution to a later stage \nwhen one batched query could be executed instead of 10 distinct queries.\n\n\nHere is an example of \nBlogStory\n resolver for field \nauthor\n that uses deferring:\n\n\n<?php\n'resolve' => function($blogStory) {\n MyUserBuffer::add($blogStory['authorId']);\n\n return new GraphQL\\Deferred(function () use ($blogStory) {\n MyUserBuffer::loadBuffered();\n return MyUserBuffer::get($blogStory['authorId']);\n });\n}\n\n\n\n\nIn this example, we fill up the buffer with 10 author ids first. Then \ngraphql-php\n continues \nresolving other non-deferred fields until there are none of them left.\n\n\nAfter that, it calls closures wrapped by \nGraphQL\\Deferred\n which in turn load all buffered \nids once (using SQL IN(?), Redis MGET or other similar tools) and returns final field value.\n\n\nOriginally this approach was advocated by Facebook in their \nDataloader\n\nproject. This solution enables very interesting optimizations at no cost. Consider the following query:\n\n\n{\n topStories(limit: 10) {\n author {\n email\n }\n }\n category {\n stories(limit: 10) {\n author {\n email\n }\n }\n }\n}\n\n\n\n\nEven though \nauthor\n field is located on different levels of the query - it can be buffered in the same buffer.\nIn this example, only one query will be executed for all story authors comparing to 20 queries\nin a naive implementation.\n\n\nAsync PHP\n\n\nSince: 0.10.0 (version 0.9.0 had slightly different API which still works, but is deprecated)\n\n\nIf your project runs in an environment that supports async operations \n(like HHVM, ReactPHP, Icicle.io, appserver.io, PHP threads, etc) \nyou can leverage the power of your platform to resolve some fields asynchronously.\n\n\nThe only requirement: your platform must support the concept of Promises compatible with\n\nPromises A+\n specification.\n\n\nTo start using this feature, switch facade method for query execution from \n\nexecuteQuery\n to \npromiseToExecute\n:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Executor\\ExecutionResult;\n\n$promise = GraphQL::promiseToExecute(\n $promiseAdapter,\n $schema, \n $queryString, \n $rootValue = null, \n $contextValue = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $validationRules = null\n);\n$promise->then(function(ExecutionResult $result) {\n return $result->toArray();\n});\n\n\n\n\nWhere \n$promiseAdapter\n is an instance of:\n\n\n\n\n\n\nFor \nReactPHP\n (requires \nreact/promise\n as composer dependency): \n \n \nGraphQL\\Executor\\Promise\\Adapter\\ReactPromiseAdapter\n\n\n\n\n\n\nOther platforms: write your own class implementing interface: \n \n \nGraphQL\\Executor\\Promise\\PromiseAdapter\n. \n\n\n\n\n\n\nThen your \nresolve\n functions should return promises of your platform instead of \nGraphQL\\Deferred\ns.",
"title": "Fetching Data"
},
{
"location": "/data-fetching/#overview",
"text": "GraphQL is data-storage agnostic. You can use any underlying data storage engine, including SQL or NoSQL database, \nplain files or in-memory data structures. In order to convert the GraphQL query to PHP array, graphql-php traverses query fields (using depth-first algorithm) and \nruns special resolve function on each field. This resolve function is provided by you as a part of field definition or query execution call . Result returned by resolve function is directly included in the response (for scalars and enums)\nor passed down to nested fields (for objects). Let's walk through an example. Consider following GraphQL query: {\n lastStory {\n title\n author {\n name\n }\n }\n} We need a Schema that can fulfill it. On the very top level the Schema contains Query type: <?php\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$queryType = new ObjectType([\n 'name' => 'Query',\n 'fields' => [\n\n 'lastStory' => [\n 'type' => $blogStoryType,\n 'resolve' => function() {\n return [\n 'id' => 1,\n 'title' => 'Example blog post',\n 'authorId' => 1\n ];\n }\n ]\n\n ]\n]); As we see field lastStory has resolve function that is responsible for fetching data. In our example, we simply return array value, but in the real-world application you would query\nyour database/cache/search index and return the result. Since lastStory is of composite type BlogStory this result is passed down to fields of this type: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$blogStoryType = new ObjectType([\n 'name' => 'BlogStory',\n 'fields' => [\n\n 'author' => [\n 'type' => $userType,\n 'resolve' => function($blogStory) {\n $users = [\n 1 => [\n 'id' => 1,\n 'name' => 'Smith'\n ],\n 2 => [\n 'id' => 2,\n 'name' => 'Anderson'\n ]\n ];\n return $users[$blogStory['authorId']];\n }\n ],\n\n 'title' => [\n 'type' => Type::string()\n ]\n\n ]\n]); Here $blogStory is the array returned by lastStory field above. Again: in the real-world applications you would fetch user data from data store by authorId and return it.\nAlso, note that you don't have to return arrays. You can return any value, graphql-php will pass it untouched\nto nested resolvers. But then the question appears - field title has no resolve option. How is it resolved? There is a default resolver for all fields. When you define your own resolve function\nfor a field you simply override this default resolver.",
"title": "Overview"
},
{
"location": "/data-fetching/#default-field-resolver",
"text": "graphql-php provides following default field resolver: <?php\nfunction defaultFieldResolver($source, $args, $context, \\GraphQL\\Type\\Definition\\ResolveInfo $info)\n{\n $fieldName = $info->fieldName;\n $property = null;\n\n if (is_array($source) || $source instanceof \\ArrayAccess) {\n if (isset($source[$fieldName])) {\n $property = $source[$fieldName];\n }\n } else if (is_object($source)) {\n if (isset($source->{$fieldName})) {\n $property = $source->{$fieldName};\n }\n }\n\n return $property instanceof \\Closure ? $property($source, $args, $context) : $property;\n} As you see it returns value by key (for arrays) or property (for objects). \nIf the value is not set - it returns null . To override the default resolver, pass it as an argument of executeQuery call.",
"title": "Default Field Resolver"
},
{
"location": "/data-fetching/#default-field-resolver-per-type",
"text": "Sometimes it might be convenient to set default field resolver per type. You can do so by providing resolveField option in type config . For example: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\ResolveInfo;\n\n$userType = new ObjectType([\n 'name' => 'User',\n 'fields' => [\n\n 'name' => Type::string(),\n 'email' => Type::string()\n\n ],\n 'resolveField' => function(User $user, $args, $context, ResolveInfo $info) {\n switch ($info->fieldName) {\n case 'name':\n return $user->getName();\n case 'email':\n return $user->getEmail();\n default:\n return null;\n }\n }\n]); Keep in mind that field resolver has precedence over default field resolver per type which in turn\n has precedence over default field resolver .",
"title": "Default Field Resolver per Type"
},
{
"location": "/data-fetching/#solving-n1-problem",
"text": "Since: 0.9.0 One of the most annoying problems with data fetching is a so-called N+1 problem . \nConsider following GraphQL query: {\n topStories(limit: 10) {\n title\n author {\n name\n email\n }\n }\n} Naive field resolution process would require up to 10 calls to the underlying data store to fetch authors for all 10 stories. graphql-php provides tools to mitigate this problem: it allows you to defer actual field resolution to a later stage \nwhen one batched query could be executed instead of 10 distinct queries. Here is an example of BlogStory resolver for field author that uses deferring: <?php\n'resolve' => function($blogStory) {\n MyUserBuffer::add($blogStory['authorId']);\n\n return new GraphQL\\Deferred(function () use ($blogStory) {\n MyUserBuffer::loadBuffered();\n return MyUserBuffer::get($blogStory['authorId']);\n });\n} In this example, we fill up the buffer with 10 author ids first. Then graphql-php continues \nresolving other non-deferred fields until there are none of them left. After that, it calls closures wrapped by GraphQL\\Deferred which in turn load all buffered \nids once (using SQL IN(?), Redis MGET or other similar tools) and returns final field value. Originally this approach was advocated by Facebook in their Dataloader \nproject. This solution enables very interesting optimizations at no cost. Consider the following query: {\n topStories(limit: 10) {\n author {\n email\n }\n }\n category {\n stories(limit: 10) {\n author {\n email\n }\n }\n }\n} Even though author field is located on different levels of the query - it can be buffered in the same buffer.\nIn this example, only one query will be executed for all story authors comparing to 20 queries\nin a naive implementation.",
"title": "Solving N+1 Problem"
},
{
"location": "/data-fetching/#async-php",
"text": "Since: 0.10.0 (version 0.9.0 had slightly different API which still works, but is deprecated) If your project runs in an environment that supports async operations \n(like HHVM, ReactPHP, Icicle.io, appserver.io, PHP threads, etc) \nyou can leverage the power of your platform to resolve some fields asynchronously. The only requirement: your platform must support the concept of Promises compatible with Promises A+ specification. To start using this feature, switch facade method for query execution from executeQuery to promiseToExecute : <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Executor\\ExecutionResult;\n\n$promise = GraphQL::promiseToExecute(\n $promiseAdapter,\n $schema, \n $queryString, \n $rootValue = null, \n $contextValue = null, \n $variableValues = null, \n $operationName = null,\n $fieldResolver = null,\n $validationRules = null\n);\n$promise->then(function(ExecutionResult $result) {\n return $result->toArray();\n}); Where $promiseAdapter is an instance of: For ReactPHP (requires react/promise as composer dependency): \n GraphQL\\Executor\\Promise\\Adapter\\ReactPromiseAdapter Other platforms: write your own class implementing interface: \n GraphQL\\Executor\\Promise\\PromiseAdapter . Then your resolve functions should return promises of your platform instead of GraphQL\\Deferred s.",
"title": "Async PHP"
},
{
"location": "/error-handling/",
"text": "Errors in GraphQL\n\n\nQuery execution process never throws exceptions. Instead, all errors are caught and collected. \nAfter execution, they are available in \n$errors\n prop of \n\nGraphQL\\Executor\\ExecutionResult\n.\n\n\nWhen the result is converted to a serializable array using its \ntoArray()\n method, all errors are \nconverted to arrays as well using default error formatting (see below). \n\n\nAlternatively, you can apply \ncustom error filtering and formatting\n\nfor your specific requirements.\n\n\nDefault Error formatting\n\n\nBy default, each error entry is converted to an associative array with following structure:\n\n\n<?php\n[\n 'message' => 'Error message',\n 'category' => 'graphql',\n 'locations' => [\n ['line' => 1, 'column' => 2]\n ],\n 'path' => [\n 'listField',\n 0,\n 'fieldWithException'\n ]\n];\n\n\n\n\nEntry at key \nlocations\n points to a character in query string which caused the error.\nIn some cases (like deep fragment fields) locations will include several entries to track down \nthe path to field with the error in query.\n\n\nEntry at key \npath\n exists only for errors caused by exceptions thrown in resolvers. \nIt contains a path from the very root field to actual field value producing an error \n(including indexes for list types and field names for composite types). \n\n\nInternal errors\n\n\nAs of version \n0.10.0\n, all exceptions thrown in resolvers are reported with generic message \n\"Internal server error\"\n.\nThis is done to avoid information leak in production environments (e.g. database connection errors, file access errors, etc).\n\n\nOnly exceptions implementing interface \nGraphQL\\Error\\ClientAware\n and claiming themselves as \nsafe\n will \nbe reported with a full error message.\n\n\nFor example:\n\n\n<?php\nuse GraphQL\\Error\\ClientAware;\n\nclass MySafeException extends \\Exception implements ClientAware\n{\n public function isClientSafe()\n {\n return true;\n }\n\n public function getCategory()\n {\n return 'businessLogic';\n }\n}\n\n\n\n\nWhen such exception is thrown it will be reported with a full error message:\n\n\n<?php\n[\n 'message' => 'My reported error',\n 'category' => 'businessLogic',\n 'locations' => [\n ['line' => 10, 'column' => 2]\n ],\n 'path' => [\n 'path',\n 'to',\n 'fieldWithException'\n ]\n];\n\n\n\n\nTo change default \n\"Internal server error\"\n message to something else, use: \n\n\nGraphQL\\Error\\FormattedError::setInternalErrorMessage(\"Unexpected error\");\n\n\n\n\nDebugging tools\n\n\nDuring development or debugging use \n$result->toArray(true)\n to add \ndebugMessage\n key to \neach formatted error entry. If you also want to add exception trace - pass flags instead:\n\n\nuse GraphQL\\Error\\Debug;\n$debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE;\n$result = GraphQL::executeQuery(/*args*/)->toArray($debug);\n\n\n\n\nThis will make each error entry to look like this:\n\n\n<?php\n[\n 'debugMessage' => 'Actual exception message',\n 'message' => 'Internal server error',\n 'category' => 'internal',\n 'locations' => [\n ['line' => 10, 'column' => 2]\n ],\n 'path' => [\n 'listField',\n 0,\n 'fieldWithException'\n ],\n 'trace' => [\n /* Formatted original exception trace */\n ]\n];\n\n\n\n\nIf you prefer first resolver exception to be re-thrown, use following flags:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Error\\Debug;\n$debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::RETHROW_INTERNAL_EXCEPTIONS;\n\n// Following will throw if there was an exception in resolver during execution:\n$result = GraphQL::executeQuery(/*args*/)->toArray($debug); \n\n\n\n\nCustom Error Handling and Formatting\n\n\nIt is possible to define custom \nformatter\n and \nhandler\n for result errors.\n\n\nFormatter\n is responsible for converting instances of \nGraphQL\\Error\\Error\n \nto an array. \nHandler\n is useful for error filtering and logging. \n\n\nFor example, these are default formatter and handler:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Error\\Error;\nuse GraphQL\\Error\\FormattedError;\n\n$myErrorFormatter = function(Error $error) {\n return FormattedError::createFromException($error);\n};\n\n$myErrorHandler = function(array $errors, callable $formatter) {\n return array_map($formatter, $errors);\n};\n\n$result = GraphQL::executeQuery(/* $args */)\n ->setErrorFormatter($myErrorFormatter)\n ->setErrorsHandler($myErrorHandler)\n ->toArray(); \n\n\n\n\nNote that when you pass \ndebug flags\n to \ntoArray()\n your custom formatter will still be \ndecorated with same debugging information mentioned above.\n\n\nSchema Errors\n\n\nSo far we only covered errors which occur during query execution process. But schema definition can \nalso throw \nGraphQL\\Error\\InvariantViolation\n if there is an error in one of type definitions.\n\n\nUsually such errors mean that there is some logical error in your schema and it is the only case \nwhen it makes sense to return \n500\n error code for GraphQL endpoint:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Type\\Schema;\nuse GraphQL\\Error\\FormattedError;\n\ntry {\n $schema = new Schema([\n // ...\n ]);\n\n $body = GraphQL::executeQuery($schema, $query);\n $status = 200;\n} catch(\\Exception $e) {\n $body = [\n 'errors' => [FormattedError::createFromException($e)]\n ];\n $status = 500;\n}\n\nheader('Content-Type: application/json', true, $status);\necho json_encode($body);",
"title": "Handling Errors"
},
{
"location": "/error-handling/#errors-in-graphql",
"text": "Query execution process never throws exceptions. Instead, all errors are caught and collected. \nAfter execution, they are available in $errors prop of GraphQL\\Executor\\ExecutionResult . When the result is converted to a serializable array using its toArray() method, all errors are \nconverted to arrays as well using default error formatting (see below). Alternatively, you can apply custom error filtering and formatting \nfor your specific requirements.",
"title": "Errors in GraphQL"
},
{
"location": "/error-handling/#default-error-formatting",
"text": "By default, each error entry is converted to an associative array with following structure: <?php\n[\n 'message' => 'Error message',\n 'category' => 'graphql',\n 'locations' => [\n ['line' => 1, 'column' => 2]\n ],\n 'path' => [\n 'listField',\n 0,\n 'fieldWithException'\n ]\n]; Entry at key locations points to a character in query string which caused the error.\nIn some cases (like deep fragment fields) locations will include several entries to track down \nthe path to field with the error in query. Entry at key path exists only for errors caused by exceptions thrown in resolvers. \nIt contains a path from the very root field to actual field value producing an error \n(including indexes for list types and field names for composite types). Internal errors As of version 0.10.0 , all exceptions thrown in resolvers are reported with generic message \"Internal server error\" .\nThis is done to avoid information leak in production environments (e.g. database connection errors, file access errors, etc). Only exceptions implementing interface GraphQL\\Error\\ClientAware and claiming themselves as safe will \nbe reported with a full error message. For example: <?php\nuse GraphQL\\Error\\ClientAware;\n\nclass MySafeException extends \\Exception implements ClientAware\n{\n public function isClientSafe()\n {\n return true;\n }\n\n public function getCategory()\n {\n return 'businessLogic';\n }\n} When such exception is thrown it will be reported with a full error message: <?php\n[\n 'message' => 'My reported error',\n 'category' => 'businessLogic',\n 'locations' => [\n ['line' => 10, 'column' => 2]\n ],\n 'path' => [\n 'path',\n 'to',\n 'fieldWithException'\n ]\n]; To change default \"Internal server error\" message to something else, use: GraphQL\\Error\\FormattedError::setInternalErrorMessage(\"Unexpected error\");",
"title": "Default Error formatting"
},
{
"location": "/error-handling/#debugging-tools",
"text": "During development or debugging use $result->toArray(true) to add debugMessage key to \neach formatted error entry. If you also want to add exception trace - pass flags instead: use GraphQL\\Error\\Debug;\n$debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE;\n$result = GraphQL::executeQuery(/*args*/)->toArray($debug); This will make each error entry to look like this: <?php\n[\n 'debugMessage' => 'Actual exception message',\n 'message' => 'Internal server error',\n 'category' => 'internal',\n 'locations' => [\n ['line' => 10, 'column' => 2]\n ],\n 'path' => [\n 'listField',\n 0,\n 'fieldWithException'\n ],\n 'trace' => [\n /* Formatted original exception trace */\n ]\n]; If you prefer first resolver exception to be re-thrown, use following flags: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Error\\Debug;\n$debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::RETHROW_INTERNAL_EXCEPTIONS;\n\n// Following will throw if there was an exception in resolver during execution:\n$result = GraphQL::executeQuery(/*args*/)->toArray($debug);",
"title": "Debugging tools"
},
{
"location": "/error-handling/#custom-error-handling-and-formatting",
"text": "It is possible to define custom formatter and handler for result errors. Formatter is responsible for converting instances of GraphQL\\Error\\Error \nto an array. Handler is useful for error filtering and logging. For example, these are default formatter and handler: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Error\\Error;\nuse GraphQL\\Error\\FormattedError;\n\n$myErrorFormatter = function(Error $error) {\n return FormattedError::createFromException($error);\n};\n\n$myErrorHandler = function(array $errors, callable $formatter) {\n return array_map($formatter, $errors);\n};\n\n$result = GraphQL::executeQuery(/* $args */)\n ->setErrorFormatter($myErrorFormatter)\n ->setErrorsHandler($myErrorHandler)\n ->toArray(); Note that when you pass debug flags to toArray() your custom formatter will still be \ndecorated with same debugging information mentioned above.",
"title": "Custom Error Handling and Formatting"
},
{
"location": "/error-handling/#schema-errors",
"text": "So far we only covered errors which occur during query execution process. But schema definition can \nalso throw GraphQL\\Error\\InvariantViolation if there is an error in one of type definitions. Usually such errors mean that there is some logical error in your schema and it is the only case \nwhen it makes sense to return 500 error code for GraphQL endpoint: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Type\\Schema;\nuse GraphQL\\Error\\FormattedError;\n\ntry {\n $schema = new Schema([\n // ...\n ]);\n\n $body = GraphQL::executeQuery($schema, $query);\n $status = 200;\n} catch(\\Exception $e) {\n $body = [\n 'errors' => [FormattedError::createFromException($e)]\n ];\n $status = 500;\n}\n\nheader('Content-Type: application/json', true, $status);\necho json_encode($body);",
"title": "Schema Errors"
},
{
"location": "/security/",
"text": "Query Complexity Analysis\n\n\nThis is a PHP port of \nQuery Complexity Analysis\n in Sangria implementation.\n\n\nComplexity analysis is a separate validation rule which calculates query complexity score before execution.\nEvery field in the query gets a default score 1 (including ObjectType nodes). Total complexity of the \nquery is the sum of all field scores. For example, the complexity of introspection query is \n109\n.\n\n\nIf this score exceeds a threshold, a query is not executed and an error is returned instead.\n\n\nComplexity analysis is disabled by default. To enabled it, add validation rule:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\QueryComplexity;\nuse GraphQL\\Validator\\DocumentValidator;\n\n$rule = new QueryComplexity($maxQueryComplexity = 100);\nDocumentValidator::addRule($rule);\n\nGraphQL::executeQuery(/*...*/);\n\n\n\n\nThis will set the rule globally. Alternatively, you can provide validation rules \nper execution\n.\n\n\nTo customize field score add \ncomplexity\n function to field definition:\n\n\n<?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$type = new ObjectType([\n 'name' => 'MyType',\n 'fields' => [\n 'someList' => [\n 'type' => Type::listOf(Type::string()),\n 'args' => [\n 'limit' => [\n 'type' => Type::int(),\n 'defaultValue' => 10\n ]\n ],\n 'complexity' => function($childrenComplexity, $args) {\n return $childrenComplexity * $args['limit'];\n }\n ]\n ]\n]);\n\n\n\n\nLimiting Query Depth\n\n\nThis is a PHP port of \nLimiting Query Depth\n in Sangria implementation.\nFor example, max depth of the introspection query is \n7\n.\n\n\nIt is disabled by default. To enable it, add following validation rule:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\QueryDepth;\nuse GraphQL\\Validator\\DocumentValidator;\n\n$rule = new QueryDepth($maxDepth = 10);\nDocumentValidator::addRule($rule);\n\nGraphQL::executeQuery(/*...*/);\n\n\n\n\nThis will set the rule globally. Alternatively, you can provide validation rules \nper execution\n.\n\n\nDisabling Introspection\n\n\nIntrospection\n is a mechanism for fetching schema structure.\nIt is used by tools like GraphiQL for auto-completion, query validation, etc.\n\n\nIntrospection is enabled by default. It means that anybody can get a full description of your schema by \nsending a special query containing meta fields \n__type\n and \n__schema\n .\n\n\nIf you are not planning to expose your API to the general public, it makes sense to disable this feature.\n\n\nGraphQL PHP provides you separate validation rule which prohibits queries that contain \n\n__type\n or \n__schema\n fields. To disable introspection, add following rule:\n\n\n<?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\DisableIntrospection;\nuse GraphQL\\Validator\\DocumentValidator;\n\nDocumentValidator::addRule(new DisableIntrospection());\n\nGraphQL::executeQuery(/*...*/);\n\n\n\n\nThis will set the rule globally. Alternatively, you can provide validation rules \nper execution\n.",
"title": "Security"
},
{
"location": "/security/#query-complexity-analysis",
"text": "This is a PHP port of Query Complexity Analysis in Sangria implementation. Complexity analysis is a separate validation rule which calculates query complexity score before execution.\nEvery field in the query gets a default score 1 (including ObjectType nodes). Total complexity of the \nquery is the sum of all field scores. For example, the complexity of introspection query is 109 . If this score exceeds a threshold, a query is not executed and an error is returned instead. Complexity analysis is disabled by default. To enabled it, add validation rule: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\QueryComplexity;\nuse GraphQL\\Validator\\DocumentValidator;\n\n$rule = new QueryComplexity($maxQueryComplexity = 100);\nDocumentValidator::addRule($rule);\n\nGraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution . To customize field score add complexity function to field definition: <?php\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Definition\\ObjectType;\n\n$type = new ObjectType([\n 'name' => 'MyType',\n 'fields' => [\n 'someList' => [\n 'type' => Type::listOf(Type::string()),\n 'args' => [\n 'limit' => [\n 'type' => Type::int(),\n 'defaultValue' => 10\n ]\n ],\n 'complexity' => function($childrenComplexity, $args) {\n return $childrenComplexity * $args['limit'];\n }\n ]\n ]\n]);",
"title": "Query Complexity Analysis"
},
{
"location": "/security/#limiting-query-depth",
"text": "This is a PHP port of Limiting Query Depth in Sangria implementation.\nFor example, max depth of the introspection query is 7 . It is disabled by default. To enable it, add following validation rule: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\QueryDepth;\nuse GraphQL\\Validator\\DocumentValidator;\n\n$rule = new QueryDepth($maxDepth = 10);\nDocumentValidator::addRule($rule);\n\nGraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution .",
"title": "Limiting Query Depth"
},
{
"location": "/security/#disabling-introspection",
"text": "Introspection is a mechanism for fetching schema structure.\nIt is used by tools like GraphiQL for auto-completion, query validation, etc. Introspection is enabled by default. It means that anybody can get a full description of your schema by \nsending a special query containing meta fields __type and __schema . If you are not planning to expose your API to the general public, it makes sense to disable this feature. GraphQL PHP provides you separate validation rule which prohibits queries that contain __type or __schema fields. To disable introspection, add following rule: <?php\nuse GraphQL\\GraphQL;\nuse GraphQL\\Validator\\Rules\\DisableIntrospection;\nuse GraphQL\\Validator\\DocumentValidator;\n\nDocumentValidator::addRule(new DisableIntrospection());\n\nGraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution .",
"title": "Disabling Introspection"
},
{
"location": "/how-it-works/",
"text": "Overview\n\n\nFollowing reading describes implementation details of query execution process. It may clarify some \ninternals of GraphQL runtime but is not required to use it.\n\n\nParsing\n\n\nTODOC\n\n\nValidating\n\n\nTODOC\n\n\nExecuting\n\n\nTODOC\n\n\nErrors explained\n\n\nThere are 3 types of errors in GraphQL:\n\n\n\n\nSyntax\n: query has invalid syntax and could not be parsed;\n\n\nValidation\n: query is incompatible with type system (e.g. unknown field is requested);\n\n\nExecution\n: occurs when some field resolver throws (or returns unexpected value).\n\n\n\n\nObviously, when \nSyntax\n or \nValidation\n error is detected - the process is interrupted and \nthe query is not executed.\n\n\nExecution process never throws exceptions. Instead, all errors are caught and collected in \nexecution result.\n\n\nGraphQL is forgiving to \nExecution\n errors which occur in resolvers of nullable fields. \nIf such field throws or returns unexpected value the value of the field in response will be simply \nreplaced with \nnull\n and error entry will be registered.\n\n\nIf an exception is thrown in the non-null field - error bubbles up to the first nullable field. \nThis nullable field is replaced with \nnull\n and error entry is added to the result. \nIf all fields up to the root are non-null - \ndata\n entry will be removed from the result\n\nand only \nerrors\n key will be presented.",
"title": "How it works"
},
{
"location": "/how-it-works/#overview",
"text": "Following reading describes implementation details of query execution process. It may clarify some \ninternals of GraphQL runtime but is not required to use it.",
"title": "Overview"
},
{
"location": "/how-it-works/#parsing",
"text": "TODOC",
"title": "Parsing"
},
{
"location": "/how-it-works/#validating",
"text": "TODOC",
"title": "Validating"
},
{
"location": "/how-it-works/#executing",
"text": "TODOC",
"title": "Executing"
},
{
"location": "/how-it-works/#errors-explained",
"text": "There are 3 types of errors in GraphQL: Syntax : query has invalid syntax and could not be parsed; Validation : query is incompatible with type system (e.g. unknown field is requested); Execution : occurs when some field resolver throws (or returns unexpected value). Obviously, when Syntax or Validation error is detected - the process is interrupted and \nthe query is not executed. Execution process never throws exceptions. Instead, all errors are caught and collected in \nexecution result. GraphQL is forgiving to Execution errors which occur in resolvers of nullable fields. \nIf such field throws or returns unexpected value the value of the field in response will be simply \nreplaced with null and error entry will be registered. If an exception is thrown in the non-null field - error bubbles up to the first nullable field. \nThis nullable field is replaced with null and error entry is added to the result. \nIf all fields up to the root are non-null - data entry will be removed from the result \nand only errors key will be presented.",
"title": "Errors explained"
},
{
"location": "/reference/",
"text": "GraphQL\\GraphQL\n\n\nThis is the primary facade for fulfilling GraphQL operations.\nSee \nrelated documentation\n.\n\n\nClass Methods:\n \n\n\n/**\n * Executes graphql query.\n *\n * More sophisticated GraphQL servers, such as those which persist queries,\n * may wish to separate the validation and execution phases to a static time\n * tooling step, and a server runtime step.\n *\n * Available options:\n *\n * schema:\n * The GraphQL type system to use when validating and executing a query.\n * source:\n * A GraphQL language formatted string representing the requested operation.\n * rootValue:\n * The value provided as the first argument to resolver functions on the top\n * level type (e.g. the query object type).\n * context:\n * The value provided as the third argument to all resolvers.\n * Use this to pass current session, user data, etc\n * variableValues:\n * A mapping of variable name to runtime value to use for all variables\n * defined in the requestString.\n * operationName:\n * The name of the operation to use if requestString contains multiple\n * possible operations. Can be omitted if requestString contains only\n * one operation.\n * fieldResolver:\n * A resolver function to use when one is not provided by the schema.\n * If not provided, the default field resolver is used (which looks for a\n * value on the source value with the field's name).\n * validationRules:\n * A set of rules for query validation step. Default value is all available rules.\n * Empty array would allow to skip query validation (may be convenient for persisted\n * queries which are validated before persisting and assumed valid during execution)\n *\n * @api\n * @param \\GraphQL\\Type\\Schema $schema\n * @param string|DocumentNode $source\n * @param mixed $rootValue\n * @param mixed $context\n * @param array|null $variableValues\n * @param string|null $operationName\n * @param callable $fieldResolver\n * @param array $validationRules\n *\n * @return ExecutionResult\n */\nstatic function executeQuery(\n GraphQL\\Type\\Schema $schema,\n $source,\n $rootValue = null,\n $context = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null,\n array $validationRules = null\n)\n\n\n\n\n/**\n * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise.\n * Useful for Async PHP platforms.\n *\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @param \\GraphQL\\Type\\Schema $schema\n * @param string|DocumentNode $source\n * @param mixed $rootValue\n * @param mixed $context\n * @param array|null $variableValues\n * @param string|null $operationName\n * @param callable $fieldResolver\n * @param array $validationRules\n *\n * @return Promise\n */\nstatic function promiseToExecute(\n GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter,\n GraphQL\\Type\\Schema $schema,\n $source,\n $rootValue = null,\n $context = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null,\n array $validationRules = null\n)\n\n\n\n\n/**\n * Returns directives defined in GraphQL spec\n *\n * @api\n * @return Directive[]\n */\nstatic function getStandardDirectives()\n\n\n\n\n/**\n * Returns types defined in GraphQL spec\n *\n * @api\n * @return Type[]\n */\nstatic function getStandardTypes()\n\n\n\n\n/**\n * Returns standard validation rules implementing GraphQL spec\n *\n * @api\n * @return AbstractValidationRule[]\n */\nstatic function getStandardValidationRules()\n\n\n\n\nGraphQL\\Type\\Definition\\Type\n\n\nRegistry of standard GraphQL types\nand a base class for all other types.\n\n\nClass Methods:\n \n\n\n/**\n * @api\n * @return IDType\n */\nstatic function id()\n\n\n\n\n/**\n * @api\n * @return StringType\n */\nstatic function string()\n\n\n\n\n/**\n * @api\n * @return BooleanType\n */\nstatic function boolean()\n\n\n\n\n/**\n * @api\n * @return IntType\n */\nstatic function int()\n\n\n\n\n/**\n * @api\n * @return FloatType\n */\nstatic function float()\n\n\n\n\n/**\n * @api\n * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType\n * @return ListOfType\n */\nstatic function listOf($wrappedType)\n\n\n\n\n/**\n * @api\n * @param ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType $wrappedType\n * @return NonNull\n */\nstatic function nonNull($wrappedType)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isInputType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isOutputType($type)\n\n\n\n\n/**\n * @api\n * @param $type\n * @return bool\n */\nstatic function isLeafType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isCompositeType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isAbstractType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType\n */\nstatic function getNullableType($type)\n\n\n\n\n/**\n * @api\n * @param Type $type\n * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType\n */\nstatic function getNamedType($type)\n\n\n\n\nGraphQL\\Type\\Definition\\ResolveInfo\n\n\nStructure containing information useful for field resolution process.\nPassed as 3rd argument to every field resolver. See \ndocs on field resolving (data fetching)\n.\n\n\nClass Props:\n \n\n\n/**\n * The name of the field being resolved\n *\n * @api\n * @var string\n */\npublic $fieldName;\n\n/**\n * AST of all nodes referencing this field in the query.\n *\n * @api\n * @var FieldNode[]\n */\npublic $fieldNodes;\n\n/**\n * Expected return type of the field being resolved\n *\n * @api\n * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull\n */\npublic $returnType;\n\n/**\n * Parent type of the field being resolved\n *\n * @api\n * @var ObjectType\n */\npublic $parentType;\n\n/**\n * Path to this field from the very root value\n *\n * @api\n * @var array\n */\npublic $path;\n\n/**\n * Instance of a schema used for execution\n *\n * @api\n * @var Schema\n */\npublic $schema;\n\n/**\n * AST of all fragments defined in query\n *\n * @api\n * @var FragmentDefinitionNode[]\n */\npublic $fragments;\n\n/**\n * Root value passed to query execution\n *\n * @api\n * @var mixed\n */\npublic $rootValue;\n\n/**\n * AST of operation definition node (query, mutation)\n *\n * @api\n * @var OperationDefinitionNode\n */\npublic $operation;\n\n/**\n * Array of variables passed to query execution\n *\n * @api\n * @var array\n */\npublic $variableValues;\n\n\n\n\nClass Methods:\n \n\n\n/**\n * Helper method that returns names of all fields selected in query for\n * $this->fieldName up to $depth levels\n *\n * Example:\n * query MyQuery{\n * {\n * root {\n * id,\n * nested {\n * nested1\n * nested2 {\n * nested3\n * }\n * }\n * }\n * }\n *\n * Given this ResolveInfo instance is a part of \"root\" field resolution, and $depth === 1,\n * method will return:\n * [\n * 'id' => true,\n * 'nested' => [\n * nested1 => true,\n * nested2 => true\n * ]\n * ]\n *\n * Warning: this method it is a naive implementation which does not take into account\n * conditional typed fragments. So use it with care for fields of interface and union types.\n *\n * @api\n * @param int $depth How many levels to include in output\n * @return array\n */\nfunction getFieldSelection($depth = 0)\n\n\n\n\nGraphQL\\Language\\DirectiveLocation\n\n\nList of available directive locations\n\n\nClass Constants:\n \n\n\nconst QUERY = \"QUERY\";\nconst MUTATION = \"MUTATION\";\nconst SUBSCRIPTION = \"SUBSCRIPTION\";\nconst FIELD = \"FIELD\";\nconst FRAGMENT_DEFINITION = \"FRAGMENT_DEFINITION\";\nconst FRAGMENT_SPREAD = \"FRAGMENT_SPREAD\";\nconst INLINE_FRAGMENT = \"INLINE_FRAGMENT\";\nconst SCHEMA = \"SCHEMA\";\nconst SCALAR = \"SCALAR\";\nconst OBJECT = \"OBJECT\";\nconst FIELD_DEFINITION = \"FIELD_DEFINITION\";\nconst ARGUMENT_DEFINITION = \"ARGUMENT_DEFINITION\";\nconst IFACE = \"INTERFACE\";\nconst UNION = \"UNION\";\nconst ENUM = \"ENUM\";\nconst ENUM_VALUE = \"ENUM_VALUE\";\nconst INPUT_OBJECT = \"INPUT_OBJECT\";\nconst INPUT_FIELD_DEFINITION = \"INPUT_FIELD_DEFINITION\";\n\n\n\n\nGraphQL\\Type\\SchemaConfig\n\n\nSchema configuration class.\nCould be passed directly to schema constructor. List of options accepted by \ncreate\n method is\n\ndescribed in docs\n.\n\n\nUsage example:\n\n\n$config = SchemaConfig::create()\n ->setQuery($myQueryType)\n ->setTypeLoader($myTypeLoader);\n\n$schema = new Schema($config);\n\n\n\nClass Methods:\n \n\n\n/**\n * Converts an array of options to instance of SchemaConfig\n * (or just returns empty config when array is not passed).\n *\n * @api\n * @param array $options\n * @return SchemaConfig\n */\nstatic function create(array $options = [])\n\n\n\n\n/**\n * @api\n * @param ObjectType $query\n * @return SchemaConfig\n */\nfunction setQuery($query)\n\n\n\n\n/**\n * @api\n * @param ObjectType $mutation\n * @return SchemaConfig\n */\nfunction setMutation($mutation)\n\n\n\n\n/**\n * @api\n * @param ObjectType $subscription\n * @return SchemaConfig\n */\nfunction setSubscription($subscription)\n\n\n\n\n/**\n * @api\n * @param Type[]|callable $types\n * @return SchemaConfig\n */\nfunction setTypes($types)\n\n\n\n\n/**\n * @api\n * @param Directive[] $directives\n * @return SchemaConfig\n */\nfunction setDirectives(array $directives)\n\n\n\n\n/**\n * @api\n * @param callable $typeLoader\n * @return SchemaConfig\n */\nfunction setTypeLoader(callable $typeLoader)\n\n\n\n\n/**\n * @api\n * @return ObjectType\n */\nfunction getQuery()\n\n\n\n\n/**\n * @api\n * @return ObjectType\n */\nfunction getMutation()\n\n\n\n\n/**\n * @api\n * @return ObjectType\n */\nfunction getSubscription()\n\n\n\n\n/**\n * @api\n * @return Type[]\n */\nfunction getTypes()\n\n\n\n\n/**\n * @api\n * @return Directive[]\n */\nfunction getDirectives()\n\n\n\n\n/**\n * @api\n * @return callable\n */\nfunction getTypeLoader()\n\n\n\n\nGraphQL\\Type\\Schema\n\n\nSchema Definition (see \nrelated docs\n)\n\n\nA Schema is created by supplying the root types of each type of operation:\nquery, mutation (optional) and subscription (optional). A schema definition is\nthen supplied to the validator and executor. Usage Example:\n\n\n$schema = new GraphQL\\Type\\Schema([\n 'query' => $MyAppQueryRootType,\n 'mutation' => $MyAppMutationRootType,\n]);\n\n\n\nOr using Schema Config instance:\n\n\n$config = GraphQL\\Type\\SchemaConfig::create()\n ->setQuery($MyAppQueryRootType)\n ->setMutation($MyAppMutationRootType);\n\n$schema = new GraphQL\\Type\\Schema($config);\n\n\n\nClass Methods:\n \n\n\n/**\n * Schema constructor.\n *\n * @api\n * @param array|SchemaConfig $config\n */\nfunction __construct($config)\n\n\n\n\n/**\n * Returns schema query type\n *\n * @api\n * @return ObjectType\n */\nfunction getQueryType()\n\n\n\n\n/**\n * Returns schema mutation type\n *\n * @api\n * @return ObjectType|null\n */\nfunction getMutationType()\n\n\n\n\n/**\n * Returns schema subscription\n *\n * @api\n * @return ObjectType|null\n */\nfunction getSubscriptionType()\n\n\n\n\n/**\n * @api\n * @return SchemaConfig\n */\nfunction getConfig()\n\n\n\n\n/**\n * Returns array of all types in this schema. Keys of this array represent type names, values are instances\n * of corresponding type definitions\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @return Type[]\n */\nfunction getTypeMap()\n\n\n\n\n/**\n * Returns type by it's name\n *\n * @api\n * @param string $name\n * @return Type\n */\nfunction getType($name)\n\n\n\n\n/**\n * Returns all possible concrete types for given abstract type\n * (implementations for interfaces and members of union type for unions)\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @param AbstractType $abstractType\n * @return ObjectType[]\n */\nfunction getPossibleTypes(GraphQL\\Type\\Definition\\AbstractType $abstractType)\n\n\n\n\n/**\n * Returns true if object type is concrete type of given abstract type\n * (implementation for interfaces and members of union type for unions)\n *\n * @api\n * @param AbstractType $abstractType\n * @param ObjectType $possibleType\n * @return bool\n */\nfunction isPossibleType(\n GraphQL\\Type\\Definition\\AbstractType $abstractType,\n GraphQL\\Type\\Definition\\ObjectType $possibleType\n)\n\n\n\n\n/**\n * Returns a list of directives supported by this schema\n *\n * @api\n * @return Directive[]\n */\nfunction getDirectives()\n\n\n\n\n/**\n * Returns instance of directive by name\n *\n * @api\n * @param $name\n * @return Directive\n */\nfunction getDirective($name)\n\n\n\n\n/**\n * Validates schema.\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @return InvariantViolation[]|Error[]\n */\nfunction validate()\n\n\n\n\n/**\n * Validates schema.\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @throws InvariantViolation\n */\nfunction assertValid()\n\n\n\n\nGraphQL\\Language\\Parser\n\n\nParses string containing GraphQL query or \ntype definition\n to Abstract Syntax Tree.\n\n\nClass Methods:\n \n\n\n/**\n * Given a GraphQL source, parses it into a `GraphQL\\Language\\AST\\DocumentNode`.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * Available options:\n *\n * noLocation: boolean,\n * (By default, the parser creates AST nodes that know the location\n * in the source that they correspond to. This configuration flag\n * disables that behavior for performance or testing.)\n *\n * experimentalFragmentVariables: boolean,\n * (If enabled, the parser will understand and parse variable definitions\n * contained in a fragment definition. They'll be represented in the\n * `variableDefinitions` field of the FragmentDefinitionNode.\n *\n * The syntax is identical to normal, query-defined variables. For example:\n *\n * fragment A($var: Boolean = false) on T {\n * ...\n * }\n *\n * Note: this feature is experimental and may change or be removed in the\n * future.)\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return DocumentNode\n * @throws SyntaxError\n */\nstatic function parse($source, array $options = [])\n\n\n\n\n/**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::valueFromAST()`.\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode\n */\nstatic function parseValue($source, array $options = [])\n\n\n\n\n/**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::typeFromAST()`.\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return ListTypeNode|NameNode|NonNullTypeNode\n */\nstatic function parseType($source, array $options = [])\n\n\n\n\nGraphQL\\Language\\Printer\n\n\nPrints AST to string. Capable of printing GraphQL queries and Type definition language.\nUseful for pretty-printing queries or printing back AST for logging, documentation, etc.\n\n\nUsage example:\n\n\n$query = 'query myQuery {someField}';\n$ast = GraphQL\\Language\\Parser::parse($query);\n$printed = GraphQL\\Language\\Printer::doPrint($ast);\n\n\n\n\nClass Methods:\n \n\n\n/**\n * Prints AST to string. Capable of printing GraphQL queries and Type definition language.\n *\n * @api\n * @param Node $ast\n * @return string\n */\nstatic function doPrint($ast)\n\n\n\n\nGraphQL\\Language\\Visitor\n\n\nUtility for efficient AST traversal and modification.\n\n\nvisit()\n will walk through an AST using a depth first traversal, calling\nthe visitor's enter function at each node in the traversal, and calling the\nleave function after visiting that node and all of it's child nodes.\n\n\nBy returning different values from the enter and leave functions, the\nbehavior of the visitor can be altered, including skipping over a sub-tree of\nthe AST (by returning false), editing the AST by returning a value or null\nto remove the value, or to stop the whole traversal by returning BREAK.\n\n\nWhen using \nvisit()\n to edit an AST, the original AST will not be modified, and\na new version of the AST with the changes applied will be returned from the\nvisit function.\n\n\n$editedAST = Visitor::visit($ast, [\n 'enter' => function ($node, $key, $parent, $path, $ancestors) {\n // return\n // null: no action\n // Visitor::skipNode(): skip visiting this node\n // Visitor::stop(): stop visiting altogether\n // Visitor::removeNode(): delete this node\n // any value: replace this node with the returned value\n },\n 'leave' => function ($node, $key, $parent, $path, $ancestors) {\n // return\n // null: no action\n // Visitor::stop(): stop visiting altogether\n // Visitor::removeNode(): delete this node\n // any value: replace this node with the returned value\n }\n]);\n\n\n\nAlternatively to providing enter() and leave() functions, a visitor can\ninstead provide functions named the same as the \nkinds of AST nodes\n,\nor enter/leave visitors at a named key, leading to four permutations of\nvisitor API:\n\n\n1) Named visitors triggered when entering a node a specific kind.\n\n\nVisitor::visit($ast, [\n 'Kind' => function ($node) {\n // enter the \"Kind\" node\n }\n]);\n\n\n\n2) Named visitors that trigger upon entering and leaving a node of\n a specific kind.\n\n\nVisitor::visit($ast, [\n 'Kind' => [\n 'enter' => function ($node) {\n // enter the \"Kind\" node\n }\n 'leave' => function ($node) {\n // leave the \"Kind\" node\n }\n ]\n]);\n\n\n\n3) Generic visitors that trigger upon entering and leaving any node.\n\n\nVisitor::visit($ast, [\n 'enter' => function ($node) {\n // enter any node\n },\n 'leave' => function ($node) {\n // leave any node\n }\n]);\n\n\n\n4) Parallel visitors for entering and leaving nodes of a specific kind.\n\n\nVisitor::visit($ast, [\n 'enter' => [\n 'Kind' => function($node) {\n // enter the \"Kind\" node\n }\n },\n 'leave' => [\n 'Kind' => function ($node) {\n // leave the \"Kind\" node\n }\n ]\n]);\n\n\n\nClass Methods:\n \n\n\n/**\n * Visit the AST (see class description for details)\n *\n * @api\n * @param Node $root\n * @param array $visitor\n * @param array $keyMap\n * @return Node|mixed\n * @throws \\Exception\n */\nstatic function visit($root, $visitor, $keyMap = null)\n\n\n\n\n/**\n * Returns marker for visitor break\n *\n * @api\n * @return VisitorOperation\n */\nstatic function stop()\n\n\n\n\n/**\n * Returns marker for skipping current node\n *\n * @api\n * @return VisitorOperation\n */\nstatic function skipNode()\n\n\n\n\n/**\n * Returns marker for removing a node\n *\n * @api\n * @return VisitorOperation\n */\nstatic function removeNode()\n\n\n\n\nGraphQL\\Language\\AST\\NodeKind\n\n\nClass Constants:\n \n\n\nconst NAME = \"Name\";\nconst DOCUMENT = \"Document\";\nconst OPERATION_DEFINITION = \"OperationDefinition\";\nconst VARIABLE_DEFINITION = \"VariableDefinition\";\nconst VARIABLE = \"Variable\";\nconst SELECTION_SET = \"SelectionSet\";\nconst FIELD = \"Field\";\nconst ARGUMENT = \"Argument\";\nconst FRAGMENT_SPREAD = \"FragmentSpread\";\nconst INLINE_FRAGMENT = \"InlineFragment\";\nconst FRAGMENT_DEFINITION = \"FragmentDefinition\";\nconst INT = \"IntValue\";\nconst FLOAT = \"FloatValue\";\nconst STRING = \"StringValue\";\nconst BOOLEAN = \"BooleanValue\";\nconst ENUM = \"EnumValue\";\nconst NULL = \"NullValue\";\nconst LST = \"ListValue\";\nconst OBJECT = \"ObjectValue\";\nconst OBJECT_FIELD = \"ObjectField\";\nconst DIRECTIVE = \"Directive\";\nconst NAMED_TYPE = \"NamedType\";\nconst LIST_TYPE = \"ListType\";\nconst NON_NULL_TYPE = \"NonNullType\";\nconst SCHEMA_DEFINITION = \"SchemaDefinition\";\nconst OPERATION_TYPE_DEFINITION = \"OperationTypeDefinition\";\nconst SCALAR_TYPE_DEFINITION = \"ScalarTypeDefinition\";\nconst OBJECT_TYPE_DEFINITION = \"ObjectTypeDefinition\";\nconst FIELD_DEFINITION = \"FieldDefinition\";\nconst INPUT_VALUE_DEFINITION = \"InputValueDefinition\";\nconst INTERFACE_TYPE_DEFINITION = \"InterfaceTypeDefinition\";\nconst UNION_TYPE_DEFINITION = \"UnionTypeDefinition\";\nconst ENUM_TYPE_DEFINITION = \"EnumTypeDefinition\";\nconst ENUM_VALUE_DEFINITION = \"EnumValueDefinition\";\nconst INPUT_OBJECT_TYPE_DEFINITION = \"InputObjectTypeDefinition\";\nconst SCALAR_TYPE_EXTENSION = \"ScalarTypeExtension\";\nconst OBJECT_TYPE_EXTENSION = \"ObjectTypeExtension\";\nconst INTERFACE_TYPE_EXTENSION = \"InterfaceTypeExtension\";\nconst UNION_TYPE_EXTENSION = \"UnionTypeExtension\";\nconst ENUM_TYPE_EXTENSION = \"EnumTypeExtension\";\nconst INPUT_OBJECT_TYPE_EXTENSION = \"InputObjectTypeExtension\";\nconst DIRECTIVE_DEFINITION = \"DirectiveDefinition\";\n\n\n\n\nGraphQL\\Executor\\Executor\n\n\nImplements the \"Evaluating requests\" section of the GraphQL specification.\n\n\nClass Methods:\n \n\n\n/**\n * Executes DocumentNode against given $schema.\n *\n * Always returns ExecutionResult and never throws. All errors which occur during operation\n * execution are collected in `$result->errors`.\n *\n * @api\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param $rootValue\n * @param $contextValue\n * @param array|\\ArrayAccess $variableValues\n * @param null $operationName\n * @param callable $fieldResolver\n *\n * @return ExecutionResult|Promise\n */\nstatic function execute(\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n $rootValue = null,\n $contextValue = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null\n)\n\n\n\n\n/**\n * Same as execute(), but requires promise adapter and returns a promise which is always\n * fulfilled with an instance of ExecutionResult and never rejected.\n *\n * Useful for async PHP platforms.\n *\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param null $rootValue\n * @param null $contextValue\n * @param null $variableValues\n * @param null $operationName\n * @param callable|null $fieldResolver\n * @return Promise\n */\nstatic function promiseToExecute(\n GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter,\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n $rootValue = null,\n $contextValue = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null\n)\n\n\n\n\nGraphQL\\Executor\\ExecutionResult\n\n\nReturned after \nquery execution\n.\nRepresents both - result of successful execution and of a failed one\n(with errors collected in \nerrors\n prop)\n\n\nCould be converted to \nspec-compliant\n\nserializable array using \ntoArray()\n\n\nClass Props:\n \n\n\n/**\n * Data collected from resolvers during query execution\n *\n * @api\n * @var array\n */\npublic $data;\n\n/**\n * Errors registered during query execution.\n *\n * If an error was caused by exception thrown in resolver, $error->getPrevious() would\n * contain original exception.\n *\n * @api\n * @var \\GraphQL\\Error\\Error[]\n */\npublic $errors;\n\n/**\n * User-defined serializable array of extensions included in serialized result.\n * Conforms to\n *\n * @api\n * @var array\n */\npublic $extensions;\n\n\n\n\nClass Methods:\n \n\n\n/**\n * Define custom error formatting (must conform to http://facebook.github.io/graphql/#sec-Errors)\n *\n * Expected signature is: function (GraphQL\\Error\\Error $error): array\n *\n * Default formatter is \"GraphQL\\Error\\FormattedError::createFromException\"\n *\n * Expected returned value must be an array:\n * array(\n * 'message' => 'errorMessage',\n * // ... other keys\n * );\n *\n * @api\n * @param callable $errorFormatter\n * @return $this\n */\nfunction setErrorFormatter(callable $errorFormatter)\n\n\n\n\n/**\n * Define custom logic for error handling (filtering, logging, etc).\n *\n * Expected handler signature is: function (array $errors, callable $formatter): array\n *\n * Default handler is:\n * function (array $errors, callable $formatter) {\n * return array_map($formatter, $errors);\n * }\n *\n * @api\n * @param callable $handler\n * @return $this\n */\nfunction setErrorsHandler(callable $handler)\n\n\n\n\n/**\n * Converts GraphQL query result to spec-compliant serializable array using provided\n * errors handler and formatter.\n *\n * If debug argument is passed, output of error formatter is enriched which debugging information\n * (\"debugMessage\", \"trace\" keys depending on flags).\n *\n * $debug argument must be either bool (only adds \"debugMessage\" to result) or sum of flags from\n * GraphQL\\Error\\Debug\n *\n * @api\n * @param bool|int $debug\n * @return array\n */\nfunction toArray($debug = false)\n\n\n\n\nGraphQL\\Executor\\Promise\\PromiseAdapter\n\n\nProvides a means for integration of async PHP platforms (\nrelated docs\n)\n\n\nInterface Methods:\n \n\n\n/**\n * Return true if the value is a promise or a deferred of the underlying platform\n *\n * @api\n * @param mixed $value\n * @return bool\n */\nfunction isThenable($value)\n\n\n\n\n/**\n * Converts thenable of the underlying platform into GraphQL\\Executor\\Promise\\Promise instance\n *\n * @api\n * @param object $thenable\n * @return Promise\n */\nfunction convertThenable($thenable)\n\n\n\n\n/**\n * Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described\n * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\\Executor\\Promise\\Promise.\n *\n * @api\n * @param Promise $promise\n * @param callable|null $onFulfilled\n * @param callable|null $onRejected\n *\n * @return Promise\n */\nfunction then(\n GraphQL\\Executor\\Promise\\Promise $promise,\n callable $onFulfilled = null,\n callable $onRejected = null\n)\n\n\n\n\n/**\n * Creates a Promise\n *\n * Expected resolver signature:\n * function(callable $resolve, callable $reject)\n *\n * @api\n * @param callable $resolver\n * @return Promise\n */\nfunction create(callable $resolver)\n\n\n\n\n/**\n * Creates a fulfilled Promise for a value if the value is not a promise.\n *\n * @api\n * @param mixed $value\n * @return Promise\n */\nfunction createFulfilled($value = null)\n\n\n\n\n/**\n * Creates a rejected promise for a reason if the reason is not a promise. If\n * the provided reason is a promise, then it is returned as-is.\n *\n * @api\n * @param \\Throwable $reason\n * @return Promise\n */\nfunction createRejected($reason)\n\n\n\n\n/**\n * Given an array of promises (or values), returns a promise that is fulfilled when all the\n * items in the array are fulfilled.\n *\n * @api\n * @param array $promisesOrValues Promises or values.\n * @return Promise\n */\nfunction all(array $promisesOrValues)\n\n\n\n\nGraphQL\\Validator\\DocumentValidator\n\n\nImplements the \"Validation\" section of the spec.\n\n\nValidation runs synchronously, returning an array of encountered errors, or\nan empty array if no errors were encountered and the document is valid.\n\n\nA list of specific validation rules may be provided. If not provided, the\ndefault list of rules defined by the GraphQL specification will be used.\n\n\nEach validation rule is an instance of GraphQL\\Validator\\Rules\\AbstractValidationRule\nwhich returns a visitor (see the \nGraphQL\\Language\\Visitor API\n).\n\n\nVisitor methods are expected to return an instance of \nGraphQL\\Error\\Error\n,\nor array of such instances when invalid.\n\n\nOptionally a custom TypeInfo instance may be provided. If not provided, one\nwill be created from the provided schema.\n\n\nClass Methods:\n \n\n\n/**\n * Primary method for query validation. See class description for details.\n *\n * @api\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param AbstractValidationRule[]|null $rules\n * @param TypeInfo|null $typeInfo\n * @return Error[]\n */\nstatic function validate(\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n array $rules = null,\n GraphQL\\Utils\\TypeInfo $typeInfo = null\n)\n\n\n\n\n/**\n * Returns all global validation rules.\n *\n * @api\n * @return AbstractValidationRule[]\n */\nstatic function allRules()\n\n\n\n\n/**\n * Returns global validation rule by name. Standard rules are named by class name, so\n * example usage for such rules:\n *\n * $rule = DocumentValidator::getRule(GraphQL\\Validator\\Rules\\QueryComplexity::class);\n *\n * @api\n * @param string $name\n * @return AbstractValidationRule\n */\nstatic function getRule($name)\n\n\n\n\n/**\n * Add rule to list of global validation rules\n *\n * @api\n * @param AbstractValidationRule $rule\n */\nstatic function addRule(GraphQL\\Validator\\Rules\\AbstractValidationRule $rule)\n\n\n\n\nGraphQL\\Error\\Error\n\n\nDescribes an Error found during the parse, validate, or\nexecute phases of performing a GraphQL operation. In addition to a message\nand stack trace, it also includes information about the locations in a\nGraphQL document and/or execution result that correspond to the Error.\n\n\nWhen the error was caused by an exception thrown in resolver, original exception\nis available via \ngetPrevious()\n.\n\n\nAlso read related docs on \nerror handling\n\n\nClass extends standard PHP \n\\Exception\n, so all standard methods of base \n\\Exception\n class\nare available in addition to those listed below.\n\n\nClass Constants:\n \n\n\nconst CATEGORY_GRAPHQL = \"graphql\";\nconst CATEGORY_INTERNAL = \"internal\";\n\n\n\n\nClass Methods:\n \n\n\n/**\n * An array of locations within the source GraphQL document which correspond to this error.\n *\n * Each entry has information about `line` and `column` within source GraphQL document:\n * $location->line;\n * $location->column;\n *\n * Errors during validation often contain multiple locations, for example to\n * point out to field mentioned in multiple fragments. Errors during execution include a\n * single location, the field which produced the error.\n *\n * @api\n * @return SourceLocation[]\n */\nfunction getLocations()\n\n\n\n\n/**\n * Returns an array describing the path from the root value to the field which produced this error.\n * Only included for execution errors.\n *\n * @api\n * @return array|null\n */\nfunction getPath()\n\n\n\n\nGraphQL\\Error\\Warning\n\n\nEncapsulates warnings produced by the library.\n\n\nWarnings can be suppressed (individually or all) if required.\nAlso it is possible to override warning handler (which is \ntrigger_error()\n by default)\n\n\nClass Constants:\n \n\n\nconst WARNING_ASSIGN = 2;\nconst WARNING_CONFIG = 4;\nconst WARNING_FULL_SCHEMA_SCAN = 8;\nconst WARNING_CONFIG_DEPRECATION = 16;\nconst WARNING_NOT_A_TYPE = 32;\nconst ALL = 63;\n\n\n\n\nClass Methods:\n \n\n\n/**\n * Sets warning handler which can intercept all system warnings.\n * When not set, trigger_error() is used to notify about warnings.\n *\n * @api\n * @param callable|null $warningHandler\n */\nstatic function setWarningHandler(callable $warningHandler = null)\n\n\n\n\n/**\n * Suppress warning by id (has no effect when custom warning handler is set)\n *\n * Usage example:\n * Warning::suppress(Warning::WARNING_NOT_A_TYPE)\n *\n * When passing true - suppresses all warnings.\n *\n * @api\n * @param bool|int $suppress\n */\nstatic function suppress($suppress = true)\n\n\n\n\n/**\n * Re-enable previously suppressed warning by id\n *\n * Usage example:\n * Warning::suppress(Warning::WARNING_NOT_A_TYPE)\n *\n * When passing true - re-enables all warnings.\n *\n * @api\n * @param bool|int $enable\n */\nstatic function enable($enable = true)\n\n\n\n\nGraphQL\\Error\\ClientAware\n\n\nThis interface is used for \ndefault error formatting\n.\n\n\nOnly errors implementing this interface (and returning true from \nisClientSafe()\n)\nwill be formatted with original error message.\n\n\nAll other errors will be formatted with generic \"Internal server error\".\n\n\nInterface Methods:\n \n\n\n/**\n * Returns true when exception message is safe to be displayed to a client.\n *\n * @api\n * @return bool\n */\nfunction isClientSafe()\n\n\n\n\n/**\n * Returns string describing a category of the error.\n *\n * Value \"graphql\" is reserved for errors produced by query parsing or validation, do not use it.\n *\n * @api\n * @return string\n */\nfunction getCategory()\n\n\n\n\nGraphQL\\Error\\Debug\n\n\nCollection of flags for \nerror debugging\n.\n\n\nClass Constants:\n \n\n\nconst INCLUDE_DEBUG_MESSAGE = 1;\nconst INCLUDE_TRACE = 2;\nconst RETHROW_INTERNAL_EXCEPTIONS = 4;\n\n\n\n\nGraphQL\\Error\\FormattedError\n\n\nThis class is used for \ndefault error formatting\n.\nIt converts PHP exceptions to \nspec-compliant errors\n\nand provides tools for error debugging.\n\n\nClass Methods:\n \n\n\n/**\n * Set default error message for internal errors formatted using createFormattedError().\n * This value can be overridden by passing 3rd argument to `createFormattedError()`.\n *\n * @api\n * @param string $msg\n */\nstatic function setInternalErrorMessage($msg)\n\n\n\n\n/**\n * Standard GraphQL error formatter. Converts any exception to array\n * conforming to GraphQL spec.\n *\n * This method only exposes exception message when exception implements ClientAware interface\n * (or when debug flags are passed).\n *\n * For a list of available debug flags see GraphQL\\Error\\Debug constants.\n *\n * @api\n * @param \\Throwable $e\n * @param bool|int $debug\n * @param string $internalErrorMessage\n * @return array\n * @throws \\Throwable\n */\nstatic function createFromException($e, $debug = false, $internalErrorMessage = null)\n\n\n\n\n/**\n * Returns error trace as serializable array\n *\n * @api\n * @param \\Throwable $error\n * @return array\n */\nstatic function toSafeTrace($error)\n\n\n\n\nGraphQL\\Server\\StandardServer\n\n\nGraphQL server compatible with both: \nexpress-graphql\n\nand \nApollo Server\n.\nUsage Example:\n\n\n$server = new StandardServer([\n 'schema' => $mySchema\n]);\n$server->handleRequest();\n\n\n\nOr using \nServerConfig\n instance:\n\n\n$config = GraphQL\\Server\\ServerConfig::create()\n ->setSchema($mySchema)\n ->setContext($myContext);\n\n$server = new GraphQL\\Server\\StandardServer($config);\n$server->handleRequest();\n\n\n\nSee \ndedicated section in docs\n for details.\n\n\nClass Methods:\n \n\n\n/**\n * Converts and exception to error and sends spec-compliant HTTP 500 error.\n * Useful when an exception is thrown somewhere outside of server execution context\n * (e.g. during schema instantiation).\n *\n * @api\n * @param \\Throwable $error\n * @param bool $debug\n * @param bool $exitWhenDone\n */\nstatic function send500Error($error, $debug = false, $exitWhenDone = false)\n\n\n\n\n/**\n * Creates new instance of a standard GraphQL HTTP server\n *\n * @api\n * @param ServerConfig|array $config\n */\nfunction __construct($config)\n\n\n\n\n/**\n * Parses HTTP request, executes and emits response (using standard PHP `header` function and `echo`)\n *\n * By default (when $parsedBody is not set) it uses PHP globals to parse a request.\n * It is possible to implement request parsing elsewhere (e.g. using framework Request instance)\n * and then pass it to the server.\n *\n * See `executeRequest()` if you prefer to emit response yourself\n * (e.g. using Response object of some framework)\n *\n * @api\n * @param OperationParams|OperationParams[] $parsedBody\n * @param bool $exitWhenDone\n */\nfunction handleRequest($parsedBody = null, $exitWhenDone = false)\n\n\n\n\n/**\n * Executes GraphQL operation and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter).\n *\n * By default (when $parsedBody is not set) it uses PHP globals to parse a request.\n * It is possible to implement request parsing elsewhere (e.g. using framework Request instance)\n * and then pass it to the server.\n *\n * PSR-7 compatible method executePsrRequest() does exactly this.\n *\n * @api\n * @param OperationParams|OperationParams[] $parsedBody\n * @return ExecutionResult|ExecutionResult[]|Promise\n * @throws InvariantViolation\n */\nfunction executeRequest($parsedBody = null)\n\n\n\n\n/**\n * Executes PSR-7 request and fulfills PSR-7 response.\n *\n * See `executePsrRequest()` if you prefer to create response yourself\n * (e.g. using specific JsonResponse instance of some framework).\n *\n * @api\n * @param ServerRequestInterface $request\n * @param ResponseInterface $response\n * @param StreamInterface $writableBodyStream\n * @return ResponseInterface|Promise\n */\nfunction processPsrRequest(\n Psr\\Http\\Message\\ServerRequestInterface $request,\n Psr\\Http\\Message\\ResponseInterface $response,\n Psr\\Http\\Message\\StreamInterface $writableBodyStream\n)\n\n\n\n\n/**\n * Executes GraphQL operation and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter)\n *\n * @api\n * @param ServerRequestInterface $request\n * @return ExecutionResult|ExecutionResult[]|Promise\n */\nfunction executePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request)\n\n\n\n\n/**\n * Returns an instance of Server helper, which contains most of the actual logic for\n * parsing / validating / executing request (which could be re-used by other server implementations)\n *\n * @api\n * @return Helper\n */\nfunction getHelper()\n\n\n\n\nGraphQL\\Server\\ServerConfig\n\n\nServer configuration class.\nCould be passed directly to server constructor. List of options accepted by \ncreate\n method is\n\ndescribed in docs\n.\n\n\nUsage example:\n\n\n$config = GraphQL\\Server\\ServerConfig::create()\n ->setSchema($mySchema)\n ->setContext($myContext);\n\n$server = new GraphQL\\Server\\StandardServer($config);\n\n\n\nClass Methods:\n \n\n\n/**\n * Converts an array of options to instance of ServerConfig\n * (or just returns empty config when array is not passed).\n *\n * @api\n * @param array $config\n * @return ServerConfig\n */\nstatic function create(array $config = [])\n\n\n\n\n/**\n * @api\n * @param Schema $schema\n * @return $this\n */\nfunction setSchema(GraphQL\\Type\\Schema $schema)\n\n\n\n\n/**\n * @api\n * @param mixed|\\Closure $context\n * @return $this\n */\nfunction setContext($context)\n\n\n\n\n/**\n * @api\n * @param mixed|\\Closure $rootValue\n * @return $this\n */\nfunction setRootValue($rootValue)\n\n\n\n\n/**\n * Expects function(Throwable $e) : array\n *\n * @api\n * @param callable $errorFormatter\n * @return $this\n */\nfunction setErrorFormatter(callable $errorFormatter)\n\n\n\n\n/**\n * Expects function(array $errors, callable $formatter) : array\n *\n * @api\n * @param callable $handler\n * @return $this\n */\nfunction setErrorsHandler(callable $handler)\n\n\n\n\n/**\n * Set validation rules for this server.\n *\n * @api\n * @param array|callable\n * @return $this\n */\nfunction setValidationRules($validationRules)\n\n\n\n\n/**\n * @api\n * @param callable $fieldResolver\n * @return $this\n */\nfunction setFieldResolver(callable $fieldResolver)\n\n\n\n\n/**\n * Expects function($queryId, OperationParams $params) : string|DocumentNode\n *\n * This function must return query string or valid DocumentNode.\n *\n * @api\n * @param callable $persistentQueryLoader\n * @return $this\n */\nfunction setPersistentQueryLoader(callable $persistentQueryLoader)\n\n\n\n\n/**\n * Set response debug flags. See GraphQL\\Error\\Debug class for a list of all available flags\n *\n * @api\n * @param bool|int $set\n * @return $this\n */\nfunction setDebug($set = true)\n\n\n\n\n/**\n * Allow batching queries (disabled by default)\n *\n * @api\n * @param bool $enableBatching\n * @return $this\n */\nfunction setQueryBatching($enableBatching)\n\n\n\n\n/**\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @return $this\n */\nfunction setPromiseAdapter(GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter)\n\n\n\n\nGraphQL\\Server\\Helper\n\n\nContains functionality that could be re-used by various server implementations\n\n\nClass Methods:\n \n\n\n/**\n * Parses HTTP request using PHP globals and returns GraphQL OperationParams\n * contained in this request. For batched requests it returns an array of OperationParams.\n *\n * This function does not check validity of these params\n * (validation is performed separately in validateOperationParams() method).\n *\n * If $readRawBodyFn argument is not provided - will attempt to read raw request body\n * from `php://input` stream.\n *\n * Internally it normalizes input to $method, $bodyParams and $queryParams and\n * calls `parseRequestParams()` to produce actual return value.\n *\n * For PSR-7 request parsing use `parsePsrRequest()` instead.\n *\n * @api\n * @param callable|null $readRawBodyFn\n * @return OperationParams|OperationParams[]\n * @throws RequestError\n */\nfunction parseHttpRequest(callable $readRawBodyFn = null)\n\n\n\n\n/**\n * Parses normalized request params and returns instance of OperationParams\n * or array of OperationParams in case of batch operation.\n *\n * Returned value is a suitable input for `executeOperation` or `executeBatch` (if array)\n *\n * @api\n * @param string $method\n * @param array $bodyParams\n * @param array $queryParams\n * @return OperationParams|OperationParams[]\n * @throws RequestError\n */\nfunction parseRequestParams($method, array $bodyParams, array $queryParams)\n\n\n\n\n/**\n * Checks validity of OperationParams extracted from HTTP request and returns an array of errors\n * if params are invalid (or empty array when params are valid)\n *\n * @api\n * @param OperationParams $params\n * @return Error[]\n */\nfunction validateOperationParams(GraphQL\\Server\\OperationParams $params)\n\n\n\n\n/**\n * Executes GraphQL operation with given server configuration and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter)\n *\n * @api\n * @param ServerConfig $config\n * @param OperationParams $op\n *\n * @return ExecutionResult|Promise\n */\nfunction executeOperation(GraphQL\\Server\\ServerConfig $config, GraphQL\\Server\\OperationParams $op)\n\n\n\n\n/**\n * Executes batched GraphQL operations with shared promise queue\n * (thus, effectively batching deferreds|promises of all queries at once)\n *\n * @api\n * @param ServerConfig $config\n * @param OperationParams[] $operations\n * @return ExecutionResult[]|Promise\n */\nfunction executeBatch(GraphQL\\Server\\ServerConfig $config, array $operations)\n\n\n\n\n/**\n * Send response using standard PHP `header()` and `echo`.\n *\n * @api\n * @param Promise|ExecutionResult|ExecutionResult[] $result\n * @param bool $exitWhenDone\n */\nfunction sendResponse($result, $exitWhenDone = false)\n\n\n\n\n/**\n * Converts PSR-7 request to OperationParams[]\n *\n * @api\n * @param ServerRequestInterface $request\n * @return array|Helper\n * @throws RequestError\n */\nfunction parsePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request)\n\n\n\n\n/**\n * Converts query execution result to PSR-7 response\n *\n * @api\n * @param Promise|ExecutionResult|ExecutionResult[] $result\n * @param ResponseInterface $response\n * @param StreamInterface $writableBodyStream\n * @return Promise|ResponseInterface\n */\nfunction toPsrResponse(\n $result,\n Psr\\Http\\Message\\ResponseInterface $response,\n Psr\\Http\\Message\\StreamInterface $writableBodyStream\n)\n\n\n\n\nGraphQL\\Server\\OperationParams\n\n\nStructure representing parsed HTTP parameters for GraphQL operation\n\n\nClass Props:\n \n\n\n/**\n * Id of the query (when using persistent queries).\n *\n * Valid aliases (case-insensitive):\n * - id\n * - queryId\n * - documentId\n *\n * @api\n * @var string\n */\npublic $queryId;\n\n/**\n * @api\n * @var string\n */\npublic $query;\n\n/**\n * @api\n * @var string\n */\npublic $operation;\n\n/**\n * @api\n * @var array\n */\npublic $variables;\n\n\n\n\nClass Methods:\n \n\n\n/**\n * Creates an instance from given array\n *\n * @api\n * @param array $params\n * @param bool $readonly\n * @return OperationParams\n */\nstatic function create(array $params, $readonly = false)\n\n\n\n\n/**\n * @api\n * @param string $key\n * @return mixed\n */\nfunction getOriginalInput($key)\n\n\n\n\n/**\n * Indicates that operation is executed in read-only context\n * (e.g. via HTTP GET request)\n *\n * @api\n * @return bool\n */\nfunction isReadOnly()\n\n\n\n\nGraphQL\\Utils\\BuildSchema\n\n\nBuild instance of \nGraphQL\\Type\\Schema\n out of type language definition (string or parsed AST)\nSee \nsection in docs\n for details.\n\n\nClass Methods:\n \n\n\n/**\n * This takes the ast of a schema document produced by the parse function in\n * GraphQL\\Language\\Parser.\n *\n * If no schema definition is provided, then it will look for types named Query\n * and Mutation.\n *\n * Given that AST it constructs a GraphQL\\Type\\Schema. The resulting schema\n * has no resolve methods, so execution will use default resolvers.\n *\n * Accepts options as a second argument:\n *\n * - commentDescriptions:\n * Provide true to use preceding comments as the description.\n *\n *\n * @api\n * @param DocumentNode $ast\n * @param array $options\n * @return Schema\n * @throws Error\n */\nstatic function buildAST(GraphQL\\Language\\AST\\DocumentNode $ast, array $options = [])\n\n\n\n\n/**\n * A helper function to build a GraphQLSchema directly from a source\n * document.\n *\n * @api\n * @param DocumentNode|Source|string $source\n * @param array $options\n * @return Schema\n */\nstatic function build($source, array $options = [])\n\n\n\n\nGraphQL\\Utils\\AST\n\n\nVarious utilities dealing with AST\n\n\nClass Methods:\n \n\n\n/**\n * Convert representation of AST as an associative array to instance of GraphQL\\Language\\AST\\Node.\n *\n * For example:\n *\n * ```php\n * AST::fromArray([\n * 'kind' => 'ListValue',\n * 'values' => [\n * ['kind' => 'StringValue', 'value' => 'my str'],\n * ['kind' => 'StringValue', 'value' => 'my other str']\n * ],\n * 'loc' => ['start' => 21, 'end' => 25]\n * ]);\n * ```\n *\n * Will produce instance of `ListValueNode` where `values` prop is a lazily-evaluated `NodeList`\n * returning instances of `StringValueNode` on access.\n *\n * This is a reverse operation for AST::toArray($node)\n *\n * @api\n * @param array $node\n * @return Node\n */\nstatic function fromArray(array $node)\n\n\n\n\n/**\n * Convert AST node to serializable array\n *\n * @api\n * @param Node $node\n * @return array\n */\nstatic function toArray(GraphQL\\Language\\AST\\Node $node)\n\n\n\n\n/**\n * Produces a GraphQL Value AST given a PHP value.\n *\n * Optionally, a GraphQL type may be provided, which will be used to\n * disambiguate between value primitives.\n *\n * | PHP Value | GraphQL Value |\n * | ------------- | -------------------- |\n * | Object | Input Object |\n * | Assoc Array | Input Object |\n * | Array | List |\n * | Boolean | Boolean |\n * | String | String / Enum Value |\n * | Int | Int |\n * | Float | Int / Float |\n * | Mixed | Enum Value |\n * | null | NullValue |\n *\n * @api\n * @param $value\n * @param InputType $type\n * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode\n */\nstatic function astFromValue($value, GraphQL\\Type\\Definition\\InputType $type)\n\n\n\n\n/**\n * Produces a PHP value given a GraphQL Value AST.\n *\n * A GraphQL type must be provided, which will be used to interpret different\n * GraphQL Value literals.\n *\n * Returns `null` when the value could not be validly coerced according to\n * the provided type.\n *\n * | GraphQL Value | PHP Value |\n * | -------------------- | ------------- |\n * | Input Object | Assoc Array |\n * | List | Array |\n * | Boolean | Boolean |\n * | String | String |\n * | Int / Float | Int / Float |\n * | Enum Value | Mixed |\n * | Null Value | null |\n *\n * @api\n * @param $valueNode\n * @param InputType $type\n * @param null $variables\n * @return array|null|\\stdClass\n * @throws \\Exception\n */\nstatic function valueFromAST($valueNode, GraphQL\\Type\\Definition\\InputType $type, $variables = null)\n\n\n\n\n/**\n * Produces a PHP value given a GraphQL Value AST.\n *\n * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value\n * will reflect the provided GraphQL value AST.\n *\n * | GraphQL Value | PHP Value |\n * | -------------------- | ------------- |\n * | Input Object | Assoc Array |\n * | List | Array |\n * | Boolean | Boolean |\n * | String | String |\n * | Int / Float | Int / Float |\n * | Enum | Mixed |\n * | Null | null |\n *\n * @api\n * @param Node $valueNode\n * @param array|null $variables\n * @return mixed\n * @throws \\Exception\n */\nstatic function valueFromASTUntyped($valueNode, array $variables = null)\n\n\n\n\n/**\n * Returns type definition for given AST Type node\n *\n * @api\n * @param Schema $schema\n * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode\n * @return Type\n * @throws \\Exception\n */\nstatic function typeFromAST(GraphQL\\Type\\Schema $schema, $inputTypeNode)\n\n\n\n\n/**\n * Returns operation type (\"query\", \"mutation\" or \"subscription\") given a document and operation name\n *\n * @api\n * @param DocumentNode $document\n * @param string $operationName\n * @return bool\n */\nstatic function getOperation(GraphQL\\Language\\AST\\DocumentNode $document, $operationName = null)\n\n\n\n\nGraphQL\\Utils\\SchemaPrinter\n\n\nGiven an instance of Schema, prints it in GraphQL type language.\n\n\nClass Methods:\n \n\n\n/**\n * Accepts options as a second argument:\n *\n * - commentDescriptions:\n * Provide true to use preceding comments as the description.\n * @api\n * @param Schema $schema\n * @return string\n */\nstatic function doPrint(GraphQL\\Type\\Schema $schema, array $options = [])\n\n\n\n\n/**\n * @api\n * @param Schema $schema\n * @return string\n */\nstatic function printIntrosepctionSchema(GraphQL\\Type\\Schema $schema, array $options = [])",
"title": "Class Reference"
},
{
"location": "/reference/#graphqlgraphql",
"text": "This is the primary facade for fulfilling GraphQL operations.\nSee related documentation . Class Methods: /**\n * Executes graphql query.\n *\n * More sophisticated GraphQL servers, such as those which persist queries,\n * may wish to separate the validation and execution phases to a static time\n * tooling step, and a server runtime step.\n *\n * Available options:\n *\n * schema:\n * The GraphQL type system to use when validating and executing a query.\n * source:\n * A GraphQL language formatted string representing the requested operation.\n * rootValue:\n * The value provided as the first argument to resolver functions on the top\n * level type (e.g. the query object type).\n * context:\n * The value provided as the third argument to all resolvers.\n * Use this to pass current session, user data, etc\n * variableValues:\n * A mapping of variable name to runtime value to use for all variables\n * defined in the requestString.\n * operationName:\n * The name of the operation to use if requestString contains multiple\n * possible operations. Can be omitted if requestString contains only\n * one operation.\n * fieldResolver:\n * A resolver function to use when one is not provided by the schema.\n * If not provided, the default field resolver is used (which looks for a\n * value on the source value with the field's name).\n * validationRules:\n * A set of rules for query validation step. Default value is all available rules.\n * Empty array would allow to skip query validation (may be convenient for persisted\n * queries which are validated before persisting and assumed valid during execution)\n *\n * @api\n * @param \\GraphQL\\Type\\Schema $schema\n * @param string|DocumentNode $source\n * @param mixed $rootValue\n * @param mixed $context\n * @param array|null $variableValues\n * @param string|null $operationName\n * @param callable $fieldResolver\n * @param array $validationRules\n *\n * @return ExecutionResult\n */\nstatic function executeQuery(\n GraphQL\\Type\\Schema $schema,\n $source,\n $rootValue = null,\n $context = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null,\n array $validationRules = null\n) /**\n * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise.\n * Useful for Async PHP platforms.\n *\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @param \\GraphQL\\Type\\Schema $schema\n * @param string|DocumentNode $source\n * @param mixed $rootValue\n * @param mixed $context\n * @param array|null $variableValues\n * @param string|null $operationName\n * @param callable $fieldResolver\n * @param array $validationRules\n *\n * @return Promise\n */\nstatic function promiseToExecute(\n GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter,\n GraphQL\\Type\\Schema $schema,\n $source,\n $rootValue = null,\n $context = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null,\n array $validationRules = null\n) /**\n * Returns directives defined in GraphQL spec\n *\n * @api\n * @return Directive[]\n */\nstatic function getStandardDirectives() /**\n * Returns types defined in GraphQL spec\n *\n * @api\n * @return Type[]\n */\nstatic function getStandardTypes() /**\n * Returns standard validation rules implementing GraphQL spec\n *\n * @api\n * @return AbstractValidationRule[]\n */\nstatic function getStandardValidationRules()",
"title": "GraphQL\\GraphQL"
},
{
"location": "/reference/#graphqltypedefinitiontype",
"text": "Registry of standard GraphQL types\nand a base class for all other types. Class Methods: /**\n * @api\n * @return IDType\n */\nstatic function id() /**\n * @api\n * @return StringType\n */\nstatic function string() /**\n * @api\n * @return BooleanType\n */\nstatic function boolean() /**\n * @api\n * @return IntType\n */\nstatic function int() /**\n * @api\n * @return FloatType\n */\nstatic function float() /**\n * @api\n * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType\n * @return ListOfType\n */\nstatic function listOf($wrappedType) /**\n * @api\n * @param ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType $wrappedType\n * @return NonNull\n */\nstatic function nonNull($wrappedType) /**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isInputType($type) /**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isOutputType($type) /**\n * @api\n * @param $type\n * @return bool\n */\nstatic function isLeafType($type) /**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isCompositeType($type) /**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isAbstractType($type) /**\n * @api\n * @param Type $type\n * @return bool\n */\nstatic function isType($type) /**\n * @api\n * @param Type $type\n * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType\n */\nstatic function getNullableType($type) /**\n * @api\n * @param Type $type\n * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType\n */\nstatic function getNamedType($type)",
"title": "GraphQL\\Type\\Definition\\Type"
},
{
"location": "/reference/#graphqltypedefinitionresolveinfo",
"text": "Structure containing information useful for field resolution process.\nPassed as 3rd argument to every field resolver. See docs on field resolving (data fetching) . Class Props: /**\n * The name of the field being resolved\n *\n * @api\n * @var string\n */\npublic $fieldName;\n\n/**\n * AST of all nodes referencing this field in the query.\n *\n * @api\n * @var FieldNode[]\n */\npublic $fieldNodes;\n\n/**\n * Expected return type of the field being resolved\n *\n * @api\n * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull\n */\npublic $returnType;\n\n/**\n * Parent type of the field being resolved\n *\n * @api\n * @var ObjectType\n */\npublic $parentType;\n\n/**\n * Path to this field from the very root value\n *\n * @api\n * @var array\n */\npublic $path;\n\n/**\n * Instance of a schema used for execution\n *\n * @api\n * @var Schema\n */\npublic $schema;\n\n/**\n * AST of all fragments defined in query\n *\n * @api\n * @var FragmentDefinitionNode[]\n */\npublic $fragments;\n\n/**\n * Root value passed to query execution\n *\n * @api\n * @var mixed\n */\npublic $rootValue;\n\n/**\n * AST of operation definition node (query, mutation)\n *\n * @api\n * @var OperationDefinitionNode\n */\npublic $operation;\n\n/**\n * Array of variables passed to query execution\n *\n * @api\n * @var array\n */\npublic $variableValues; Class Methods: /**\n * Helper method that returns names of all fields selected in query for\n * $this->fieldName up to $depth levels\n *\n * Example:\n * query MyQuery{\n * {\n * root {\n * id,\n * nested {\n * nested1\n * nested2 {\n * nested3\n * }\n * }\n * }\n * }\n *\n * Given this ResolveInfo instance is a part of \"root\" field resolution, and $depth === 1,\n * method will return:\n * [\n * 'id' => true,\n * 'nested' => [\n * nested1 => true,\n * nested2 => true\n * ]\n * ]\n *\n * Warning: this method it is a naive implementation which does not take into account\n * conditional typed fragments. So use it with care for fields of interface and union types.\n *\n * @api\n * @param int $depth How many levels to include in output\n * @return array\n */\nfunction getFieldSelection($depth = 0)",
"title": "GraphQL\\Type\\Definition\\ResolveInfo"
},
{
"location": "/reference/#graphqllanguagedirectivelocation",
"text": "List of available directive locations Class Constants: const QUERY = \"QUERY\";\nconst MUTATION = \"MUTATION\";\nconst SUBSCRIPTION = \"SUBSCRIPTION\";\nconst FIELD = \"FIELD\";\nconst FRAGMENT_DEFINITION = \"FRAGMENT_DEFINITION\";\nconst FRAGMENT_SPREAD = \"FRAGMENT_SPREAD\";\nconst INLINE_FRAGMENT = \"INLINE_FRAGMENT\";\nconst SCHEMA = \"SCHEMA\";\nconst SCALAR = \"SCALAR\";\nconst OBJECT = \"OBJECT\";\nconst FIELD_DEFINITION = \"FIELD_DEFINITION\";\nconst ARGUMENT_DEFINITION = \"ARGUMENT_DEFINITION\";\nconst IFACE = \"INTERFACE\";\nconst UNION = \"UNION\";\nconst ENUM = \"ENUM\";\nconst ENUM_VALUE = \"ENUM_VALUE\";\nconst INPUT_OBJECT = \"INPUT_OBJECT\";\nconst INPUT_FIELD_DEFINITION = \"INPUT_FIELD_DEFINITION\";",
"title": "GraphQL\\Language\\DirectiveLocation"
},
{
"location": "/reference/#graphqltypeschemaconfig",
"text": "Schema configuration class.\nCould be passed directly to schema constructor. List of options accepted by create method is described in docs . Usage example: $config = SchemaConfig::create()\n ->setQuery($myQueryType)\n ->setTypeLoader($myTypeLoader);\n\n$schema = new Schema($config); Class Methods: /**\n * Converts an array of options to instance of SchemaConfig\n * (or just returns empty config when array is not passed).\n *\n * @api\n * @param array $options\n * @return SchemaConfig\n */\nstatic function create(array $options = []) /**\n * @api\n * @param ObjectType $query\n * @return SchemaConfig\n */\nfunction setQuery($query) /**\n * @api\n * @param ObjectType $mutation\n * @return SchemaConfig\n */\nfunction setMutation($mutation) /**\n * @api\n * @param ObjectType $subscription\n * @return SchemaConfig\n */\nfunction setSubscription($subscription) /**\n * @api\n * @param Type[]|callable $types\n * @return SchemaConfig\n */\nfunction setTypes($types) /**\n * @api\n * @param Directive[] $directives\n * @return SchemaConfig\n */\nfunction setDirectives(array $directives) /**\n * @api\n * @param callable $typeLoader\n * @return SchemaConfig\n */\nfunction setTypeLoader(callable $typeLoader) /**\n * @api\n * @return ObjectType\n */\nfunction getQuery() /**\n * @api\n * @return ObjectType\n */\nfunction getMutation() /**\n * @api\n * @return ObjectType\n */\nfunction getSubscription() /**\n * @api\n * @return Type[]\n */\nfunction getTypes() /**\n * @api\n * @return Directive[]\n */\nfunction getDirectives() /**\n * @api\n * @return callable\n */\nfunction getTypeLoader()",
"title": "GraphQL\\Type\\SchemaConfig"
},
{
"location": "/reference/#graphqltypeschema",
"text": "Schema Definition (see related docs ) A Schema is created by supplying the root types of each type of operation:\nquery, mutation (optional) and subscription (optional). A schema definition is\nthen supplied to the validator and executor. Usage Example: $schema = new GraphQL\\Type\\Schema([\n 'query' => $MyAppQueryRootType,\n 'mutation' => $MyAppMutationRootType,\n]); Or using Schema Config instance: $config = GraphQL\\Type\\SchemaConfig::create()\n ->setQuery($MyAppQueryRootType)\n ->setMutation($MyAppMutationRootType);\n\n$schema = new GraphQL\\Type\\Schema($config); Class Methods: /**\n * Schema constructor.\n *\n * @api\n * @param array|SchemaConfig $config\n */\nfunction __construct($config) /**\n * Returns schema query type\n *\n * @api\n * @return ObjectType\n */\nfunction getQueryType() /**\n * Returns schema mutation type\n *\n * @api\n * @return ObjectType|null\n */\nfunction getMutationType() /**\n * Returns schema subscription\n *\n * @api\n * @return ObjectType|null\n */\nfunction getSubscriptionType() /**\n * @api\n * @return SchemaConfig\n */\nfunction getConfig() /**\n * Returns array of all types in this schema. Keys of this array represent type names, values are instances\n * of corresponding type definitions\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @return Type[]\n */\nfunction getTypeMap() /**\n * Returns type by it's name\n *\n * @api\n * @param string $name\n * @return Type\n */\nfunction getType($name) /**\n * Returns all possible concrete types for given abstract type\n * (implementations for interfaces and members of union type for unions)\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @param AbstractType $abstractType\n * @return ObjectType[]\n */\nfunction getPossibleTypes(GraphQL\\Type\\Definition\\AbstractType $abstractType) /**\n * Returns true if object type is concrete type of given abstract type\n * (implementation for interfaces and members of union type for unions)\n *\n * @api\n * @param AbstractType $abstractType\n * @param ObjectType $possibleType\n * @return bool\n */\nfunction isPossibleType(\n GraphQL\\Type\\Definition\\AbstractType $abstractType,\n GraphQL\\Type\\Definition\\ObjectType $possibleType\n) /**\n * Returns a list of directives supported by this schema\n *\n * @api\n * @return Directive[]\n */\nfunction getDirectives() /**\n * Returns instance of directive by name\n *\n * @api\n * @param $name\n * @return Directive\n */\nfunction getDirective($name) /**\n * Validates schema.\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @return InvariantViolation[]|Error[]\n */\nfunction validate() /**\n * Validates schema.\n *\n * This operation requires full schema scan. Do not use in production environment.\n *\n * @api\n * @throws InvariantViolation\n */\nfunction assertValid()",
"title": "GraphQL\\Type\\Schema"
},
{
"location": "/reference/#graphqllanguageparser",
"text": "Parses string containing GraphQL query or type definition to Abstract Syntax Tree. Class Methods: /**\n * Given a GraphQL source, parses it into a `GraphQL\\Language\\AST\\DocumentNode`.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * Available options:\n *\n * noLocation: boolean,\n * (By default, the parser creates AST nodes that know the location\n * in the source that they correspond to. This configuration flag\n * disables that behavior for performance or testing.)\n *\n * experimentalFragmentVariables: boolean,\n * (If enabled, the parser will understand and parse variable definitions\n * contained in a fragment definition. They'll be represented in the\n * `variableDefinitions` field of the FragmentDefinitionNode.\n *\n * The syntax is identical to normal, query-defined variables. For example:\n *\n * fragment A($var: Boolean = false) on T {\n * ...\n * }\n *\n * Note: this feature is experimental and may change or be removed in the\n * future.)\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return DocumentNode\n * @throws SyntaxError\n */\nstatic function parse($source, array $options = []) /**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::valueFromAST()`.\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode\n */\nstatic function parseValue($source, array $options = []) /**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::typeFromAST()`.\n *\n * @api\n * @param Source|string $source\n * @param array $options\n * @return ListTypeNode|NameNode|NonNullTypeNode\n */\nstatic function parseType($source, array $options = [])",
"title": "GraphQL\\Language\\Parser"
},
{
"location": "/reference/#graphqllanguageprinter",
"text": "Prints AST to string. Capable of printing GraphQL queries and Type definition language.\nUseful for pretty-printing queries or printing back AST for logging, documentation, etc. Usage example: $query = 'query myQuery {someField}';\n$ast = GraphQL\\Language\\Parser::parse($query);\n$printed = GraphQL\\Language\\Printer::doPrint($ast); Class Methods: /**\n * Prints AST to string. Capable of printing GraphQL queries and Type definition language.\n *\n * @api\n * @param Node $ast\n * @return string\n */\nstatic function doPrint($ast)",
"title": "GraphQL\\Language\\Printer"
},
{
"location": "/reference/#graphqllanguagevisitor",
"text": "Utility for efficient AST traversal and modification. visit() will walk through an AST using a depth first traversal, calling\nthe visitor's enter function at each node in the traversal, and calling the\nleave function after visiting that node and all of it's child nodes. By returning different values from the enter and leave functions, the\nbehavior of the visitor can be altered, including skipping over a sub-tree of\nthe AST (by returning false), editing the AST by returning a value or null\nto remove the value, or to stop the whole traversal by returning BREAK. When using visit() to edit an AST, the original AST will not be modified, and\na new version of the AST with the changes applied will be returned from the\nvisit function. $editedAST = Visitor::visit($ast, [\n 'enter' => function ($node, $key, $parent, $path, $ancestors) {\n // return\n // null: no action\n // Visitor::skipNode(): skip visiting this node\n // Visitor::stop(): stop visiting altogether\n // Visitor::removeNode(): delete this node\n // any value: replace this node with the returned value\n },\n 'leave' => function ($node, $key, $parent, $path, $ancestors) {\n // return\n // null: no action\n // Visitor::stop(): stop visiting altogether\n // Visitor::removeNode(): delete this node\n // any value: replace this node with the returned value\n }\n]); Alternatively to providing enter() and leave() functions, a visitor can\ninstead provide functions named the same as the kinds of AST nodes ,\nor enter/leave visitors at a named key, leading to four permutations of\nvisitor API: 1) Named visitors triggered when entering a node a specific kind. Visitor::visit($ast, [\n 'Kind' => function ($node) {\n // enter the \"Kind\" node\n }\n]); 2) Named visitors that trigger upon entering and leaving a node of\n a specific kind. Visitor::visit($ast, [\n 'Kind' => [\n 'enter' => function ($node) {\n // enter the \"Kind\" node\n }\n 'leave' => function ($node) {\n // leave the \"Kind\" node\n }\n ]\n]); 3) Generic visitors that trigger upon entering and leaving any node. Visitor::visit($ast, [\n 'enter' => function ($node) {\n // enter any node\n },\n 'leave' => function ($node) {\n // leave any node\n }\n]); 4) Parallel visitors for entering and leaving nodes of a specific kind. Visitor::visit($ast, [\n 'enter' => [\n 'Kind' => function($node) {\n // enter the \"Kind\" node\n }\n },\n 'leave' => [\n 'Kind' => function ($node) {\n // leave the \"Kind\" node\n }\n ]\n]); Class Methods: /**\n * Visit the AST (see class description for details)\n *\n * @api\n * @param Node $root\n * @param array $visitor\n * @param array $keyMap\n * @return Node|mixed\n * @throws \\Exception\n */\nstatic function visit($root, $visitor, $keyMap = null) /**\n * Returns marker for visitor break\n *\n * @api\n * @return VisitorOperation\n */\nstatic function stop() /**\n * Returns marker for skipping current node\n *\n * @api\n * @return VisitorOperation\n */\nstatic function skipNode() /**\n * Returns marker for removing a node\n *\n * @api\n * @return VisitorOperation\n */\nstatic function removeNode()",
"title": "GraphQL\\Language\\Visitor"
},
{
"location": "/reference/#graphqllanguageastnodekind",
"text": "Class Constants: const NAME = \"Name\";\nconst DOCUMENT = \"Document\";\nconst OPERATION_DEFINITION = \"OperationDefinition\";\nconst VARIABLE_DEFINITION = \"VariableDefinition\";\nconst VARIABLE = \"Variable\";\nconst SELECTION_SET = \"SelectionSet\";\nconst FIELD = \"Field\";\nconst ARGUMENT = \"Argument\";\nconst FRAGMENT_SPREAD = \"FragmentSpread\";\nconst INLINE_FRAGMENT = \"InlineFragment\";\nconst FRAGMENT_DEFINITION = \"FragmentDefinition\";\nconst INT = \"IntValue\";\nconst FLOAT = \"FloatValue\";\nconst STRING = \"StringValue\";\nconst BOOLEAN = \"BooleanValue\";\nconst ENUM = \"EnumValue\";\nconst NULL = \"NullValue\";\nconst LST = \"ListValue\";\nconst OBJECT = \"ObjectValue\";\nconst OBJECT_FIELD = \"ObjectField\";\nconst DIRECTIVE = \"Directive\";\nconst NAMED_TYPE = \"NamedType\";\nconst LIST_TYPE = \"ListType\";\nconst NON_NULL_TYPE = \"NonNullType\";\nconst SCHEMA_DEFINITION = \"SchemaDefinition\";\nconst OPERATION_TYPE_DEFINITION = \"OperationTypeDefinition\";\nconst SCALAR_TYPE_DEFINITION = \"ScalarTypeDefinition\";\nconst OBJECT_TYPE_DEFINITION = \"ObjectTypeDefinition\";\nconst FIELD_DEFINITION = \"FieldDefinition\";\nconst INPUT_VALUE_DEFINITION = \"InputValueDefinition\";\nconst INTERFACE_TYPE_DEFINITION = \"InterfaceTypeDefinition\";\nconst UNION_TYPE_DEFINITION = \"UnionTypeDefinition\";\nconst ENUM_TYPE_DEFINITION = \"EnumTypeDefinition\";\nconst ENUM_VALUE_DEFINITION = \"EnumValueDefinition\";\nconst INPUT_OBJECT_TYPE_DEFINITION = \"InputObjectTypeDefinition\";\nconst SCALAR_TYPE_EXTENSION = \"ScalarTypeExtension\";\nconst OBJECT_TYPE_EXTENSION = \"ObjectTypeExtension\";\nconst INTERFACE_TYPE_EXTENSION = \"InterfaceTypeExtension\";\nconst UNION_TYPE_EXTENSION = \"UnionTypeExtension\";\nconst ENUM_TYPE_EXTENSION = \"EnumTypeExtension\";\nconst INPUT_OBJECT_TYPE_EXTENSION = \"InputObjectTypeExtension\";\nconst DIRECTIVE_DEFINITION = \"DirectiveDefinition\";",
"title": "GraphQL\\Language\\AST\\NodeKind"
},
{
"location": "/reference/#graphqlexecutorexecutor",
"text": "Implements the \"Evaluating requests\" section of the GraphQL specification. Class Methods: /**\n * Executes DocumentNode against given $schema.\n *\n * Always returns ExecutionResult and never throws. All errors which occur during operation\n * execution are collected in `$result->errors`.\n *\n * @api\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param $rootValue\n * @param $contextValue\n * @param array|\\ArrayAccess $variableValues\n * @param null $operationName\n * @param callable $fieldResolver\n *\n * @return ExecutionResult|Promise\n */\nstatic function execute(\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n $rootValue = null,\n $contextValue = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null\n) /**\n * Same as execute(), but requires promise adapter and returns a promise which is always\n * fulfilled with an instance of ExecutionResult and never rejected.\n *\n * Useful for async PHP platforms.\n *\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param null $rootValue\n * @param null $contextValue\n * @param null $variableValues\n * @param null $operationName\n * @param callable|null $fieldResolver\n * @return Promise\n */\nstatic function promiseToExecute(\n GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter,\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n $rootValue = null,\n $contextValue = null,\n $variableValues = null,\n $operationName = null,\n callable $fieldResolver = null\n)",
"title": "GraphQL\\Executor\\Executor"
},
{
"location": "/reference/#graphqlexecutorexecutionresult",
"text": "Returned after query execution .\nRepresents both - result of successful execution and of a failed one\n(with errors collected in errors prop) Could be converted to spec-compliant \nserializable array using toArray() Class Props: /**\n * Data collected from resolvers during query execution\n *\n * @api\n * @var array\n */\npublic $data;\n\n/**\n * Errors registered during query execution.\n *\n * If an error was caused by exception thrown in resolver, $error->getPrevious() would\n * contain original exception.\n *\n * @api\n * @var \\GraphQL\\Error\\Error[]\n */\npublic $errors;\n\n/**\n * User-defined serializable array of extensions included in serialized result.\n * Conforms to\n *\n * @api\n * @var array\n */\npublic $extensions; Class Methods: /**\n * Define custom error formatting (must conform to http://facebook.github.io/graphql/#sec-Errors)\n *\n * Expected signature is: function (GraphQL\\Error\\Error $error): array\n *\n * Default formatter is \"GraphQL\\Error\\FormattedError::createFromException\"\n *\n * Expected returned value must be an array:\n * array(\n * 'message' => 'errorMessage',\n * // ... other keys\n * );\n *\n * @api\n * @param callable $errorFormatter\n * @return $this\n */\nfunction setErrorFormatter(callable $errorFormatter) /**\n * Define custom logic for error handling (filtering, logging, etc).\n *\n * Expected handler signature is: function (array $errors, callable $formatter): array\n *\n * Default handler is:\n * function (array $errors, callable $formatter) {\n * return array_map($formatter, $errors);\n * }\n *\n * @api\n * @param callable $handler\n * @return $this\n */\nfunction setErrorsHandler(callable $handler) /**\n * Converts GraphQL query result to spec-compliant serializable array using provided\n * errors handler and formatter.\n *\n * If debug argument is passed, output of error formatter is enriched which debugging information\n * (\"debugMessage\", \"trace\" keys depending on flags).\n *\n * $debug argument must be either bool (only adds \"debugMessage\" to result) or sum of flags from\n * GraphQL\\Error\\Debug\n *\n * @api\n * @param bool|int $debug\n * @return array\n */\nfunction toArray($debug = false)",
"title": "GraphQL\\Executor\\ExecutionResult"
},
{
"location": "/reference/#graphqlexecutorpromisepromiseadapter",
"text": "Provides a means for integration of async PHP platforms ( related docs ) Interface Methods: /**\n * Return true if the value is a promise or a deferred of the underlying platform\n *\n * @api\n * @param mixed $value\n * @return bool\n */\nfunction isThenable($value) /**\n * Converts thenable of the underlying platform into GraphQL\\Executor\\Promise\\Promise instance\n *\n * @api\n * @param object $thenable\n * @return Promise\n */\nfunction convertThenable($thenable) /**\n * Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described\n * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\\Executor\\Promise\\Promise.\n *\n * @api\n * @param Promise $promise\n * @param callable|null $onFulfilled\n * @param callable|null $onRejected\n *\n * @return Promise\n */\nfunction then(\n GraphQL\\Executor\\Promise\\Promise $promise,\n callable $onFulfilled = null,\n callable $onRejected = null\n) /**\n * Creates a Promise\n *\n * Expected resolver signature:\n * function(callable $resolve, callable $reject)\n *\n * @api\n * @param callable $resolver\n * @return Promise\n */\nfunction create(callable $resolver) /**\n * Creates a fulfilled Promise for a value if the value is not a promise.\n *\n * @api\n * @param mixed $value\n * @return Promise\n */\nfunction createFulfilled($value = null) /**\n * Creates a rejected promise for a reason if the reason is not a promise. If\n * the provided reason is a promise, then it is returned as-is.\n *\n * @api\n * @param \\Throwable $reason\n * @return Promise\n */\nfunction createRejected($reason) /**\n * Given an array of promises (or values), returns a promise that is fulfilled when all the\n * items in the array are fulfilled.\n *\n * @api\n * @param array $promisesOrValues Promises or values.\n * @return Promise\n */\nfunction all(array $promisesOrValues)",
"title": "GraphQL\\Executor\\Promise\\PromiseAdapter"
},
{
"location": "/reference/#graphqlvalidatordocumentvalidator",
"text": "Implements the \"Validation\" section of the spec. Validation runs synchronously, returning an array of encountered errors, or\nan empty array if no errors were encountered and the document is valid. A list of specific validation rules may be provided. If not provided, the\ndefault list of rules defined by the GraphQL specification will be used. Each validation rule is an instance of GraphQL\\Validator\\Rules\\AbstractValidationRule\nwhich returns a visitor (see the GraphQL\\Language\\Visitor API ). Visitor methods are expected to return an instance of GraphQL\\Error\\Error ,\nor array of such instances when invalid. Optionally a custom TypeInfo instance may be provided. If not provided, one\nwill be created from the provided schema. Class Methods: /**\n * Primary method for query validation. See class description for details.\n *\n * @api\n * @param Schema $schema\n * @param DocumentNode $ast\n * @param AbstractValidationRule[]|null $rules\n * @param TypeInfo|null $typeInfo\n * @return Error[]\n */\nstatic function validate(\n GraphQL\\Type\\Schema $schema,\n GraphQL\\Language\\AST\\DocumentNode $ast,\n array $rules = null,\n GraphQL\\Utils\\TypeInfo $typeInfo = null\n) /**\n * Returns all global validation rules.\n *\n * @api\n * @return AbstractValidationRule[]\n */\nstatic function allRules() /**\n * Returns global validation rule by name. Standard rules are named by class name, so\n * example usage for such rules:\n *\n * $rule = DocumentValidator::getRule(GraphQL\\Validator\\Rules\\QueryComplexity::class);\n *\n * @api\n * @param string $name\n * @return AbstractValidationRule\n */\nstatic function getRule($name) /**\n * Add rule to list of global validation rules\n *\n * @api\n * @param AbstractValidationRule $rule\n */\nstatic function addRule(GraphQL\\Validator\\Rules\\AbstractValidationRule $rule)",
"title": "GraphQL\\Validator\\DocumentValidator"
},
{
"location": "/reference/#graphqlerrorerror",
"text": "Describes an Error found during the parse, validate, or\nexecute phases of performing a GraphQL operation. In addition to a message\nand stack trace, it also includes information about the locations in a\nGraphQL document and/or execution result that correspond to the Error. When the error was caused by an exception thrown in resolver, original exception\nis available via getPrevious() . Also read related docs on error handling Class extends standard PHP \\Exception , so all standard methods of base \\Exception class\nare available in addition to those listed below. Class Constants: const CATEGORY_GRAPHQL = \"graphql\";\nconst CATEGORY_INTERNAL = \"internal\"; Class Methods: /**\n * An array of locations within the source GraphQL document which correspond to this error.\n *\n * Each entry has information about `line` and `column` within source GraphQL document:\n * $location->line;\n * $location->column;\n *\n * Errors during validation often contain multiple locations, for example to\n * point out to field mentioned in multiple fragments. Errors during execution include a\n * single location, the field which produced the error.\n *\n * @api\n * @return SourceLocation[]\n */\nfunction getLocations() /**\n * Returns an array describing the path from the root value to the field which produced this error.\n * Only included for execution errors.\n *\n * @api\n * @return array|null\n */\nfunction getPath()",
"title": "GraphQL\\Error\\Error"
},
{
"location": "/reference/#graphqlerrorwarning",
"text": "Encapsulates warnings produced by the library. Warnings can be suppressed (individually or all) if required.\nAlso it is possible to override warning handler (which is trigger_error() by default) Class Constants: const WARNING_ASSIGN = 2;\nconst WARNING_CONFIG = 4;\nconst WARNING_FULL_SCHEMA_SCAN = 8;\nconst WARNING_CONFIG_DEPRECATION = 16;\nconst WARNING_NOT_A_TYPE = 32;\nconst ALL = 63; Class Methods: /**\n * Sets warning handler which can intercept all system warnings.\n * When not set, trigger_error() is used to notify about warnings.\n *\n * @api\n * @param callable|null $warningHandler\n */\nstatic function setWarningHandler(callable $warningHandler = null) /**\n * Suppress warning by id (has no effect when custom warning handler is set)\n *\n * Usage example:\n * Warning::suppress(Warning::WARNING_NOT_A_TYPE)\n *\n * When passing true - suppresses all warnings.\n *\n * @api\n * @param bool|int $suppress\n */\nstatic function suppress($suppress = true) /**\n * Re-enable previously suppressed warning by id\n *\n * Usage example:\n * Warning::suppress(Warning::WARNING_NOT_A_TYPE)\n *\n * When passing true - re-enables all warnings.\n *\n * @api\n * @param bool|int $enable\n */\nstatic function enable($enable = true)",
"title": "GraphQL\\Error\\Warning"
},
{
"location": "/reference/#graphqlerrorclientaware",
"text": "This interface is used for default error formatting . Only errors implementing this interface (and returning true from isClientSafe() )\nwill be formatted with original error message. All other errors will be formatted with generic \"Internal server error\". Interface Methods: /**\n * Returns true when exception message is safe to be displayed to a client.\n *\n * @api\n * @return bool\n */\nfunction isClientSafe() /**\n * Returns string describing a category of the error.\n *\n * Value \"graphql\" is reserved for errors produced by query parsing or validation, do not use it.\n *\n * @api\n * @return string\n */\nfunction getCategory()",
"title": "GraphQL\\Error\\ClientAware"
},
{
"location": "/reference/#graphqlerrordebug",
"text": "Collection of flags for error debugging . Class Constants: const INCLUDE_DEBUG_MESSAGE = 1;\nconst INCLUDE_TRACE = 2;\nconst RETHROW_INTERNAL_EXCEPTIONS = 4;",
"title": "GraphQL\\Error\\Debug"
},
{
"location": "/reference/#graphqlerrorformattederror",
"text": "This class is used for default error formatting .\nIt converts PHP exceptions to spec-compliant errors \nand provides tools for error debugging. Class Methods: /**\n * Set default error message for internal errors formatted using createFormattedError().\n * This value can be overridden by passing 3rd argument to `createFormattedError()`.\n *\n * @api\n * @param string $msg\n */\nstatic function setInternalErrorMessage($msg) /**\n * Standard GraphQL error formatter. Converts any exception to array\n * conforming to GraphQL spec.\n *\n * This method only exposes exception message when exception implements ClientAware interface\n * (or when debug flags are passed).\n *\n * For a list of available debug flags see GraphQL\\Error\\Debug constants.\n *\n * @api\n * @param \\Throwable $e\n * @param bool|int $debug\n * @param string $internalErrorMessage\n * @return array\n * @throws \\Throwable\n */\nstatic function createFromException($e, $debug = false, $internalErrorMessage = null) /**\n * Returns error trace as serializable array\n *\n * @api\n * @param \\Throwable $error\n * @return array\n */\nstatic function toSafeTrace($error)",
"title": "GraphQL\\Error\\FormattedError"
},
{
"location": "/reference/#graphqlserverstandardserver",
"text": "GraphQL server compatible with both: express-graphql \nand Apollo Server .\nUsage Example: $server = new StandardServer([\n 'schema' => $mySchema\n]);\n$server->handleRequest(); Or using ServerConfig instance: $config = GraphQL\\Server\\ServerConfig::create()\n ->setSchema($mySchema)\n ->setContext($myContext);\n\n$server = new GraphQL\\Server\\StandardServer($config);\n$server->handleRequest(); See dedicated section in docs for details. Class Methods: /**\n * Converts and exception to error and sends spec-compliant HTTP 500 error.\n * Useful when an exception is thrown somewhere outside of server execution context\n * (e.g. during schema instantiation).\n *\n * @api\n * @param \\Throwable $error\n * @param bool $debug\n * @param bool $exitWhenDone\n */\nstatic function send500Error($error, $debug = false, $exitWhenDone = false) /**\n * Creates new instance of a standard GraphQL HTTP server\n *\n * @api\n * @param ServerConfig|array $config\n */\nfunction __construct($config) /**\n * Parses HTTP request, executes and emits response (using standard PHP `header` function and `echo`)\n *\n * By default (when $parsedBody is not set) it uses PHP globals to parse a request.\n * It is possible to implement request parsing elsewhere (e.g. using framework Request instance)\n * and then pass it to the server.\n *\n * See `executeRequest()` if you prefer to emit response yourself\n * (e.g. using Response object of some framework)\n *\n * @api\n * @param OperationParams|OperationParams[] $parsedBody\n * @param bool $exitWhenDone\n */\nfunction handleRequest($parsedBody = null, $exitWhenDone = false) /**\n * Executes GraphQL operation and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter).\n *\n * By default (when $parsedBody is not set) it uses PHP globals to parse a request.\n * It is possible to implement request parsing elsewhere (e.g. using framework Request instance)\n * and then pass it to the server.\n *\n * PSR-7 compatible method executePsrRequest() does exactly this.\n *\n * @api\n * @param OperationParams|OperationParams[] $parsedBody\n * @return ExecutionResult|ExecutionResult[]|Promise\n * @throws InvariantViolation\n */\nfunction executeRequest($parsedBody = null) /**\n * Executes PSR-7 request and fulfills PSR-7 response.\n *\n * See `executePsrRequest()` if you prefer to create response yourself\n * (e.g. using specific JsonResponse instance of some framework).\n *\n * @api\n * @param ServerRequestInterface $request\n * @param ResponseInterface $response\n * @param StreamInterface $writableBodyStream\n * @return ResponseInterface|Promise\n */\nfunction processPsrRequest(\n Psr\\Http\\Message\\ServerRequestInterface $request,\n Psr\\Http\\Message\\ResponseInterface $response,\n Psr\\Http\\Message\\StreamInterface $writableBodyStream\n) /**\n * Executes GraphQL operation and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter)\n *\n * @api\n * @param ServerRequestInterface $request\n * @return ExecutionResult|ExecutionResult[]|Promise\n */\nfunction executePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /**\n * Returns an instance of Server helper, which contains most of the actual logic for\n * parsing / validating / executing request (which could be re-used by other server implementations)\n *\n * @api\n * @return Helper\n */\nfunction getHelper()",
"title": "GraphQL\\Server\\StandardServer"
},
{
"location": "/reference/#graphqlserverserverconfig",
"text": "Server configuration class.\nCould be passed directly to server constructor. List of options accepted by create method is described in docs . Usage example: $config = GraphQL\\Server\\ServerConfig::create()\n ->setSchema($mySchema)\n ->setContext($myContext);\n\n$server = new GraphQL\\Server\\StandardServer($config); Class Methods: /**\n * Converts an array of options to instance of ServerConfig\n * (or just returns empty config when array is not passed).\n *\n * @api\n * @param array $config\n * @return ServerConfig\n */\nstatic function create(array $config = []) /**\n * @api\n * @param Schema $schema\n * @return $this\n */\nfunction setSchema(GraphQL\\Type\\Schema $schema) /**\n * @api\n * @param mixed|\\Closure $context\n * @return $this\n */\nfunction setContext($context) /**\n * @api\n * @param mixed|\\Closure $rootValue\n * @return $this\n */\nfunction setRootValue($rootValue) /**\n * Expects function(Throwable $e) : array\n *\n * @api\n * @param callable $errorFormatter\n * @return $this\n */\nfunction setErrorFormatter(callable $errorFormatter) /**\n * Expects function(array $errors, callable $formatter) : array\n *\n * @api\n * @param callable $handler\n * @return $this\n */\nfunction setErrorsHandler(callable $handler) /**\n * Set validation rules for this server.\n *\n * @api\n * @param array|callable\n * @return $this\n */\nfunction setValidationRules($validationRules) /**\n * @api\n * @param callable $fieldResolver\n * @return $this\n */\nfunction setFieldResolver(callable $fieldResolver) /**\n * Expects function($queryId, OperationParams $params) : string|DocumentNode\n *\n * This function must return query string or valid DocumentNode.\n *\n * @api\n * @param callable $persistentQueryLoader\n * @return $this\n */\nfunction setPersistentQueryLoader(callable $persistentQueryLoader) /**\n * Set response debug flags. See GraphQL\\Error\\Debug class for a list of all available flags\n *\n * @api\n * @param bool|int $set\n * @return $this\n */\nfunction setDebug($set = true) /**\n * Allow batching queries (disabled by default)\n *\n * @api\n * @param bool $enableBatching\n * @return $this\n */\nfunction setQueryBatching($enableBatching) /**\n * @api\n * @param PromiseAdapter $promiseAdapter\n * @return $this\n */\nfunction setPromiseAdapter(GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter)",
"title": "GraphQL\\Server\\ServerConfig"
},
{
"location": "/reference/#graphqlserverhelper",
"text": "Contains functionality that could be re-used by various server implementations Class Methods: /**\n * Parses HTTP request using PHP globals and returns GraphQL OperationParams\n * contained in this request. For batched requests it returns an array of OperationParams.\n *\n * This function does not check validity of these params\n * (validation is performed separately in validateOperationParams() method).\n *\n * If $readRawBodyFn argument is not provided - will attempt to read raw request body\n * from `php://input` stream.\n *\n * Internally it normalizes input to $method, $bodyParams and $queryParams and\n * calls `parseRequestParams()` to produce actual return value.\n *\n * For PSR-7 request parsing use `parsePsrRequest()` instead.\n *\n * @api\n * @param callable|null $readRawBodyFn\n * @return OperationParams|OperationParams[]\n * @throws RequestError\n */\nfunction parseHttpRequest(callable $readRawBodyFn = null) /**\n * Parses normalized request params and returns instance of OperationParams\n * or array of OperationParams in case of batch operation.\n *\n * Returned value is a suitable input for `executeOperation` or `executeBatch` (if array)\n *\n * @api\n * @param string $method\n * @param array $bodyParams\n * @param array $queryParams\n * @return OperationParams|OperationParams[]\n * @throws RequestError\n */\nfunction parseRequestParams($method, array $bodyParams, array $queryParams) /**\n * Checks validity of OperationParams extracted from HTTP request and returns an array of errors\n * if params are invalid (or empty array when params are valid)\n *\n * @api\n * @param OperationParams $params\n * @return Error[]\n */\nfunction validateOperationParams(GraphQL\\Server\\OperationParams $params) /**\n * Executes GraphQL operation with given server configuration and returns execution result\n * (or promise when promise adapter is different from SyncPromiseAdapter)\n *\n * @api\n * @param ServerConfig $config\n * @param OperationParams $op\n *\n * @return ExecutionResult|Promise\n */\nfunction executeOperation(GraphQL\\Server\\ServerConfig $config, GraphQL\\Server\\OperationParams $op) /**\n * Executes batched GraphQL operations with shared promise queue\n * (thus, effectively batching deferreds|promises of all queries at once)\n *\n * @api\n * @param ServerConfig $config\n * @param OperationParams[] $operations\n * @return ExecutionResult[]|Promise\n */\nfunction executeBatch(GraphQL\\Server\\ServerConfig $config, array $operations) /**\n * Send response using standard PHP `header()` and `echo`.\n *\n * @api\n * @param Promise|ExecutionResult|ExecutionResult[] $result\n * @param bool $exitWhenDone\n */\nfunction sendResponse($result, $exitWhenDone = false) /**\n * Converts PSR-7 request to OperationParams[]\n *\n * @api\n * @param ServerRequestInterface $request\n * @return array|Helper\n * @throws RequestError\n */\nfunction parsePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /**\n * Converts query execution result to PSR-7 response\n *\n * @api\n * @param Promise|ExecutionResult|ExecutionResult[] $result\n * @param ResponseInterface $response\n * @param StreamInterface $writableBodyStream\n * @return Promise|ResponseInterface\n */\nfunction toPsrResponse(\n $result,\n Psr\\Http\\Message\\ResponseInterface $response,\n Psr\\Http\\Message\\StreamInterface $writableBodyStream\n)",
"title": "GraphQL\\Server\\Helper"
},
{
"location": "/reference/#graphqlserveroperationparams",
"text": "Structure representing parsed HTTP parameters for GraphQL operation Class Props: /**\n * Id of the query (when using persistent queries).\n *\n * Valid aliases (case-insensitive):\n * - id\n * - queryId\n * - documentId\n *\n * @api\n * @var string\n */\npublic $queryId;\n\n/**\n * @api\n * @var string\n */\npublic $query;\n\n/**\n * @api\n * @var string\n */\npublic $operation;\n\n/**\n * @api\n * @var array\n */\npublic $variables; Class Methods: /**\n * Creates an instance from given array\n *\n * @api\n * @param array $params\n * @param bool $readonly\n * @return OperationParams\n */\nstatic function create(array $params, $readonly = false) /**\n * @api\n * @param string $key\n * @return mixed\n */\nfunction getOriginalInput($key) /**\n * Indicates that operation is executed in read-only context\n * (e.g. via HTTP GET request)\n *\n * @api\n * @return bool\n */\nfunction isReadOnly()",
"title": "GraphQL\\Server\\OperationParams"
},
{
"location": "/reference/#graphqlutilsbuildschema",
"text": "Build instance of GraphQL\\Type\\Schema out of type language definition (string or parsed AST)\nSee section in docs for details. Class Methods: /**\n * This takes the ast of a schema document produced by the parse function in\n * GraphQL\\Language\\Parser.\n *\n * If no schema definition is provided, then it will look for types named Query\n * and Mutation.\n *\n * Given that AST it constructs a GraphQL\\Type\\Schema. The resulting schema\n * has no resolve methods, so execution will use default resolvers.\n *\n * Accepts options as a second argument:\n *\n * - commentDescriptions:\n * Provide true to use preceding comments as the description.\n *\n *\n * @api\n * @param DocumentNode $ast\n * @param array $options\n * @return Schema\n * @throws Error\n */\nstatic function buildAST(GraphQL\\Language\\AST\\DocumentNode $ast, array $options = []) /**\n * A helper function to build a GraphQLSchema directly from a source\n * document.\n *\n * @api\n * @param DocumentNode|Source|string $source\n * @param array $options\n * @return Schema\n */\nstatic function build($source, array $options = [])",
"title": "GraphQL\\Utils\\BuildSchema"
},
{
"location": "/reference/#graphqlutilsast",
"text": "Various utilities dealing with AST Class Methods: /**\n * Convert representation of AST as an associative array to instance of GraphQL\\Language\\AST\\Node.\n *\n * For example:\n *\n * ```php\n * AST::fromArray([\n * 'kind' => 'ListValue',\n * 'values' => [\n * ['kind' => 'StringValue', 'value' => 'my str'],\n * ['kind' => 'StringValue', 'value' => 'my other str']\n * ],\n * 'loc' => ['start' => 21, 'end' => 25]\n * ]);\n * ```\n *\n * Will produce instance of `ListValueNode` where `values` prop is a lazily-evaluated `NodeList`\n * returning instances of `StringValueNode` on access.\n *\n * This is a reverse operation for AST::toArray($node)\n *\n * @api\n * @param array $node\n * @return Node\n */\nstatic function fromArray(array $node) /**\n * Convert AST node to serializable array\n *\n * @api\n * @param Node $node\n * @return array\n */\nstatic function toArray(GraphQL\\Language\\AST\\Node $node) /**\n * Produces a GraphQL Value AST given a PHP value.\n *\n * Optionally, a GraphQL type may be provided, which will be used to\n * disambiguate between value primitives.\n *\n * | PHP Value | GraphQL Value |\n * | ------------- | -------------------- |\n * | Object | Input Object |\n * | Assoc Array | Input Object |\n * | Array | List |\n * | Boolean | Boolean |\n * | String | String / Enum Value |\n * | Int | Int |\n * | Float | Int / Float |\n * | Mixed | Enum Value |\n * | null | NullValue |\n *\n * @api\n * @param $value\n * @param InputType $type\n * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode\n */\nstatic function astFromValue($value, GraphQL\\Type\\Definition\\InputType $type) /**\n * Produces a PHP value given a GraphQL Value AST.\n *\n * A GraphQL type must be provided, which will be used to interpret different\n * GraphQL Value literals.\n *\n * Returns `null` when the value could not be validly coerced according to\n * the provided type.\n *\n * | GraphQL Value | PHP Value |\n * | -------------------- | ------------- |\n * | Input Object | Assoc Array |\n * | List | Array |\n * | Boolean | Boolean |\n * | String | String |\n * | Int / Float | Int / Float |\n * | Enum Value | Mixed |\n * | Null Value | null |\n *\n * @api\n * @param $valueNode\n * @param InputType $type\n * @param null $variables\n * @return array|null|\\stdClass\n * @throws \\Exception\n */\nstatic function valueFromAST($valueNode, GraphQL\\Type\\Definition\\InputType $type, $variables = null) /**\n * Produces a PHP value given a GraphQL Value AST.\n *\n * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value\n * will reflect the provided GraphQL value AST.\n *\n * | GraphQL Value | PHP Value |\n * | -------------------- | ------------- |\n * | Input Object | Assoc Array |\n * | List | Array |\n * | Boolean | Boolean |\n * | String | String |\n * | Int / Float | Int / Float |\n * | Enum | Mixed |\n * | Null | null |\n *\n * @api\n * @param Node $valueNode\n * @param array|null $variables\n * @return mixed\n * @throws \\Exception\n */\nstatic function valueFromASTUntyped($valueNode, array $variables = null) /**\n * Returns type definition for given AST Type node\n *\n * @api\n * @param Schema $schema\n * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode\n * @return Type\n * @throws \\Exception\n */\nstatic function typeFromAST(GraphQL\\Type\\Schema $schema, $inputTypeNode) /**\n * Returns operation type (\"query\", \"mutation\" or \"subscription\") given a document and operation name\n *\n * @api\n * @param DocumentNode $document\n * @param string $operationName\n * @return bool\n */\nstatic function getOperation(GraphQL\\Language\\AST\\DocumentNode $document, $operationName = null)",
"title": "GraphQL\\Utils\\AST"
},
{
"location": "/reference/#graphqlutilsschemaprinter",
"text": "Given an instance of Schema, prints it in GraphQL type language. Class Methods: /**\n * Accepts options as a second argument:\n *\n * - commentDescriptions:\n * Provide true to use preceding comments as the description.\n * @api\n * @param Schema $schema\n * @return string\n */\nstatic function doPrint(GraphQL\\Type\\Schema $schema, array $options = []) /**\n * @api\n * @param Schema $schema\n * @return string\n */\nstatic function printIntrosepctionSchema(GraphQL\\Type\\Schema $schema, array $options = [])",
"title": "GraphQL\\Utils\\SchemaPrinter"
}
]
}