mirror of
https://github.com/retailcrm/graphql-php.git
synced 2024-11-25 14:26:08 +03:00
1 line
242 KiB
JSON
Executable File
1 line
242 KiB
JSON
Executable File
{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"About GraphQL GraphQL is a modern way to build HTTP APIs consumed by the web and mobile clients. It is intended to be a replacement for REST and SOAP APIs (even for existing applications ). GraphQL itself is a specification designed by Facebook engineers. 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 . All of them equally apply to this PHP implementation. About graphql-php graphql-php is a feature-complete implementation of GraphQL specification in PHP (5.5+, 7.0+). It was originally inspired by reference JavaScript implementation published by Facebook. This library is a thin wrapper around your existing data layer and business logic. It doesn't dictate how these layers are implemented or which storage engines are 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 existing PHP frameworks, add support for Relay, etc. Current Status The first version of this library (v0.1) was released on August 10th 2015. The current version supports all features described by GraphQL specification as well as some experimental features like Schema Language parser and Schema printer . Ready for real-world usage. GitHub Project source code is hosted on GitHub .","title":"About"},{"location":"#about-graphql","text":"GraphQL is a modern way to build HTTP APIs consumed by the web and mobile clients. It is intended to be a replacement for REST and SOAP APIs (even for existing applications ). GraphQL itself is a specification designed by Facebook engineers. 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 . All 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+). It was originally inspired by reference JavaScript implementation published by Facebook. This library is a thin wrapper around your existing data layer and business logic. It doesn't dictate how these layers are implemented or which storage engines are 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 existing 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 supports all features described by GraphQL specification 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":"best-practices/","text":"Type Registry graphql-php expects that each type in Schema is presented by single instance. Therefore if you define your types as separate PHP classes you need to ensure that each type is referenced only once. Technically you can create several instances of your type (for example for tests), but GraphQL\\Type\\Schema will throw on attempt to add different instances with the same name. There are several ways to achieve this depending on your preferences. We provide reference implementation below that introduces TypeRegistry class:","title":"Type Registry"},{"location":"best-practices/#type-registry","text":"graphql-php expects that each type in Schema is presented by single instance. Therefore if you define your types as separate PHP classes you need to ensure that each type is referenced only once. Technically you can create several instances of your type (for example for tests), but GraphQL\\Type\\Schema will throw on attempt to add different instances with the same name. There are several ways to achieve this depending on your preferences. We provide reference implementation below that introduces TypeRegistry class:","title":"Type Registry"},{"location":"complementary-tools/","text":"Integrations 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 GraphQL PHP Tools 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. General GraphQL Tools GraphiQL - An in-browser IDE for exploring GraphQL ChromeiQL or GraphiQL Feen - 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 or GraphiQL Feen - GraphiQL as Google Chrome extension","title":"General GraphQL Tools"},{"location":"concepts/","text":"Overview GraphQL is data-centric. On the very top level it is built around three major concepts: Schema , Query and Mutation . You are expected to express your application as Schema (aka Type System) and expose it with single HTTP endpoint (e.g. using our standard server ). Application clients (e.g. web or mobile clients) send Queries to this endpoint to request structured data and Mutations to perform changes (usually with HTTP POST method). Queries Queries are expressed in simple language that resembles JSON: { hero { name friends { name } } } It was designed to mirror the structure of expected response: { \"hero\": { \"name\": \"R2-D2\", \"friends\": [ {\"name\": \"Luke Skywalker\"}, {\"name\": \"Han Solo\"}, {\"name\": \"Leia Organa\"} ] } } graphql-php runtime parses Queries, makes sure that they are valid for given Type System and executes using data fetching tools provided by you as a part of integration. Queries are supposed to be idempotent. Mutations Mutations use advanced features of the very same query language (like arguments and variables) and have only semantic difference from Queries: mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } } Variables $ep and $review are sent alongside with mutation. Full HTTP request might look like this: // POST /graphql-endpoint // Content-Type: application/javascript // { \"query\": \"mutation CreateReviewForEpisode...\", \"variables\": { \"ep\": \"JEDI\", \"review\": { \"stars\": 5, \"commentary\": \"This is a great movie!\" } } } As you see variables may include complex objects and they will be correctly validated by graphql-php runtime. Another nice feature of GraphQL mutations is that they also hold the query for data to be returned after mutation. In our example mutation will return: { \"createReview\": { \"stars\": 5, \"commentary\": \"This is a great movie!\" } } Type System Conceptually GraphQL type is a collection of fields. Each field in turn has it's own type which allows to build complex hierarchies. Quick example on pseudo-language: type BlogPost { title: String! author: User body: String } type User { id: Id! firstName: String lastName: String } Type system is a heart of GraphQL integration. That's where graphql-php comes into play. It provides following tools and primitives to describe your App as hierarchy of types: Primitives for defining objects and interfaces Primitives for defining enumerations and unions Primitives for defining custom scalar types Built-in scalar types: ID , String , Int , Float , Boolean Built-in type modifiers: ListOf and NonNull Same example expressed in graphql-php : <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::nonNull(Type::id()), 'firstName' => Type::string(), 'lastName' => Type::string() ] ]); $blogPostType = new ObjectType([ 'name' => 'BlogPost', 'fields' => [ 'title' => Type::nonNull(Type::string()), 'author' => $userType ] ]); Further Reading To get deeper understanding of GraphQL concepts - read the docs on official GraphQL website To get started with graphql-php - continue to next section \"Getting Started\"","title":"Overview"},{"location":"concepts/#overview","text":"GraphQL is data-centric. On the very top level it is built around three major concepts: Schema , Query and Mutation . You are expected to express your application as Schema (aka Type System) and expose it with single HTTP endpoint (e.g. using our standard server ). Application clients (e.g. web or mobile clients) send Queries to this endpoint to request structured data and Mutations to perform changes (usually with HTTP POST method).","title":"Overview"},{"location":"concepts/#queries","text":"Queries are expressed in simple language that resembles JSON: { hero { name friends { name } } } It was designed to mirror the structure of expected response: { \"hero\": { \"name\": \"R2-D2\", \"friends\": [ {\"name\": \"Luke Skywalker\"}, {\"name\": \"Han Solo\"}, {\"name\": \"Leia Organa\"} ] } } graphql-php runtime parses Queries, makes sure that they are valid for given Type System and executes using data fetching tools provided by you as a part of integration. Queries are supposed to be idempotent.","title":"Queries"},{"location":"concepts/#mutations","text":"Mutations use advanced features of the very same query language (like arguments and variables) and have only semantic difference from Queries: mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } } Variables $ep and $review are sent alongside with mutation. Full HTTP request might look like this: // POST /graphql-endpoint // Content-Type: application/javascript // { \"query\": \"mutation CreateReviewForEpisode...\", \"variables\": { \"ep\": \"JEDI\", \"review\": { \"stars\": 5, \"commentary\": \"This is a great movie!\" } } } As you see variables may include complex objects and they will be correctly validated by graphql-php runtime. Another nice feature of GraphQL mutations is that they also hold the query for data to be returned after mutation. In our example mutation will return: { \"createReview\": { \"stars\": 5, \"commentary\": \"This is a great movie!\" } }","title":"Mutations"},{"location":"concepts/#type-system","text":"Conceptually GraphQL type is a collection of fields. Each field in turn has it's own type which allows to build complex hierarchies. Quick example on pseudo-language: type BlogPost { title: String! author: User body: String } type User { id: Id! firstName: String lastName: String } Type system is a heart of GraphQL integration. That's where graphql-php comes into play. It provides following tools and primitives to describe your App as hierarchy of types: Primitives for defining objects and interfaces Primitives for defining enumerations and unions Primitives for defining custom scalar types Built-in scalar types: ID , String , Int , Float , Boolean Built-in type modifiers: ListOf and NonNull Same example expressed in graphql-php : <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::nonNull(Type::id()), 'firstName' => Type::string(), 'lastName' => Type::string() ] ]); $blogPostType = new ObjectType([ 'name' => 'BlogPost', 'fields' => [ 'title' => Type::nonNull(Type::string()), 'author' => $userType ] ]);","title":"Type System"},{"location":"concepts/#further-reading","text":"To get deeper understanding of GraphQL concepts - read the docs on official GraphQL website To get started with graphql-php - continue to next section \"Getting Started\"","title":"Further Reading"},{"location":"data-fetching/","text":"Overview GraphQL is data-storage agnostic. You can use any underlying data storage engine, including SQL or NoSQL database, plain 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 runs 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) or passed down to nested fields (for objects). Let's walk through an example. Consider following GraphQL query: { lastStory { title author { name } } } We need a Schema that can fulfill it. On the very top level the Schema contains Query type: <?php use GraphQL\\Type\\Definition\\ObjectType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'lastStory' => [ 'type' => $blogStoryType, 'resolve' => function() { return [ 'id' => 1, 'title' => 'Example blog post', 'authorId' => 1 ]; } ] ] ]); 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 your 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $blogStoryType = new ObjectType([ 'name' => 'BlogStory', 'fields' => [ 'author' => [ 'type' => $userType, 'resolve' => function($blogStory) { $users = [ 1 => [ 'id' => 1, 'name' => 'Smith' ], 2 => [ 'id' => 2, 'name' => 'Anderson' ] ]; return $users[$blogStory['authorId']]; } ], 'title' => [ 'type' => Type::string() ] ] ]); 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. Also, note that you don't have to return arrays. You can return any value, graphql-php will pass it untouched to 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 for a field you simply override this default resolver. Default Field Resolver graphql-php provides following default field resolver: <?php function defaultFieldResolver($source, $args, $context, \\GraphQL\\Type\\Definition\\ResolveInfo $info) { $fieldName = $info->fieldName; $property = null; if (is_array($source) || $source instanceof \\ArrayAccess) { if (isset($source[$fieldName])) { $property = $source[$fieldName]; } } else if (is_object($source)) { if (isset($source->{$fieldName})) { $property = $source->{$fieldName}; } } return $property instanceof \\Closure ? $property($source, $args, $context) : $property; } As you see it returns value by key (for arrays) or property (for objects). If the value is not set - it returns null . To override the default resolver, pass it as an argument of executeQuery call. Default Field Resolver per Type 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\ResolveInfo; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'name' => Type::string(), 'email' => Type::string() ], 'resolveField' => function(User $user, $args, $context, ResolveInfo $info) { switch ($info->fieldName) { case 'name': return $user->getName(); case 'email': return $user->getEmail(); default: return null; } } ]); Keep in mind that field resolver has precedence over default field resolver per type which in turn has precedence over default field resolver . Solving N+1 Problem Since: 0.9.0 One of the most annoying problems with data fetching is a so-called N+1 problem . Consider following GraphQL query: { topStories(limit: 10) { title author { name email } } } 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 when 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 'resolve' => function($blogStory) { MyUserBuffer::add($blogStory['authorId']); return new GraphQL\\Deferred(function () use ($blogStory) { MyUserBuffer::loadBuffered(); return MyUserBuffer::get($blogStory['authorId']); }); } In this example, we fill up the buffer with 10 author ids first. Then graphql-php continues resolving 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 ids 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 project. This solution enables very interesting optimizations at no cost. Consider the following query: { topStories(limit: 10) { author { email } } category { stories(limit: 10) { author { email } } } } Even though author field is located on different levels of the query - it can be buffered in the same buffer. In this example, only one query will be executed for all story authors comparing to 20 queries in a naive implementation. Async PHP 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 (like HHVM, ReactPHP, Icicle.io, appserver.io, PHP threads, etc) you 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 use GraphQL\\GraphQL; use GraphQL\\Executor\\ExecutionResult; $promise = GraphQL::promiseToExecute( $promiseAdapter, $schema, $queryString, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, $fieldResolver = null, $validationRules = null ); $promise->then(function(ExecutionResult $result) { return $result->toArray(); }); Where $promiseAdapter is an instance of: For ReactPHP (requires react/promise as composer dependency): GraphQL\\Executor\\Promise\\Adapter\\ReactPromiseAdapter Other platforms: write your own class implementing interface: GraphQL\\Executor\\Promise\\PromiseAdapter . Then your resolve functions should return promises of your platform instead of GraphQL\\Deferred s.","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, plain 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 runs 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) or passed down to nested fields (for objects). Let's walk through an example. Consider following GraphQL query: { lastStory { title author { name } } } We need a Schema that can fulfill it. On the very top level the Schema contains Query type: <?php use GraphQL\\Type\\Definition\\ObjectType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'lastStory' => [ 'type' => $blogStoryType, 'resolve' => function() { return [ 'id' => 1, 'title' => 'Example blog post', 'authorId' => 1 ]; } ] ] ]); 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 your 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $blogStoryType = new ObjectType([ 'name' => 'BlogStory', 'fields' => [ 'author' => [ 'type' => $userType, 'resolve' => function($blogStory) { $users = [ 1 => [ 'id' => 1, 'name' => 'Smith' ], 2 => [ 'id' => 2, 'name' => 'Anderson' ] ]; return $users[$blogStory['authorId']]; } ], 'title' => [ 'type' => Type::string() ] ] ]); 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. Also, note that you don't have to return arrays. You can return any value, graphql-php will pass it untouched to 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 for 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 function defaultFieldResolver($source, $args, $context, \\GraphQL\\Type\\Definition\\ResolveInfo $info) { $fieldName = $info->fieldName; $property = null; if (is_array($source) || $source instanceof \\ArrayAccess) { if (isset($source[$fieldName])) { $property = $source[$fieldName]; } } else if (is_object($source)) { if (isset($source->{$fieldName})) { $property = $source->{$fieldName}; } } return $property instanceof \\Closure ? $property($source, $args, $context) : $property; } As you see it returns value by key (for arrays) or property (for objects). If 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\ResolveInfo; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'name' => Type::string(), 'email' => Type::string() ], 'resolveField' => function(User $user, $args, $context, ResolveInfo $info) { switch ($info->fieldName) { case 'name': return $user->getName(); case 'email': return $user->getEmail(); default: return null; } } ]); Keep in mind that field resolver has precedence over default field resolver per type which in turn 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 . Consider following GraphQL query: { topStories(limit: 10) { title author { name email } } } 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 when 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 'resolve' => function($blogStory) { MyUserBuffer::add($blogStory['authorId']); return new GraphQL\\Deferred(function () use ($blogStory) { MyUserBuffer::loadBuffered(); return MyUserBuffer::get($blogStory['authorId']); }); } In this example, we fill up the buffer with 10 author ids first. Then graphql-php continues resolving 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 ids 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 project. This solution enables very interesting optimizations at no cost. Consider the following query: { topStories(limit: 10) { author { email } } category { stories(limit: 10) { author { email } } } } Even though author field is located on different levels of the query - it can be buffered in the same buffer. In this example, only one query will be executed for all story authors comparing to 20 queries in 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 (like HHVM, ReactPHP, Icicle.io, appserver.io, PHP threads, etc) you 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 use GraphQL\\GraphQL; use GraphQL\\Executor\\ExecutionResult; $promise = GraphQL::promiseToExecute( $promiseAdapter, $schema, $queryString, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, $fieldResolver = null, $validationRules = null ); $promise->then(function(ExecutionResult $result) { return $result->toArray(); }); Where $promiseAdapter is an instance of: For ReactPHP (requires react/promise as composer dependency): GraphQL\\Executor\\Promise\\Adapter\\ReactPromiseAdapter Other platforms: write your own class implementing interface: 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 Query execution process never throws exceptions. Instead, all errors are caught and collected. After 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 converted to arrays as well using default error formatting (see below). Alternatively, you can apply custom error filtering and formatting for your specific requirements. Default Error formatting By default, each error entry is converted to an associative array with following structure: <?php [ 'message' => 'Error message', 'category' => 'graphql', 'locations' => [ ['line' => 1, 'column' => 2] ], 'path' => [ 'listField', 0, 'fieldWithException' ] ]; Entry at key locations points to a character in query string which caused the error. In some cases (like deep fragment fields) locations will include several entries to track down the path to field with the error in query. Entry at key path exists only for errors caused by exceptions thrown in resolvers. It contains a path from the very root field to actual field value producing an error (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\" . This 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 be reported with a full error message. For example: <?php use GraphQL\\Error\\ClientAware; class MySafeException extends \\Exception implements ClientAware { public function isClientSafe() { return true; } public function getCategory() { return 'businessLogic'; } } When such exception is thrown it will be reported with a full error message: <?php [ 'message' => 'My reported error', 'category' => 'businessLogic', 'locations' => [ ['line' => 10, 'column' => 2] ], 'path' => [ 'path', 'to', 'fieldWithException' ] ]; To change default \"Internal server error\" message to something else, use: GraphQL\\Error\\FormattedError::setInternalErrorMessage(\"Unexpected error\"); Debugging tools During development or debugging use $result->toArray(true) to add debugMessage key to each formatted error entry. If you also want to add exception trace - pass flags instead: use GraphQL\\Error\\Debug; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE; $result = GraphQL::executeQuery(/*args*/)->toArray($debug); This will make each error entry to look like this: <?php [ 'debugMessage' => 'Actual exception message', 'message' => 'Internal server error', 'category' => 'internal', 'locations' => [ ['line' => 10, 'column' => 2] ], 'path' => [ 'listField', 0, 'fieldWithException' ], 'trace' => [ /* Formatted original exception trace */ ] ]; If you prefer first resolver exception to be re-thrown, use following flags: <?php use GraphQL\\GraphQL; use GraphQL\\Error\\Debug; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::RETHROW_INTERNAL_EXCEPTIONS; // Following will throw if there was an exception in resolver during execution: $result = GraphQL::executeQuery(/*args*/)->toArray($debug); Custom Error Handling and Formatting It is possible to define custom formatter and handler for result errors. Formatter is responsible for converting instances of GraphQL\\Error\\Error to an array. Handler is useful for error filtering and logging. For example, these are default formatter and handler: <?php use GraphQL\\GraphQL; use GraphQL\\Error\\Error; use GraphQL\\Error\\FormattedError; $myErrorFormatter = function(Error $error) { return FormattedError::createFromException($error); }; $myErrorHandler = function(array $errors, callable $formatter) { return array_map($formatter, $errors); }; $result = GraphQL::executeQuery(/* $args */) ->setErrorFormatter($myErrorFormatter) ->setErrorsHandler($myErrorHandler) ->toArray(); Note that when you pass debug flags to toArray() your custom formatter will still be decorated with same debugging information mentioned above. Schema Errors So far we only covered errors which occur during query execution process. But schema definition can also 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 when it makes sense to return 500 error code for GraphQL endpoint: <?php use GraphQL\\GraphQL; use GraphQL\\Type\\Schema; use GraphQL\\Error\\FormattedError; try { $schema = new Schema([ // ... ]); $body = GraphQL::executeQuery($schema, $query); $status = 200; } catch(\\Exception $e) { $body = [ 'errors' => [FormattedError::createFromException($e)] ]; $status = 500; } header('Content-Type: application/json', true, $status); echo 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. After 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 converted to arrays as well using default error formatting (see below). Alternatively, you can apply custom error filtering and formatting for 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 [ 'message' => 'Error message', 'category' => 'graphql', 'locations' => [ ['line' => 1, 'column' => 2] ], 'path' => [ 'listField', 0, 'fieldWithException' ] ]; Entry at key locations points to a character in query string which caused the error. In some cases (like deep fragment fields) locations will include several entries to track down the path to field with the error in query. Entry at key path exists only for errors caused by exceptions thrown in resolvers. It contains a path from the very root field to actual field value producing an error (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\" . This 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 be reported with a full error message. For example: <?php use GraphQL\\Error\\ClientAware; class MySafeException extends \\Exception implements ClientAware { public function isClientSafe() { return true; } public function getCategory() { return 'businessLogic'; } } When such exception is thrown it will be reported with a full error message: <?php [ 'message' => 'My reported error', 'category' => 'businessLogic', 'locations' => [ ['line' => 10, 'column' => 2] ], 'path' => [ 'path', 'to', 'fieldWithException' ] ]; 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 each formatted error entry. If you also want to add exception trace - pass flags instead: use GraphQL\\Error\\Debug; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE; $result = GraphQL::executeQuery(/*args*/)->toArray($debug); This will make each error entry to look like this: <?php [ 'debugMessage' => 'Actual exception message', 'message' => 'Internal server error', 'category' => 'internal', 'locations' => [ ['line' => 10, 'column' => 2] ], 'path' => [ 'listField', 0, 'fieldWithException' ], 'trace' => [ /* Formatted original exception trace */ ] ]; If you prefer first resolver exception to be re-thrown, use following flags: <?php use GraphQL\\GraphQL; use GraphQL\\Error\\Debug; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::RETHROW_INTERNAL_EXCEPTIONS; // Following will throw if there was an exception in resolver during execution: $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 to an array. Handler is useful for error filtering and logging. For example, these are default formatter and handler: <?php use GraphQL\\GraphQL; use GraphQL\\Error\\Error; use GraphQL\\Error\\FormattedError; $myErrorFormatter = function(Error $error) { return FormattedError::createFromException($error); }; $myErrorHandler = function(array $errors, callable $formatter) { return array_map($formatter, $errors); }; $result = GraphQL::executeQuery(/* $args */) ->setErrorFormatter($myErrorFormatter) ->setErrorsHandler($myErrorHandler) ->toArray(); Note that when you pass debug flags to toArray() your custom formatter will still be decorated 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 also 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 when it makes sense to return 500 error code for GraphQL endpoint: <?php use GraphQL\\GraphQL; use GraphQL\\Type\\Schema; use GraphQL\\Error\\FormattedError; try { $schema = new Schema([ // ... ]); $body = GraphQL::executeQuery($schema, $query); $status = 200; } catch(\\Exception $e) { $body = [ 'errors' => [FormattedError::createFromException($e)] ]; $status = 500; } header('Content-Type: application/json', true, $status); echo json_encode($body);","title":"Schema Errors"},{"location":"executing-queries/","text":"Using Facade Method 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 use GraphQL\\GraphQL; $result = GraphQL::executeQuery( $schema, $queryString, $rootValue = null, $context = null, $variableValues = null, $operationName = null, $fieldResolver = null, $validationRules = null ); It returns an instance of GraphQL\\Executor\\ExecutionResult which can be easily converted to array: $serializableResult = $result->toArray(); Returned array contains data and errors keys, as described by the GraphQL spec . This array is suitable for further serialization (e.g. using json_encode ). See 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) Using Server If you are building HTTP GraphQL API, you may prefer our Standard Server (compatible with express-graphql ). It 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 use GraphQL\\Server\\StandardServer; $server = new StandardServer([/* server options, see below */]); $server->handleRequest(); // parses PHP globals and emits response Server also supports PSR-7 request/response interfaces : <?php use GraphQL\\Server\\StandardServer; use GraphQL\\Executor\\ExecutionResult; use Psr\\Http\\Message\\ServerRequestInterface; use Psr\\Http\\Message\\ResponseInterface; use Psr\\Http\\Message\\StreamInterface; /** @var ServerRequestInterface $psrRequest */ /** @var ResponseInterface $psrResponse */ /** @var StreamInterface $psrBodyStream */ $server = new StandardServer([/* server options, see below */]); $psrResponse = $server->processPsrRequest($psrRequest, $psrResponse, $psrBodyStream); // Alternatively create PSR-7 response yourself: /** @var ExecutionResult|ExecutionResult[] $result */ $result = $server->executePsrRequest($psrRequest); $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 Server configuration options 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, use GraphQL\\Server\\ServerConfig instead of an array: <?php use GraphQL\\Server\\ServerConfig; use GraphQL\\Server\\StandardServer; $config = ServerConfig::create() ->setSchema($schema) ->setErrorFormatter($myFormatter) ->setDebug($debug) ; $server = new StandardServer($config); Query batching 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. So for example following batch will require single DB request (if user field is deferred): [ { \"query\": \"{user(id: 1)} { id }\" }, { \"query\": \"{user(id: 2)} { id }\" }, { \"query\": \"{user(id: 3)} { id }\" } ] To enable query batching, pass queryBatching option in server config: <?php use GraphQL\\Server\\StandardServer; $server = new StandardServer([ 'queryBatching' => true ]); Custom Validation Rules Before execution, a query is validated using a set of standard rules defined by the GraphQL spec. It is possible to override standard set of rules globally or per execution. Add rules globally: <?php use GraphQL\\Validator\\Rules; use GraphQL\\Validator\\DocumentValidator; // Add to standard set of rules globally: DocumentValidator::addRule(new Rules\\DisableIntrospection()); Custom rules per execution: <?php use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules; $myValiationRules = array_merge( GraphQL::getStandardValidationRules(), [ new Rules\\QueryComplexity(100), new Rules\\DisableIntrospection() ] ); $result = GraphQL::executeQuery( $schema, $queryString, $rootValue = null, $context = null, $variableValues = null, $operationName = null, $fieldResolver = null, $myValiationRules // <-- this will override global validation rules for this request ); Or with a standard server: <?php use GraphQL\\Server\\StandardServer; $server = new StandardServer([ 'validationRules' => $myValiationRules ]);","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 use GraphQL\\GraphQL; $result = GraphQL::executeQuery( $schema, $queryString, $rootValue = null, $context = null, $variableValues = null, $operationName = null, $fieldResolver = null, $validationRules = null ); It returns an instance of GraphQL\\Executor\\ExecutionResult which can be easily converted to array: $serializableResult = $result->toArray(); Returned array contains data and errors keys, as described by the GraphQL spec . This array is suitable for further serialization (e.g. using json_encode ). See 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 (compatible with express-graphql ). It 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 use GraphQL\\Server\\StandardServer; $server = new StandardServer([/* server options, see below */]); $server->handleRequest(); // parses PHP globals and emits response Server also supports PSR-7 request/response interfaces : <?php use GraphQL\\Server\\StandardServer; use GraphQL\\Executor\\ExecutionResult; use Psr\\Http\\Message\\ServerRequestInterface; use Psr\\Http\\Message\\ResponseInterface; use Psr\\Http\\Message\\StreamInterface; /** @var ServerRequestInterface $psrRequest */ /** @var ResponseInterface $psrResponse */ /** @var StreamInterface $psrBodyStream */ $server = new StandardServer([/* server options, see below */]); $psrResponse = $server->processPsrRequest($psrRequest, $psrResponse, $psrBodyStream); // Alternatively create PSR-7 response yourself: /** @var ExecutionResult|ExecutionResult[] $result */ $result = $server->executePsrRequest($psrRequest); $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, use GraphQL\\Server\\ServerConfig instead of an array: <?php use GraphQL\\Server\\ServerConfig; use GraphQL\\Server\\StandardServer; $config = ServerConfig::create() ->setSchema($schema) ->setErrorFormatter($myFormatter) ->setDebug($debug) ; $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. So for example following batch will require single DB request (if user field is deferred): [ { \"query\": \"{user(id: 1)} { id }\" }, { \"query\": \"{user(id: 2)} { id }\" }, { \"query\": \"{user(id: 3)} { id }\" } ] To enable query batching, pass queryBatching option in server config: <?php use GraphQL\\Server\\StandardServer; $server = new StandardServer([ 'queryBatching' => true ]);","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. It is possible to override standard set of rules globally or per execution. Add rules globally: <?php use GraphQL\\Validator\\Rules; use GraphQL\\Validator\\DocumentValidator; // Add to standard set of rules globally: DocumentValidator::addRule(new Rules\\DisableIntrospection()); Custom rules per execution: <?php use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules; $myValiationRules = array_merge( GraphQL::getStandardValidationRules(), [ new Rules\\QueryComplexity(100), new Rules\\DisableIntrospection() ] ); $result = GraphQL::executeQuery( $schema, $queryString, $rootValue = null, $context = null, $variableValues = null, $operationName = null, $fieldResolver = null, $myValiationRules // <-- this will override global validation rules for this request ); Or with a standard server: <?php use GraphQL\\Server\\StandardServer; $server = new StandardServer([ 'validationRules' => $myValiationRules ]);","title":"Custom Validation Rules"},{"location":"getting-started/","text":"Prerequisites This documentation assumes your familiarity with GraphQL concepts. If it is not the case - first learn about GraphQL on the official website . Installation Using composer , simply run: composer require webonyx/graphql-php Upgrading We try to keep library releases backwards compatible. But when breaking changes are inevitable they are explained in upgrade instructions . Install Tools (optional) While it is possible to communicate with GraphQL API using regular HTTP tools it is way more convenient for humans to use GraphiQL - an in-browser IDE for exploring GraphQL APIs. It provides syntax-highlighting, auto-completion and auto-generated documentation for GraphQL 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 page and install it locally. Hello World Let's create a type system that will be capable to process following simple query: query { echo(message: \"Hello World\") } To do so we need an object type with field echo : <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'echo' => [ 'type' => Type::string(), 'args' => [ 'message' => Type::nonNull(Type::string()), ], 'resolve' => function ($root, $args) { return $root['prefix'] . $args['message']; } ], ], ]); (Note: type definition can be expressed in different styles , but this example uses inline style for simplicity) The interesting piece here is resolve option of field definition. It is responsible for returning a 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 (not in this example though). Now when our type is ready, let's create GraphQL endpoint file for it graphql.php : <?php use GraphQL\\GraphQL; use GraphQL\\Type\\Schema; $schema = new Schema([ 'query' => $queryType ]); $rawInput = file_get_contents('php://input'); $input = json_decode($rawInput, true); $query = $input['query']; $variableValues = isset($input['variables']) ? $input['variables'] : null; try { $rootValue = ['prefix' => 'You said: ']; $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues); $output = $result->toArray(); } catch (\\Exception $e) { $output = [ 'errors' => [ [ 'message' => $e->getMessage() ] ] ]; } header('Content-Type: application/json'); echo json_encode($output); Our example is finished. Try it by running: php -S localhost:8080 graphql.php curl http://localhost:8080 -d '{\"query\": \"query { echo(message: \\\"Hello World\\\") }\" }' Check out the full source code of this example which also includes simple mutation. Obviously hello world only scratches the surface of what is possible. So check out next example, which is closer to real-world apps. Or keep reading about schema definition . Blog example It is often easier to start with a full-featured example and then get back to documentation for your own work. Check out Blog example of GraphQL API . It 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 - first 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 they 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 more convenient for humans to use GraphiQL - an in-browser IDE for exploring GraphQL APIs. It provides syntax-highlighting, auto-completion and auto-generated documentation for GraphQL 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 page 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 { echo(message: \"Hello World\") } To do so we need an object type with field echo : <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'echo' => [ 'type' => Type::string(), 'args' => [ 'message' => Type::nonNull(Type::string()), ], 'resolve' => function ($root, $args) { return $root['prefix'] . $args['message']; } ], ], ]); (Note: type definition can be expressed in different styles , but this example uses inline style for simplicity) The interesting piece here is resolve option of field definition. It is responsible for returning a 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 (not in this example though). Now when our type is ready, let's create GraphQL endpoint file for it graphql.php : <?php use GraphQL\\GraphQL; use GraphQL\\Type\\Schema; $schema = new Schema([ 'query' => $queryType ]); $rawInput = file_get_contents('php://input'); $input = json_decode($rawInput, true); $query = $input['query']; $variableValues = isset($input['variables']) ? $input['variables'] : null; try { $rootValue = ['prefix' => 'You said: ']; $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues); $output = $result->toArray(); } catch (\\Exception $e) { $output = [ 'errors' => [ [ 'message' => $e->getMessage() ] ] ]; } header('Content-Type: application/json'); echo json_encode($output); Our example is finished. Try it by running: php -S localhost:8080 graphql.php curl http://localhost:8080 -d '{\"query\": \"query { echo(message: \\\"Hello World\\\") }\" }' Check out the full source code of this example which also includes simple mutation. Obviously hello world only scratches the surface of what is possible. So check out next example, which is closer to real-world apps. Or 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 for your own work. Check out Blog example of GraphQL API . It is quite close to real-world GraphQL hierarchies. Follow instructions and try it yourself in ~10 minutes.","title":"Blog example"},{"location":"how-it-works/","text":"Overview Following reading describes implementation details of query execution process. It may clarify some internals of GraphQL runtime but is not required to use it. Parsing TODOC Validating TODOC Executing TODOC Errors explained 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 the query is not executed. Execution process never throws exceptions. Instead, all errors are caught and collected in execution result. GraphQL is forgiving to Execution errors which occur in resolvers of nullable fields. If such field throws or returns unexpected value the value of the field in response will be simply replaced 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. This nullable field is replaced with null and error entry is added to the result. If all fields up to the root are non-null - data entry will be removed from the result and only errors 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 internals 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 the query is not executed. Execution process never throws exceptions. Instead, all errors are caught and collected in execution result. GraphQL is forgiving to Execution errors which occur in resolvers of nullable fields. If such field throws or returns unexpected value the value of the field in response will be simply replaced 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. This nullable field is replaced with null and error entry is added to the result. If all fields up to the root are non-null - data entry will be removed from the result and only errors key will be presented.","title":"Errors explained"},{"location":"reference/","text":"GraphQL\\GraphQL This is the primary facade for fulfilling GraphQL operations. See related documentation . Class Methods: /** * Executes graphql query. * * More sophisticated GraphQL servers, such as those which persist queries, * may wish to separate the validation and execution phases to a static time * tooling step, and a server runtime step. * * Available options: * * schema: * The GraphQL type system to use when validating and executing a query. * source: * A GraphQL language formatted string representing the requested operation. * rootValue: * The value provided as the first argument to resolver functions on the top * level type (e.g. the query object type). * context: * The value provided as the third argument to all resolvers. * Use this to pass current session, user data, etc * variableValues: * A mapping of variable name to runtime value to use for all variables * defined in the requestString. * operationName: * The name of the operation to use if requestString contains multiple * possible operations. Can be omitted if requestString contains only * one operation. * fieldResolver: * A resolver function to use when one is not provided by the schema. * If not provided, the default field resolver is used (which looks for a * value on the source value with the field's name). * validationRules: * A set of rules for query validation step. Default value is all available rules. * Empty array would allow to skip query validation (may be convenient for persisted * queries which are validated before persisting and assumed valid during execution) * * @api * @param \\GraphQL\\Type\\Schema $schema * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param array|null $variableValues * @param string|null $operationName * @param callable $fieldResolver * @param array $validationRules * * @return ExecutionResult */ static function executeQuery( GraphQL\\Type\\Schema $schema, $source, $rootValue = null, $context = null, $variableValues = null, $operationName = null, callable $fieldResolver = null, array $validationRules = null ) /** * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise. * Useful for Async PHP platforms. * * @api * @param PromiseAdapter $promiseAdapter * @param \\GraphQL\\Type\\Schema $schema * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param array|null $variableValues * @param string|null $operationName * @param callable $fieldResolver * @param array $validationRules * * @return Promise */ static function promiseToExecute( GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter, GraphQL\\Type\\Schema $schema, $source, $rootValue = null, $context = null, $variableValues = null, $operationName = null, callable $fieldResolver = null, array $validationRules = null ) /** * Returns directives defined in GraphQL spec * * @api * @return Directive[] */ static function getStandardDirectives() /** * Returns types defined in GraphQL spec * * @api * @return Type[] */ static function getStandardTypes() /** * Returns standard validation rules implementing GraphQL spec * * @api * @return AbstractValidationRule[] */ static function getStandardValidationRules() GraphQL\\Type\\Definition\\Type Registry of standard GraphQL types and a base class for all other types. Class Methods: /** * @api * @return IDType */ static function id() /** * @api * @return StringType */ static function string() /** * @api * @return BooleanType */ static function boolean() /** * @api * @return IntType */ static function int() /** * @api * @return FloatType */ static function float() /** * @api * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType * @return ListOfType */ static function listOf($wrappedType) /** * @api * @param ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType $wrappedType * @return NonNull */ static function nonNull($wrappedType) /** * @api * @param Type $type * @return bool */ static function isInputType($type) /** * @api * @param Type $type * @return bool */ static function isOutputType($type) /** * @api * @param $type * @return bool */ static function isLeafType($type) /** * @api * @param Type $type * @return bool */ static function isCompositeType($type) /** * @api * @param Type $type * @return bool */ static function isAbstractType($type) /** * @api * @param Type $type * @return bool */ static function isType($type) /** * @api * @param Type $type * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType */ static function getNullableType($type) /** * @api * @param Type $type * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType */ static function getNamedType($type) GraphQL\\Type\\Definition\\ResolveInfo Structure containing information useful for field resolution process. Passed as 3rd argument to every field resolver. See docs on field resolving (data fetching) . Class Props: /** * The name of the field being resolved * * @api * @var string */ public $fieldName; /** * AST of all nodes referencing this field in the query. * * @api * @var FieldNode[] */ public $fieldNodes; /** * Expected return type of the field being resolved * * @api * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull */ public $returnType; /** * Parent type of the field being resolved * * @api * @var ObjectType */ public $parentType; /** * Path to this field from the very root value * * @api * @var array */ public $path; /** * Instance of a schema used for execution * * @api * @var Schema */ public $schema; /** * AST of all fragments defined in query * * @api * @var FragmentDefinitionNode[] */ public $fragments; /** * Root value passed to query execution * * @api * @var mixed */ public $rootValue; /** * AST of operation definition node (query, mutation) * * @api * @var OperationDefinitionNode */ public $operation; /** * Array of variables passed to query execution * * @api * @var array */ public $variableValues; Class Methods: /** * Helper method that returns names of all fields selected in query for * $this->fieldName up to $depth levels * * Example: * query MyQuery{ * { * root { * id, * nested { * nested1 * nested2 { * nested3 * } * } * } * } * * Given this ResolveInfo instance is a part of \"root\" field resolution, and $depth === 1, * method will return: * [ * 'id' => true, * 'nested' => [ * nested1 => true, * nested2 => true * ] * ] * * Warning: this method it is a naive implementation which does not take into account * conditional typed fragments. So use it with care for fields of interface and union types. * * @api * @param int $depth How many levels to include in output * @return array */ function getFieldSelection($depth = 0) GraphQL\\Language\\DirectiveLocation List of available directive locations Class Constants: const QUERY = \"QUERY\"; const MUTATION = \"MUTATION\"; const SUBSCRIPTION = \"SUBSCRIPTION\"; const FIELD = \"FIELD\"; const FRAGMENT_DEFINITION = \"FRAGMENT_DEFINITION\"; const FRAGMENT_SPREAD = \"FRAGMENT_SPREAD\"; const INLINE_FRAGMENT = \"INLINE_FRAGMENT\"; const SCHEMA = \"SCHEMA\"; const SCALAR = \"SCALAR\"; const OBJECT = \"OBJECT\"; const FIELD_DEFINITION = \"FIELD_DEFINITION\"; const ARGUMENT_DEFINITION = \"ARGUMENT_DEFINITION\"; const IFACE = \"INTERFACE\"; const UNION = \"UNION\"; const ENUM = \"ENUM\"; const ENUM_VALUE = \"ENUM_VALUE\"; const INPUT_OBJECT = \"INPUT_OBJECT\"; const INPUT_FIELD_DEFINITION = \"INPUT_FIELD_DEFINITION\"; GraphQL\\Type\\SchemaConfig Schema configuration class. Could be passed directly to schema constructor. List of options accepted by create method is described in docs . Usage example: $config = SchemaConfig::create() ->setQuery($myQueryType) ->setTypeLoader($myTypeLoader); $schema = new Schema($config); Class Methods: /** * Converts an array of options to instance of SchemaConfig * (or just returns empty config when array is not passed). * * @api * @param array $options * @return SchemaConfig */ static function create(array $options = []) /** * @api * @param ObjectType $query * @return SchemaConfig */ function setQuery($query) /** * @api * @param ObjectType $mutation * @return SchemaConfig */ function setMutation($mutation) /** * @api * @param ObjectType $subscription * @return SchemaConfig */ function setSubscription($subscription) /** * @api * @param Type[]|callable $types * @return SchemaConfig */ function setTypes($types) /** * @api * @param Directive[] $directives * @return SchemaConfig */ function setDirectives(array $directives) /** * @api * @param callable $typeLoader * @return SchemaConfig */ function setTypeLoader(callable $typeLoader) /** * @api * @return ObjectType */ function getQuery() /** * @api * @return ObjectType */ function getMutation() /** * @api * @return ObjectType */ function getSubscription() /** * @api * @return Type[] */ function getTypes() /** * @api * @return Directive[] */ function getDirectives() /** * @api * @return callable */ function getTypeLoader() GraphQL\\Type\\Schema Schema Definition (see related docs ) A Schema is created by supplying the root types of each type of operation: query, mutation (optional) and subscription (optional). A schema definition is then supplied to the validator and executor. Usage Example: $schema = new GraphQL\\Type\\Schema([ 'query' => $MyAppQueryRootType, 'mutation' => $MyAppMutationRootType, ]); Or using Schema Config instance: $config = GraphQL\\Type\\SchemaConfig::create() ->setQuery($MyAppQueryRootType) ->setMutation($MyAppMutationRootType); $schema = new GraphQL\\Type\\Schema($config); Class Methods: /** * Schema constructor. * * @api * @param array|SchemaConfig $config */ function __construct($config) /** * Returns schema query type * * @api * @return ObjectType */ function getQueryType() /** * Returns schema mutation type * * @api * @return ObjectType|null */ function getMutationType() /** * Returns schema subscription * * @api * @return ObjectType|null */ function getSubscriptionType() /** * @api * @return SchemaConfig */ function getConfig() /** * Returns array of all types in this schema. Keys of this array represent type names, values are instances * of corresponding type definitions * * This operation requires full schema scan. Do not use in production environment. * * @api * @return Type[] */ function getTypeMap() /** * Returns type by it's name * * @api * @param string $name * @return Type */ function getType($name) /** * Returns all possible concrete types for given abstract type * (implementations for interfaces and members of union type for unions) * * This operation requires full schema scan. Do not use in production environment. * * @api * @param AbstractType $abstractType * @return ObjectType[] */ function getPossibleTypes(GraphQL\\Type\\Definition\\AbstractType $abstractType) /** * Returns true if object type is concrete type of given abstract type * (implementation for interfaces and members of union type for unions) * * @api * @param AbstractType $abstractType * @param ObjectType $possibleType * @return bool */ function isPossibleType( GraphQL\\Type\\Definition\\AbstractType $abstractType, GraphQL\\Type\\Definition\\ObjectType $possibleType ) /** * Returns a list of directives supported by this schema * * @api * @return Directive[] */ function getDirectives() /** * Returns instance of directive by name * * @api * @param $name * @return Directive */ function getDirective($name) /** * Validates schema. * * This operation requires full schema scan. Do not use in production environment. * * @api * @return InvariantViolation[]|Error[] */ function validate() /** * Validates schema. * * This operation requires full schema scan. Do not use in production environment. * * @api * @throws InvariantViolation */ function assertValid() GraphQL\\Language\\Parser Parses string containing GraphQL query or type definition to Abstract Syntax Tree. Class Methods: /** * Given a GraphQL source, parses it into a `GraphQL\\Language\\AST\\DocumentNode`. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * Available options: * * noLocation: boolean, * (By default, the parser creates AST nodes that know the location * in the source that they correspond to. This configuration flag * disables that behavior for performance or testing.) * * experimentalFragmentVariables: boolean, * (If enabled, the parser will understand and parse variable definitions * contained in a fragment definition. They'll be represented in the * `variableDefinitions` field of the FragmentDefinitionNode. * * The syntax is identical to normal, query-defined variables. For example: * * fragment A($var: Boolean = false) on T { * ... * } * * Note: this feature is experimental and may change or be removed in the * future.) * * @api * @param Source|string $source * @param array $options * @return DocumentNode * @throws SyntaxError */ static function parse($source, array $options = []) /** * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for * that value. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Values directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::valueFromAST()`. * * @api * @param Source|string $source * @param array $options * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode */ static function parseValue($source, array $options = []) /** * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for * that type. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Types directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::typeFromAST()`. * * @api * @param Source|string $source * @param array $options * @return ListTypeNode|NameNode|NonNullTypeNode */ static function parseType($source, array $options = []) GraphQL\\Language\\Printer Prints AST to string. Capable of printing GraphQL queries and Type definition language. Useful for pretty-printing queries or printing back AST for logging, documentation, etc. Usage example: $query = 'query myQuery {someField}'; $ast = GraphQL\\Language\\Parser::parse($query); $printed = GraphQL\\Language\\Printer::doPrint($ast); Class Methods: /** * Prints AST to string. Capable of printing GraphQL queries and Type definition language. * * @api * @param Node $ast * @return string */ static function doPrint($ast) GraphQL\\Language\\Visitor Utility for efficient AST traversal and modification. visit() will walk through an AST using a depth first traversal, calling the visitor's enter function at each node in the traversal, and calling the leave function after visiting that node and all of it's child nodes. By returning different values from the enter and leave functions, the behavior of the visitor can be altered, including skipping over a sub-tree of the AST (by returning false), editing the AST by returning a value or null to 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 a new version of the AST with the changes applied will be returned from the visit function. $editedAST = Visitor::visit($ast, [ 'enter' => function ($node, $key, $parent, $path, $ancestors) { // return // null: no action // Visitor::skipNode(): skip visiting this node // Visitor::stop(): stop visiting altogether // Visitor::removeNode(): delete this node // any value: replace this node with the returned value }, 'leave' => function ($node, $key, $parent, $path, $ancestors) { // return // null: no action // Visitor::stop(): stop visiting altogether // Visitor::removeNode(): delete this node // any value: replace this node with the returned value } ]); Alternatively to providing enter() and leave() functions, a visitor can instead provide functions named the same as the kinds of AST nodes , or enter/leave visitors at a named key, leading to four permutations of visitor API: 1) Named visitors triggered when entering a node a specific kind. Visitor::visit($ast, [ 'Kind' => function ($node) { // enter the \"Kind\" node } ]); 2) Named visitors that trigger upon entering and leaving a node of a specific kind. Visitor::visit($ast, [ 'Kind' => [ 'enter' => function ($node) { // enter the \"Kind\" node } 'leave' => function ($node) { // leave the \"Kind\" node } ] ]); 3) Generic visitors that trigger upon entering and leaving any node. Visitor::visit($ast, [ 'enter' => function ($node) { // enter any node }, 'leave' => function ($node) { // leave any node } ]); 4) Parallel visitors for entering and leaving nodes of a specific kind. Visitor::visit($ast, [ 'enter' => [ 'Kind' => function($node) { // enter the \"Kind\" node } }, 'leave' => [ 'Kind' => function ($node) { // leave the \"Kind\" node } ] ]); Class Methods: /** * Visit the AST (see class description for details) * * @api * @param Node $root * @param array $visitor * @param array $keyMap * @return Node|mixed * @throws \\Exception */ static function visit($root, $visitor, $keyMap = null) /** * Returns marker for visitor break * * @api * @return VisitorOperation */ static function stop() /** * Returns marker for skipping current node * * @api * @return VisitorOperation */ static function skipNode() /** * Returns marker for removing a node * * @api * @return VisitorOperation */ static function removeNode() GraphQL\\Language\\AST\\NodeKind Class Constants: const NAME = \"Name\"; const DOCUMENT = \"Document\"; const OPERATION_DEFINITION = \"OperationDefinition\"; const VARIABLE_DEFINITION = \"VariableDefinition\"; const VARIABLE = \"Variable\"; const SELECTION_SET = \"SelectionSet\"; const FIELD = \"Field\"; const ARGUMENT = \"Argument\"; const FRAGMENT_SPREAD = \"FragmentSpread\"; const INLINE_FRAGMENT = \"InlineFragment\"; const FRAGMENT_DEFINITION = \"FragmentDefinition\"; const INT = \"IntValue\"; const FLOAT = \"FloatValue\"; const STRING = \"StringValue\"; const BOOLEAN = \"BooleanValue\"; const ENUM = \"EnumValue\"; const NULL = \"NullValue\"; const LST = \"ListValue\"; const OBJECT = \"ObjectValue\"; const OBJECT_FIELD = \"ObjectField\"; const DIRECTIVE = \"Directive\"; const NAMED_TYPE = \"NamedType\"; const LIST_TYPE = \"ListType\"; const NON_NULL_TYPE = \"NonNullType\"; const SCHEMA_DEFINITION = \"SchemaDefinition\"; const OPERATION_TYPE_DEFINITION = \"OperationTypeDefinition\"; const SCALAR_TYPE_DEFINITION = \"ScalarTypeDefinition\"; const OBJECT_TYPE_DEFINITION = \"ObjectTypeDefinition\"; const FIELD_DEFINITION = \"FieldDefinition\"; const INPUT_VALUE_DEFINITION = \"InputValueDefinition\"; const INTERFACE_TYPE_DEFINITION = \"InterfaceTypeDefinition\"; const UNION_TYPE_DEFINITION = \"UnionTypeDefinition\"; const ENUM_TYPE_DEFINITION = \"EnumTypeDefinition\"; const ENUM_VALUE_DEFINITION = \"EnumValueDefinition\"; const INPUT_OBJECT_TYPE_DEFINITION = \"InputObjectTypeDefinition\"; const SCALAR_TYPE_EXTENSION = \"ScalarTypeExtension\"; const OBJECT_TYPE_EXTENSION = \"ObjectTypeExtension\"; const INTERFACE_TYPE_EXTENSION = \"InterfaceTypeExtension\"; const UNION_TYPE_EXTENSION = \"UnionTypeExtension\"; const ENUM_TYPE_EXTENSION = \"EnumTypeExtension\"; const INPUT_OBJECT_TYPE_EXTENSION = \"InputObjectTypeExtension\"; const DIRECTIVE_DEFINITION = \"DirectiveDefinition\"; GraphQL\\Executor\\Executor Implements the \"Evaluating requests\" section of the GraphQL specification. Class Methods: /** * Executes DocumentNode against given $schema. * * Always returns ExecutionResult and never throws. All errors which occur during operation * execution are collected in `$result->errors`. * * @api * @param Schema $schema * @param DocumentNode $ast * @param $rootValue * @param $contextValue * @param array|\\ArrayAccess $variableValues * @param null $operationName * @param callable $fieldResolver * * @return ExecutionResult|Promise */ static function execute( GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, callable $fieldResolver = null ) /** * Same as execute(), but requires promise adapter and returns a promise which is always * fulfilled with an instance of ExecutionResult and never rejected. * * Useful for async PHP platforms. * * @api * @param PromiseAdapter $promiseAdapter * @param Schema $schema * @param DocumentNode $ast * @param null $rootValue * @param null $contextValue * @param null $variableValues * @param null $operationName * @param callable|null $fieldResolver * @return Promise */ static function promiseToExecute( GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter, GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, callable $fieldResolver = null ) GraphQL\\Executor\\ExecutionResult Returned after query execution . Represents both - result of successful execution and of a failed one (with errors collected in errors prop) Could be converted to spec-compliant serializable array using toArray() Class Props: /** * Data collected from resolvers during query execution * * @api * @var array */ public $data; /** * Errors registered during query execution. * * If an error was caused by exception thrown in resolver, $error->getPrevious() would * contain original exception. * * @api * @var \\GraphQL\\Error\\Error[] */ public $errors; /** * User-defined serializable array of extensions included in serialized result. * Conforms to * * @api * @var array */ public $extensions; Class Methods: /** * Define custom error formatting (must conform to http://facebook.github.io/graphql/#sec-Errors) * * Expected signature is: function (GraphQL\\Error\\Error $error): array * * Default formatter is \"GraphQL\\Error\\FormattedError::createFromException\" * * Expected returned value must be an array: * array( * 'message' => 'errorMessage', * // ... other keys * ); * * @api * @param callable $errorFormatter * @return $this */ function setErrorFormatter(callable $errorFormatter) /** * Define custom logic for error handling (filtering, logging, etc). * * Expected handler signature is: function (array $errors, callable $formatter): array * * Default handler is: * function (array $errors, callable $formatter) { * return array_map($formatter, $errors); * } * * @api * @param callable $handler * @return $this */ function setErrorsHandler(callable $handler) /** * Converts GraphQL query result to spec-compliant serializable array using provided * errors handler and formatter. * * If debug argument is passed, output of error formatter is enriched which debugging information * (\"debugMessage\", \"trace\" keys depending on flags). * * $debug argument must be either bool (only adds \"debugMessage\" to result) or sum of flags from * GraphQL\\Error\\Debug * * @api * @param bool|int $debug * @return array */ function toArray($debug = false) GraphQL\\Executor\\Promise\\PromiseAdapter Provides a means for integration of async PHP platforms ( related docs ) Interface Methods: /** * Return true if the value is a promise or a deferred of the underlying platform * * @api * @param mixed $value * @return bool */ function isThenable($value) /** * Converts thenable of the underlying platform into GraphQL\\Executor\\Promise\\Promise instance * * @api * @param object $thenable * @return Promise */ function convertThenable($thenable) /** * Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\\Executor\\Promise\\Promise. * * @api * @param Promise $promise * @param callable|null $onFulfilled * @param callable|null $onRejected * * @return Promise */ function then( GraphQL\\Executor\\Promise\\Promise $promise, callable $onFulfilled = null, callable $onRejected = null ) /** * Creates a Promise * * Expected resolver signature: * function(callable $resolve, callable $reject) * * @api * @param callable $resolver * @return Promise */ function create(callable $resolver) /** * Creates a fulfilled Promise for a value if the value is not a promise. * * @api * @param mixed $value * @return Promise */ function createFulfilled($value = null) /** * Creates a rejected promise for a reason if the reason is not a promise. If * the provided reason is a promise, then it is returned as-is. * * @api * @param \\Throwable $reason * @return Promise */ function createRejected($reason) /** * Given an array of promises (or values), returns a promise that is fulfilled when all the * items in the array are fulfilled. * * @api * @param array $promisesOrValues Promises or values. * @return Promise */ function all(array $promisesOrValues) GraphQL\\Validator\\DocumentValidator Implements the \"Validation\" section of the spec. Validation runs synchronously, returning an array of encountered errors, or an 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 default list of rules defined by the GraphQL specification will be used. Each validation rule is an instance of GraphQL\\Validator\\Rules\\AbstractValidationRule which returns a visitor (see the GraphQL\\Language\\Visitor API ). Visitor methods are expected to return an instance of GraphQL\\Error\\Error , or array of such instances when invalid. Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema. Class Methods: /** * Primary method for query validation. See class description for details. * * @api * @param Schema $schema * @param DocumentNode $ast * @param AbstractValidationRule[]|null $rules * @param TypeInfo|null $typeInfo * @return Error[] */ static function validate( GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, array $rules = null, GraphQL\\Utils\\TypeInfo $typeInfo = null ) /** * Returns all global validation rules. * * @api * @return AbstractValidationRule[] */ static function allRules() /** * Returns global validation rule by name. Standard rules are named by class name, so * example usage for such rules: * * $rule = DocumentValidator::getRule(GraphQL\\Validator\\Rules\\QueryComplexity::class); * * @api * @param string $name * @return AbstractValidationRule */ static function getRule($name) /** * Add rule to list of global validation rules * * @api * @param AbstractValidationRule $rule */ static function addRule(GraphQL\\Validator\\Rules\\AbstractValidationRule $rule) GraphQL\\Error\\Error Describes an Error found during the parse, validate, or execute phases of performing a GraphQL operation. In addition to a message and stack trace, it also includes information about the locations in a GraphQL document and/or execution result that correspond to the Error. When the error was caused by an exception thrown in resolver, original exception is available via getPrevious() . Also read related docs on error handling Class extends standard PHP \\Exception , so all standard methods of base \\Exception class are available in addition to those listed below. Class Constants: const CATEGORY_GRAPHQL = \"graphql\"; const CATEGORY_INTERNAL = \"internal\"; Class Methods: /** * An array of locations within the source GraphQL document which correspond to this error. * * Each entry has information about `line` and `column` within source GraphQL document: * $location->line; * $location->column; * * Errors during validation often contain multiple locations, for example to * point out to field mentioned in multiple fragments. Errors during execution include a * single location, the field which produced the error. * * @api * @return SourceLocation[] */ function getLocations() /** * Returns an array describing the path from the root value to the field which produced this error. * Only included for execution errors. * * @api * @return array|null */ function getPath() GraphQL\\Error\\Warning Encapsulates warnings produced by the library. Warnings can be suppressed (individually or all) if required. Also it is possible to override warning handler (which is trigger_error() by default) Class Constants: const WARNING_ASSIGN = 2; const WARNING_CONFIG = 4; const WARNING_FULL_SCHEMA_SCAN = 8; const WARNING_CONFIG_DEPRECATION = 16; const WARNING_NOT_A_TYPE = 32; const ALL = 63; Class Methods: /** * Sets warning handler which can intercept all system warnings. * When not set, trigger_error() is used to notify about warnings. * * @api * @param callable|null $warningHandler */ static function setWarningHandler(callable $warningHandler = null) /** * Suppress warning by id (has no effect when custom warning handler is set) * * Usage example: * Warning::suppress(Warning::WARNING_NOT_A_TYPE) * * When passing true - suppresses all warnings. * * @api * @param bool|int $suppress */ static function suppress($suppress = true) /** * Re-enable previously suppressed warning by id * * Usage example: * Warning::suppress(Warning::WARNING_NOT_A_TYPE) * * When passing true - re-enables all warnings. * * @api * @param bool|int $enable */ static function enable($enable = true) GraphQL\\Error\\ClientAware This interface is used for default error formatting . Only errors implementing this interface (and returning true from isClientSafe() ) will be formatted with original error message. All other errors will be formatted with generic \"Internal server error\". Interface Methods: /** * Returns true when exception message is safe to be displayed to a client. * * @api * @return bool */ function isClientSafe() /** * Returns string describing a category of the error. * * Value \"graphql\" is reserved for errors produced by query parsing or validation, do not use it. * * @api * @return string */ function getCategory() GraphQL\\Error\\Debug Collection of flags for error debugging . Class Constants: const INCLUDE_DEBUG_MESSAGE = 1; const INCLUDE_TRACE = 2; const RETHROW_INTERNAL_EXCEPTIONS = 4; GraphQL\\Error\\FormattedError This class is used for default error formatting . It converts PHP exceptions to spec-compliant errors and provides tools for error debugging. Class Methods: /** * Set default error message for internal errors formatted using createFormattedError(). * This value can be overridden by passing 3rd argument to `createFormattedError()`. * * @api * @param string $msg */ static function setInternalErrorMessage($msg) /** * Standard GraphQL error formatter. Converts any exception to array * conforming to GraphQL spec. * * This method only exposes exception message when exception implements ClientAware interface * (or when debug flags are passed). * * For a list of available debug flags see GraphQL\\Error\\Debug constants. * * @api * @param \\Throwable $e * @param bool|int $debug * @param string $internalErrorMessage * @return array * @throws \\Throwable */ static function createFromException($e, $debug = false, $internalErrorMessage = null) /** * Returns error trace as serializable array * * @api * @param \\Throwable $error * @return array */ static function toSafeTrace($error) GraphQL\\Server\\StandardServer GraphQL server compatible with both: express-graphql and Apollo Server . Usage Example: $server = new StandardServer([ 'schema' => $mySchema ]); $server->handleRequest(); Or using ServerConfig instance: $config = GraphQL\\Server\\ServerConfig::create() ->setSchema($mySchema) ->setContext($myContext); $server = new GraphQL\\Server\\StandardServer($config); $server->handleRequest(); See dedicated section in docs for details. Class Methods: /** * Converts and exception to error and sends spec-compliant HTTP 500 error. * Useful when an exception is thrown somewhere outside of server execution context * (e.g. during schema instantiation). * * @api * @param \\Throwable $error * @param bool $debug * @param bool $exitWhenDone */ static function send500Error($error, $debug = false, $exitWhenDone = false) /** * Creates new instance of a standard GraphQL HTTP server * * @api * @param ServerConfig|array $config */ function __construct($config) /** * Parses HTTP request, executes and emits response (using standard PHP `header` function and `echo`) * * By default (when $parsedBody is not set) it uses PHP globals to parse a request. * It is possible to implement request parsing elsewhere (e.g. using framework Request instance) * and then pass it to the server. * * See `executeRequest()` if you prefer to emit response yourself * (e.g. using Response object of some framework) * * @api * @param OperationParams|OperationParams[] $parsedBody * @param bool $exitWhenDone */ function handleRequest($parsedBody = null, $exitWhenDone = false) /** * Executes GraphQL operation and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter). * * By default (when $parsedBody is not set) it uses PHP globals to parse a request. * It is possible to implement request parsing elsewhere (e.g. using framework Request instance) * and then pass it to the server. * * PSR-7 compatible method executePsrRequest() does exactly this. * * @api * @param OperationParams|OperationParams[] $parsedBody * @return ExecutionResult|ExecutionResult[]|Promise * @throws InvariantViolation */ function executeRequest($parsedBody = null) /** * Executes PSR-7 request and fulfills PSR-7 response. * * See `executePsrRequest()` if you prefer to create response yourself * (e.g. using specific JsonResponse instance of some framework). * * @api * @param ServerRequestInterface $request * @param ResponseInterface $response * @param StreamInterface $writableBodyStream * @return ResponseInterface|Promise */ function processPsrRequest( Psr\\Http\\Message\\ServerRequestInterface $request, Psr\\Http\\Message\\ResponseInterface $response, Psr\\Http\\Message\\StreamInterface $writableBodyStream ) /** * Executes GraphQL operation and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * * @api * @param ServerRequestInterface $request * @return ExecutionResult|ExecutionResult[]|Promise */ function executePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /** * Returns an instance of Server helper, which contains most of the actual logic for * parsing / validating / executing request (which could be re-used by other server implementations) * * @api * @return Helper */ function getHelper() GraphQL\\Server\\ServerConfig Server configuration class. Could be passed directly to server constructor. List of options accepted by create method is described in docs . Usage example: $config = GraphQL\\Server\\ServerConfig::create() ->setSchema($mySchema) ->setContext($myContext); $server = new GraphQL\\Server\\StandardServer($config); Class Methods: /** * Converts an array of options to instance of ServerConfig * (or just returns empty config when array is not passed). * * @api * @param array $config * @return ServerConfig */ static function create(array $config = []) /** * @api * @param Schema $schema * @return $this */ function setSchema(GraphQL\\Type\\Schema $schema) /** * @api * @param mixed|\\Closure $context * @return $this */ function setContext($context) /** * @api * @param mixed|\\Closure $rootValue * @return $this */ function setRootValue($rootValue) /** * Expects function(Throwable $e) : array * * @api * @param callable $errorFormatter * @return $this */ function setErrorFormatter(callable $errorFormatter) /** * Expects function(array $errors, callable $formatter) : array * * @api * @param callable $handler * @return $this */ function setErrorsHandler(callable $handler) /** * Set validation rules for this server. * * @api * @param array|callable * @return $this */ function setValidationRules($validationRules) /** * @api * @param callable $fieldResolver * @return $this */ function setFieldResolver(callable $fieldResolver) /** * Expects function($queryId, OperationParams $params) : string|DocumentNode * * This function must return query string or valid DocumentNode. * * @api * @param callable $persistentQueryLoader * @return $this */ function setPersistentQueryLoader(callable $persistentQueryLoader) /** * Set response debug flags. See GraphQL\\Error\\Debug class for a list of all available flags * * @api * @param bool|int $set * @return $this */ function setDebug($set = true) /** * Allow batching queries (disabled by default) * * @api * @param bool $enableBatching * @return $this */ function setQueryBatching($enableBatching) /** * @api * @param PromiseAdapter $promiseAdapter * @return $this */ function setPromiseAdapter(GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter) GraphQL\\Server\\Helper Contains functionality that could be re-used by various server implementations Class Methods: /** * Parses HTTP request using PHP globals and returns GraphQL OperationParams * contained in this request. For batched requests it returns an array of OperationParams. * * This function does not check validity of these params * (validation is performed separately in validateOperationParams() method). * * If $readRawBodyFn argument is not provided - will attempt to read raw request body * from `php://input` stream. * * Internally it normalizes input to $method, $bodyParams and $queryParams and * calls `parseRequestParams()` to produce actual return value. * * For PSR-7 request parsing use `parsePsrRequest()` instead. * * @api * @param callable|null $readRawBodyFn * @return OperationParams|OperationParams[] * @throws RequestError */ function parseHttpRequest(callable $readRawBodyFn = null) /** * Parses normalized request params and returns instance of OperationParams * or array of OperationParams in case of batch operation. * * Returned value is a suitable input for `executeOperation` or `executeBatch` (if array) * * @api * @param string $method * @param array $bodyParams * @param array $queryParams * @return OperationParams|OperationParams[] * @throws RequestError */ function parseRequestParams($method, array $bodyParams, array $queryParams) /** * Checks validity of OperationParams extracted from HTTP request and returns an array of errors * if params are invalid (or empty array when params are valid) * * @api * @param OperationParams $params * @return Error[] */ function validateOperationParams(GraphQL\\Server\\OperationParams $params) /** * Executes GraphQL operation with given server configuration and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * * @api * @param ServerConfig $config * @param OperationParams $op * * @return ExecutionResult|Promise */ function executeOperation(GraphQL\\Server\\ServerConfig $config, GraphQL\\Server\\OperationParams $op) /** * Executes batched GraphQL operations with shared promise queue * (thus, effectively batching deferreds|promises of all queries at once) * * @api * @param ServerConfig $config * @param OperationParams[] $operations * @return ExecutionResult[]|Promise */ function executeBatch(GraphQL\\Server\\ServerConfig $config, array $operations) /** * Send response using standard PHP `header()` and `echo`. * * @api * @param Promise|ExecutionResult|ExecutionResult[] $result * @param bool $exitWhenDone */ function sendResponse($result, $exitWhenDone = false) /** * Converts PSR-7 request to OperationParams[] * * @api * @param ServerRequestInterface $request * @return array|Helper * @throws RequestError */ function parsePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /** * Converts query execution result to PSR-7 response * * @api * @param Promise|ExecutionResult|ExecutionResult[] $result * @param ResponseInterface $response * @param StreamInterface $writableBodyStream * @return Promise|ResponseInterface */ function toPsrResponse( $result, Psr\\Http\\Message\\ResponseInterface $response, Psr\\Http\\Message\\StreamInterface $writableBodyStream ) GraphQL\\Server\\OperationParams Structure representing parsed HTTP parameters for GraphQL operation Class Props: /** * Id of the query (when using persistent queries). * * Valid aliases (case-insensitive): * - id * - queryId * - documentId * * @api * @var string */ public $queryId; /** * @api * @var string */ public $query; /** * @api * @var string */ public $operation; /** * @api * @var array */ public $variables; Class Methods: /** * Creates an instance from given array * * @api * @param array $params * @param bool $readonly * @return OperationParams */ static function create(array $params, $readonly = false) /** * @api * @param string $key * @return mixed */ function getOriginalInput($key) /** * Indicates that operation is executed in read-only context * (e.g. via HTTP GET request) * * @api * @return bool */ function isReadOnly() GraphQL\\Utils\\BuildSchema Build instance of GraphQL\\Type\\Schema out of type language definition (string or parsed AST) See section in docs for details. Class Methods: /** * This takes the ast of a schema document produced by the parse function in * GraphQL\\Language\\Parser. * * If no schema definition is provided, then it will look for types named Query * and Mutation. * * Given that AST it constructs a GraphQL\\Type\\Schema. The resulting schema * has no resolve methods, so execution will use default resolvers. * * Accepts options as a second argument: * * - commentDescriptions: * Provide true to use preceding comments as the description. * * * @api * @param DocumentNode $ast * @param array $options * @return Schema * @throws Error */ static function buildAST(GraphQL\\Language\\AST\\DocumentNode $ast, array $options = []) /** * A helper function to build a GraphQLSchema directly from a source * document. * * @api * @param DocumentNode|Source|string $source * @param array $options * @return Schema */ static function build($source, array $options = []) GraphQL\\Utils\\AST Various utilities dealing with AST Class Methods: /** * Convert representation of AST as an associative array to instance of GraphQL\\Language\\AST\\Node. * * For example: * * ```php * AST::fromArray([ * 'kind' => 'ListValue', * 'values' => [ * ['kind' => 'StringValue', 'value' => 'my str'], * ['kind' => 'StringValue', 'value' => 'my other str'] * ], * 'loc' => ['start' => 21, 'end' => 25] * ]); * ``` * * Will produce instance of `ListValueNode` where `values` prop is a lazily-evaluated `NodeList` * returning instances of `StringValueNode` on access. * * This is a reverse operation for AST::toArray($node) * * @api * @param array $node * @return Node */ static function fromArray(array $node) /** * Convert AST node to serializable array * * @api * @param Node $node * @return array */ static function toArray(GraphQL\\Language\\AST\\Node $node) /** * Produces a GraphQL Value AST given a PHP value. * * Optionally, a GraphQL type may be provided, which will be used to * disambiguate between value primitives. * * | PHP Value | GraphQL Value | * | ------------- | -------------------- | * | Object | Input Object | * | Assoc Array | Input Object | * | Array | List | * | Boolean | Boolean | * | String | String / Enum Value | * | Int | Int | * | Float | Int / Float | * | Mixed | Enum Value | * | null | NullValue | * * @api * @param $value * @param InputType $type * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode */ static function astFromValue($value, GraphQL\\Type\\Definition\\InputType $type) /** * Produces a PHP value given a GraphQL Value AST. * * A GraphQL type must be provided, which will be used to interpret different * GraphQL Value literals. * * Returns `null` when the value could not be validly coerced according to * the provided type. * * | GraphQL Value | PHP Value | * | -------------------- | ------------- | * | Input Object | Assoc Array | * | List | Array | * | Boolean | Boolean | * | String | String | * | Int / Float | Int / Float | * | Enum Value | Mixed | * | Null Value | null | * * @api * @param $valueNode * @param InputType $type * @param null $variables * @return array|null|\\stdClass * @throws \\Exception */ static function valueFromAST($valueNode, GraphQL\\Type\\Definition\\InputType $type, $variables = null) /** * Produces a PHP value given a GraphQL Value AST. * * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value * will reflect the provided GraphQL value AST. * * | GraphQL Value | PHP Value | * | -------------------- | ------------- | * | Input Object | Assoc Array | * | List | Array | * | Boolean | Boolean | * | String | String | * | Int / Float | Int / Float | * | Enum | Mixed | * | Null | null | * * @api * @param Node $valueNode * @param array|null $variables * @return mixed * @throws \\Exception */ static function valueFromASTUntyped($valueNode, array $variables = null) /** * Returns type definition for given AST Type node * * @api * @param Schema $schema * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * @return Type * @throws \\Exception */ static function typeFromAST(GraphQL\\Type\\Schema $schema, $inputTypeNode) /** * Returns operation type (\"query\", \"mutation\" or \"subscription\") given a document and operation name * * @api * @param DocumentNode $document * @param string $operationName * @return bool */ static function getOperation(GraphQL\\Language\\AST\\DocumentNode $document, $operationName = null) GraphQL\\Utils\\SchemaPrinter Given an instance of Schema, prints it in GraphQL type language. Class Methods: /** * Accepts options as a second argument: * * - commentDescriptions: * Provide true to use preceding comments as the description. * @api * @param Schema $schema * @return string */ static function doPrint(GraphQL\\Type\\Schema $schema, array $options = []) /** * @api * @param Schema $schema * @return string */ static function printIntrosepctionSchema(GraphQL\\Type\\Schema $schema, array $options = [])","title":"Class Reference"},{"location":"reference/#graphqlgraphql","text":"This is the primary facade for fulfilling GraphQL operations. See related documentation . Class Methods: /** * Executes graphql query. * * More sophisticated GraphQL servers, such as those which persist queries, * may wish to separate the validation and execution phases to a static time * tooling step, and a server runtime step. * * Available options: * * schema: * The GraphQL type system to use when validating and executing a query. * source: * A GraphQL language formatted string representing the requested operation. * rootValue: * The value provided as the first argument to resolver functions on the top * level type (e.g. the query object type). * context: * The value provided as the third argument to all resolvers. * Use this to pass current session, user data, etc * variableValues: * A mapping of variable name to runtime value to use for all variables * defined in the requestString. * operationName: * The name of the operation to use if requestString contains multiple * possible operations. Can be omitted if requestString contains only * one operation. * fieldResolver: * A resolver function to use when one is not provided by the schema. * If not provided, the default field resolver is used (which looks for a * value on the source value with the field's name). * validationRules: * A set of rules for query validation step. Default value is all available rules. * Empty array would allow to skip query validation (may be convenient for persisted * queries which are validated before persisting and assumed valid during execution) * * @api * @param \\GraphQL\\Type\\Schema $schema * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param array|null $variableValues * @param string|null $operationName * @param callable $fieldResolver * @param array $validationRules * * @return ExecutionResult */ static function executeQuery( GraphQL\\Type\\Schema $schema, $source, $rootValue = null, $context = null, $variableValues = null, $operationName = null, callable $fieldResolver = null, array $validationRules = null ) /** * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise. * Useful for Async PHP platforms. * * @api * @param PromiseAdapter $promiseAdapter * @param \\GraphQL\\Type\\Schema $schema * @param string|DocumentNode $source * @param mixed $rootValue * @param mixed $context * @param array|null $variableValues * @param string|null $operationName * @param callable $fieldResolver * @param array $validationRules * * @return Promise */ static function promiseToExecute( GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter, GraphQL\\Type\\Schema $schema, $source, $rootValue = null, $context = null, $variableValues = null, $operationName = null, callable $fieldResolver = null, array $validationRules = null ) /** * Returns directives defined in GraphQL spec * * @api * @return Directive[] */ static function getStandardDirectives() /** * Returns types defined in GraphQL spec * * @api * @return Type[] */ static function getStandardTypes() /** * Returns standard validation rules implementing GraphQL spec * * @api * @return AbstractValidationRule[] */ static function getStandardValidationRules()","title":"GraphQL\\GraphQL"},{"location":"reference/#graphqltypedefinitiontype","text":"Registry of standard GraphQL types and a base class for all other types. Class Methods: /** * @api * @return IDType */ static function id() /** * @api * @return StringType */ static function string() /** * @api * @return BooleanType */ static function boolean() /** * @api * @return IntType */ static function int() /** * @api * @return FloatType */ static function float() /** * @api * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType * @return ListOfType */ static function listOf($wrappedType) /** * @api * @param ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType $wrappedType * @return NonNull */ static function nonNull($wrappedType) /** * @api * @param Type $type * @return bool */ static function isInputType($type) /** * @api * @param Type $type * @return bool */ static function isOutputType($type) /** * @api * @param $type * @return bool */ static function isLeafType($type) /** * @api * @param Type $type * @return bool */ static function isCompositeType($type) /** * @api * @param Type $type * @return bool */ static function isAbstractType($type) /** * @api * @param Type $type * @return bool */ static function isType($type) /** * @api * @param Type $type * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType */ static function getNullableType($type) /** * @api * @param Type $type * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType */ static function getNamedType($type)","title":"GraphQL\\Type\\Definition\\Type"},{"location":"reference/#graphqltypedefinitionresolveinfo","text":"Structure containing information useful for field resolution process. Passed as 3rd argument to every field resolver. See docs on field resolving (data fetching) . Class Props: /** * The name of the field being resolved * * @api * @var string */ public $fieldName; /** * AST of all nodes referencing this field in the query. * * @api * @var FieldNode[] */ public $fieldNodes; /** * Expected return type of the field being resolved * * @api * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull */ public $returnType; /** * Parent type of the field being resolved * * @api * @var ObjectType */ public $parentType; /** * Path to this field from the very root value * * @api * @var array */ public $path; /** * Instance of a schema used for execution * * @api * @var Schema */ public $schema; /** * AST of all fragments defined in query * * @api * @var FragmentDefinitionNode[] */ public $fragments; /** * Root value passed to query execution * * @api * @var mixed */ public $rootValue; /** * AST of operation definition node (query, mutation) * * @api * @var OperationDefinitionNode */ public $operation; /** * Array of variables passed to query execution * * @api * @var array */ public $variableValues; Class Methods: /** * Helper method that returns names of all fields selected in query for * $this->fieldName up to $depth levels * * Example: * query MyQuery{ * { * root { * id, * nested { * nested1 * nested2 { * nested3 * } * } * } * } * * Given this ResolveInfo instance is a part of \"root\" field resolution, and $depth === 1, * method will return: * [ * 'id' => true, * 'nested' => [ * nested1 => true, * nested2 => true * ] * ] * * Warning: this method it is a naive implementation which does not take into account * conditional typed fragments. So use it with care for fields of interface and union types. * * @api * @param int $depth How many levels to include in output * @return array */ function getFieldSelection($depth = 0)","title":"GraphQL\\Type\\Definition\\ResolveInfo"},{"location":"reference/#graphqllanguagedirectivelocation","text":"List of available directive locations Class Constants: const QUERY = \"QUERY\"; const MUTATION = \"MUTATION\"; const SUBSCRIPTION = \"SUBSCRIPTION\"; const FIELD = \"FIELD\"; const FRAGMENT_DEFINITION = \"FRAGMENT_DEFINITION\"; const FRAGMENT_SPREAD = \"FRAGMENT_SPREAD\"; const INLINE_FRAGMENT = \"INLINE_FRAGMENT\"; const SCHEMA = \"SCHEMA\"; const SCALAR = \"SCALAR\"; const OBJECT = \"OBJECT\"; const FIELD_DEFINITION = \"FIELD_DEFINITION\"; const ARGUMENT_DEFINITION = \"ARGUMENT_DEFINITION\"; const IFACE = \"INTERFACE\"; const UNION = \"UNION\"; const ENUM = \"ENUM\"; const ENUM_VALUE = \"ENUM_VALUE\"; const INPUT_OBJECT = \"INPUT_OBJECT\"; const INPUT_FIELD_DEFINITION = \"INPUT_FIELD_DEFINITION\";","title":"GraphQL\\Language\\DirectiveLocation"},{"location":"reference/#graphqltypeschemaconfig","text":"Schema configuration class. Could be passed directly to schema constructor. List of options accepted by create method is described in docs . Usage example: $config = SchemaConfig::create() ->setQuery($myQueryType) ->setTypeLoader($myTypeLoader); $schema = new Schema($config); Class Methods: /** * Converts an array of options to instance of SchemaConfig * (or just returns empty config when array is not passed). * * @api * @param array $options * @return SchemaConfig */ static function create(array $options = []) /** * @api * @param ObjectType $query * @return SchemaConfig */ function setQuery($query) /** * @api * @param ObjectType $mutation * @return SchemaConfig */ function setMutation($mutation) /** * @api * @param ObjectType $subscription * @return SchemaConfig */ function setSubscription($subscription) /** * @api * @param Type[]|callable $types * @return SchemaConfig */ function setTypes($types) /** * @api * @param Directive[] $directives * @return SchemaConfig */ function setDirectives(array $directives) /** * @api * @param callable $typeLoader * @return SchemaConfig */ function setTypeLoader(callable $typeLoader) /** * @api * @return ObjectType */ function getQuery() /** * @api * @return ObjectType */ function getMutation() /** * @api * @return ObjectType */ function getSubscription() /** * @api * @return Type[] */ function getTypes() /** * @api * @return Directive[] */ function getDirectives() /** * @api * @return callable */ function 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: query, mutation (optional) and subscription (optional). A schema definition is then supplied to the validator and executor. Usage Example: $schema = new GraphQL\\Type\\Schema([ 'query' => $MyAppQueryRootType, 'mutation' => $MyAppMutationRootType, ]); Or using Schema Config instance: $config = GraphQL\\Type\\SchemaConfig::create() ->setQuery($MyAppQueryRootType) ->setMutation($MyAppMutationRootType); $schema = new GraphQL\\Type\\Schema($config); Class Methods: /** * Schema constructor. * * @api * @param array|SchemaConfig $config */ function __construct($config) /** * Returns schema query type * * @api * @return ObjectType */ function getQueryType() /** * Returns schema mutation type * * @api * @return ObjectType|null */ function getMutationType() /** * Returns schema subscription * * @api * @return ObjectType|null */ function getSubscriptionType() /** * @api * @return SchemaConfig */ function getConfig() /** * Returns array of all types in this schema. Keys of this array represent type names, values are instances * of corresponding type definitions * * This operation requires full schema scan. Do not use in production environment. * * @api * @return Type[] */ function getTypeMap() /** * Returns type by it's name * * @api * @param string $name * @return Type */ function getType($name) /** * Returns all possible concrete types for given abstract type * (implementations for interfaces and members of union type for unions) * * This operation requires full schema scan. Do not use in production environment. * * @api * @param AbstractType $abstractType * @return ObjectType[] */ function getPossibleTypes(GraphQL\\Type\\Definition\\AbstractType $abstractType) /** * Returns true if object type is concrete type of given abstract type * (implementation for interfaces and members of union type for unions) * * @api * @param AbstractType $abstractType * @param ObjectType $possibleType * @return bool */ function isPossibleType( GraphQL\\Type\\Definition\\AbstractType $abstractType, GraphQL\\Type\\Definition\\ObjectType $possibleType ) /** * Returns a list of directives supported by this schema * * @api * @return Directive[] */ function getDirectives() /** * Returns instance of directive by name * * @api * @param $name * @return Directive */ function getDirective($name) /** * Validates schema. * * This operation requires full schema scan. Do not use in production environment. * * @api * @return InvariantViolation[]|Error[] */ function validate() /** * Validates schema. * * This operation requires full schema scan. Do not use in production environment. * * @api * @throws InvariantViolation */ function assertValid()","title":"GraphQL\\Type\\Schema"},{"location":"reference/#graphqllanguageparser","text":"Parses string containing GraphQL query or type definition to Abstract Syntax Tree. Class Methods: /** * Given a GraphQL source, parses it into a `GraphQL\\Language\\AST\\DocumentNode`. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * Available options: * * noLocation: boolean, * (By default, the parser creates AST nodes that know the location * in the source that they correspond to. This configuration flag * disables that behavior for performance or testing.) * * experimentalFragmentVariables: boolean, * (If enabled, the parser will understand and parse variable definitions * contained in a fragment definition. They'll be represented in the * `variableDefinitions` field of the FragmentDefinitionNode. * * The syntax is identical to normal, query-defined variables. For example: * * fragment A($var: Boolean = false) on T { * ... * } * * Note: this feature is experimental and may change or be removed in the * future.) * * @api * @param Source|string $source * @param array $options * @return DocumentNode * @throws SyntaxError */ static function parse($source, array $options = []) /** * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for * that value. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Values directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::valueFromAST()`. * * @api * @param Source|string $source * @param array $options * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode */ static function parseValue($source, array $options = []) /** * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for * that type. * Throws `GraphQL\\Error\\SyntaxError` if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Types directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: `GraphQL\\Utils\\AST::typeFromAST()`. * * @api * @param Source|string $source * @param array $options * @return ListTypeNode|NameNode|NonNullTypeNode */ static 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. Useful for pretty-printing queries or printing back AST for logging, documentation, etc. Usage example: $query = 'query myQuery {someField}'; $ast = GraphQL\\Language\\Parser::parse($query); $printed = GraphQL\\Language\\Printer::doPrint($ast); Class Methods: /** * Prints AST to string. Capable of printing GraphQL queries and Type definition language. * * @api * @param Node $ast * @return string */ static 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 the visitor's enter function at each node in the traversal, and calling the leave function after visiting that node and all of it's child nodes. By returning different values from the enter and leave functions, the behavior of the visitor can be altered, including skipping over a sub-tree of the AST (by returning false), editing the AST by returning a value or null to 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 a new version of the AST with the changes applied will be returned from the visit function. $editedAST = Visitor::visit($ast, [ 'enter' => function ($node, $key, $parent, $path, $ancestors) { // return // null: no action // Visitor::skipNode(): skip visiting this node // Visitor::stop(): stop visiting altogether // Visitor::removeNode(): delete this node // any value: replace this node with the returned value }, 'leave' => function ($node, $key, $parent, $path, $ancestors) { // return // null: no action // Visitor::stop(): stop visiting altogether // Visitor::removeNode(): delete this node // any value: replace this node with the returned value } ]); Alternatively to providing enter() and leave() functions, a visitor can instead provide functions named the same as the kinds of AST nodes , or enter/leave visitors at a named key, leading to four permutations of visitor API: 1) Named visitors triggered when entering a node a specific kind. Visitor::visit($ast, [ 'Kind' => function ($node) { // enter the \"Kind\" node } ]); 2) Named visitors that trigger upon entering and leaving a node of a specific kind. Visitor::visit($ast, [ 'Kind' => [ 'enter' => function ($node) { // enter the \"Kind\" node } 'leave' => function ($node) { // leave the \"Kind\" node } ] ]); 3) Generic visitors that trigger upon entering and leaving any node. Visitor::visit($ast, [ 'enter' => function ($node) { // enter any node }, 'leave' => function ($node) { // leave any node } ]); 4) Parallel visitors for entering and leaving nodes of a specific kind. Visitor::visit($ast, [ 'enter' => [ 'Kind' => function($node) { // enter the \"Kind\" node } }, 'leave' => [ 'Kind' => function ($node) { // leave the \"Kind\" node } ] ]); Class Methods: /** * Visit the AST (see class description for details) * * @api * @param Node $root * @param array $visitor * @param array $keyMap * @return Node|mixed * @throws \\Exception */ static function visit($root, $visitor, $keyMap = null) /** * Returns marker for visitor break * * @api * @return VisitorOperation */ static function stop() /** * Returns marker for skipping current node * * @api * @return VisitorOperation */ static function skipNode() /** * Returns marker for removing a node * * @api * @return VisitorOperation */ static function removeNode()","title":"GraphQL\\Language\\Visitor"},{"location":"reference/#graphqllanguageastnodekind","text":"Class Constants: const NAME = \"Name\"; const DOCUMENT = \"Document\"; const OPERATION_DEFINITION = \"OperationDefinition\"; const VARIABLE_DEFINITION = \"VariableDefinition\"; const VARIABLE = \"Variable\"; const SELECTION_SET = \"SelectionSet\"; const FIELD = \"Field\"; const ARGUMENT = \"Argument\"; const FRAGMENT_SPREAD = \"FragmentSpread\"; const INLINE_FRAGMENT = \"InlineFragment\"; const FRAGMENT_DEFINITION = \"FragmentDefinition\"; const INT = \"IntValue\"; const FLOAT = \"FloatValue\"; const STRING = \"StringValue\"; const BOOLEAN = \"BooleanValue\"; const ENUM = \"EnumValue\"; const NULL = \"NullValue\"; const LST = \"ListValue\"; const OBJECT = \"ObjectValue\"; const OBJECT_FIELD = \"ObjectField\"; const DIRECTIVE = \"Directive\"; const NAMED_TYPE = \"NamedType\"; const LIST_TYPE = \"ListType\"; const NON_NULL_TYPE = \"NonNullType\"; const SCHEMA_DEFINITION = \"SchemaDefinition\"; const OPERATION_TYPE_DEFINITION = \"OperationTypeDefinition\"; const SCALAR_TYPE_DEFINITION = \"ScalarTypeDefinition\"; const OBJECT_TYPE_DEFINITION = \"ObjectTypeDefinition\"; const FIELD_DEFINITION = \"FieldDefinition\"; const INPUT_VALUE_DEFINITION = \"InputValueDefinition\"; const INTERFACE_TYPE_DEFINITION = \"InterfaceTypeDefinition\"; const UNION_TYPE_DEFINITION = \"UnionTypeDefinition\"; const ENUM_TYPE_DEFINITION = \"EnumTypeDefinition\"; const ENUM_VALUE_DEFINITION = \"EnumValueDefinition\"; const INPUT_OBJECT_TYPE_DEFINITION = \"InputObjectTypeDefinition\"; const SCALAR_TYPE_EXTENSION = \"ScalarTypeExtension\"; const OBJECT_TYPE_EXTENSION = \"ObjectTypeExtension\"; const INTERFACE_TYPE_EXTENSION = \"InterfaceTypeExtension\"; const UNION_TYPE_EXTENSION = \"UnionTypeExtension\"; const ENUM_TYPE_EXTENSION = \"EnumTypeExtension\"; const INPUT_OBJECT_TYPE_EXTENSION = \"InputObjectTypeExtension\"; const DIRECTIVE_DEFINITION = \"DirectiveDefinition\";","title":"GraphQL\\Language\\AST\\NodeKind"},{"location":"reference/#graphqlexecutorexecutor","text":"Implements the \"Evaluating requests\" section of the GraphQL specification. Class Methods: /** * Executes DocumentNode against given $schema. * * Always returns ExecutionResult and never throws. All errors which occur during operation * execution are collected in `$result->errors`. * * @api * @param Schema $schema * @param DocumentNode $ast * @param $rootValue * @param $contextValue * @param array|\\ArrayAccess $variableValues * @param null $operationName * @param callable $fieldResolver * * @return ExecutionResult|Promise */ static function execute( GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, callable $fieldResolver = null ) /** * Same as execute(), but requires promise adapter and returns a promise which is always * fulfilled with an instance of ExecutionResult and never rejected. * * Useful for async PHP platforms. * * @api * @param PromiseAdapter $promiseAdapter * @param Schema $schema * @param DocumentNode $ast * @param null $rootValue * @param null $contextValue * @param null $variableValues * @param null $operationName * @param callable|null $fieldResolver * @return Promise */ static function promiseToExecute( GraphQL\\Executor\\Promise\\PromiseAdapter $promiseAdapter, GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null, callable $fieldResolver = null )","title":"GraphQL\\Executor\\Executor"},{"location":"reference/#graphqlexecutorexecutionresult","text":"Returned after query execution . Represents both - result of successful execution and of a failed one (with errors collected in errors prop) Could be converted to spec-compliant serializable array using toArray() Class Props: /** * Data collected from resolvers during query execution * * @api * @var array */ public $data; /** * Errors registered during query execution. * * If an error was caused by exception thrown in resolver, $error->getPrevious() would * contain original exception. * * @api * @var \\GraphQL\\Error\\Error[] */ public $errors; /** * User-defined serializable array of extensions included in serialized result. * Conforms to * * @api * @var array */ public $extensions; Class Methods: /** * Define custom error formatting (must conform to http://facebook.github.io/graphql/#sec-Errors) * * Expected signature is: function (GraphQL\\Error\\Error $error): array * * Default formatter is \"GraphQL\\Error\\FormattedError::createFromException\" * * Expected returned value must be an array: * array( * 'message' => 'errorMessage', * // ... other keys * ); * * @api * @param callable $errorFormatter * @return $this */ function setErrorFormatter(callable $errorFormatter) /** * Define custom logic for error handling (filtering, logging, etc). * * Expected handler signature is: function (array $errors, callable $formatter): array * * Default handler is: * function (array $errors, callable $formatter) { * return array_map($formatter, $errors); * } * * @api * @param callable $handler * @return $this */ function setErrorsHandler(callable $handler) /** * Converts GraphQL query result to spec-compliant serializable array using provided * errors handler and formatter. * * If debug argument is passed, output of error formatter is enriched which debugging information * (\"debugMessage\", \"trace\" keys depending on flags). * * $debug argument must be either bool (only adds \"debugMessage\" to result) or sum of flags from * GraphQL\\Error\\Debug * * @api * @param bool|int $debug * @return array */ function toArray($debug = false)","title":"GraphQL\\Executor\\ExecutionResult"},{"location":"reference/#graphqlexecutorpromisepromiseadapter","text":"Provides a means for integration of async PHP platforms ( related docs ) Interface Methods: /** * Return true if the value is a promise or a deferred of the underlying platform * * @api * @param mixed $value * @return bool */ function isThenable($value) /** * Converts thenable of the underlying platform into GraphQL\\Executor\\Promise\\Promise instance * * @api * @param object $thenable * @return Promise */ function convertThenable($thenable) /** * Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\\Executor\\Promise\\Promise. * * @api * @param Promise $promise * @param callable|null $onFulfilled * @param callable|null $onRejected * * @return Promise */ function then( GraphQL\\Executor\\Promise\\Promise $promise, callable $onFulfilled = null, callable $onRejected = null ) /** * Creates a Promise * * Expected resolver signature: * function(callable $resolve, callable $reject) * * @api * @param callable $resolver * @return Promise */ function create(callable $resolver) /** * Creates a fulfilled Promise for a value if the value is not a promise. * * @api * @param mixed $value * @return Promise */ function createFulfilled($value = null) /** * Creates a rejected promise for a reason if the reason is not a promise. If * the provided reason is a promise, then it is returned as-is. * * @api * @param \\Throwable $reason * @return Promise */ function createRejected($reason) /** * Given an array of promises (or values), returns a promise that is fulfilled when all the * items in the array are fulfilled. * * @api * @param array $promisesOrValues Promises or values. * @return Promise */ function 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 an 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 default list of rules defined by the GraphQL specification will be used. Each validation rule is an instance of GraphQL\\Validator\\Rules\\AbstractValidationRule which returns a visitor (see the GraphQL\\Language\\Visitor API ). Visitor methods are expected to return an instance of GraphQL\\Error\\Error , or array of such instances when invalid. Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema. Class Methods: /** * Primary method for query validation. See class description for details. * * @api * @param Schema $schema * @param DocumentNode $ast * @param AbstractValidationRule[]|null $rules * @param TypeInfo|null $typeInfo * @return Error[] */ static function validate( GraphQL\\Type\\Schema $schema, GraphQL\\Language\\AST\\DocumentNode $ast, array $rules = null, GraphQL\\Utils\\TypeInfo $typeInfo = null ) /** * Returns all global validation rules. * * @api * @return AbstractValidationRule[] */ static function allRules() /** * Returns global validation rule by name. Standard rules are named by class name, so * example usage for such rules: * * $rule = DocumentValidator::getRule(GraphQL\\Validator\\Rules\\QueryComplexity::class); * * @api * @param string $name * @return AbstractValidationRule */ static function getRule($name) /** * Add rule to list of global validation rules * * @api * @param AbstractValidationRule $rule */ static function addRule(GraphQL\\Validator\\Rules\\AbstractValidationRule $rule)","title":"GraphQL\\Validator\\DocumentValidator"},{"location":"reference/#graphqlerrorerror","text":"Describes an Error found during the parse, validate, or execute phases of performing a GraphQL operation. In addition to a message and stack trace, it also includes information about the locations in a GraphQL document and/or execution result that correspond to the Error. When the error was caused by an exception thrown in resolver, original exception is available via getPrevious() . Also read related docs on error handling Class extends standard PHP \\Exception , so all standard methods of base \\Exception class are available in addition to those listed below. Class Constants: const CATEGORY_GRAPHQL = \"graphql\"; const CATEGORY_INTERNAL = \"internal\"; Class Methods: /** * An array of locations within the source GraphQL document which correspond to this error. * * Each entry has information about `line` and `column` within source GraphQL document: * $location->line; * $location->column; * * Errors during validation often contain multiple locations, for example to * point out to field mentioned in multiple fragments. Errors during execution include a * single location, the field which produced the error. * * @api * @return SourceLocation[] */ function getLocations() /** * Returns an array describing the path from the root value to the field which produced this error. * Only included for execution errors. * * @api * @return array|null */ function getPath()","title":"GraphQL\\Error\\Error"},{"location":"reference/#graphqlerrorwarning","text":"Encapsulates warnings produced by the library. Warnings can be suppressed (individually or all) if required. Also it is possible to override warning handler (which is trigger_error() by default) Class Constants: const WARNING_ASSIGN = 2; const WARNING_CONFIG = 4; const WARNING_FULL_SCHEMA_SCAN = 8; const WARNING_CONFIG_DEPRECATION = 16; const WARNING_NOT_A_TYPE = 32; const ALL = 63; Class Methods: /** * Sets warning handler which can intercept all system warnings. * When not set, trigger_error() is used to notify about warnings. * * @api * @param callable|null $warningHandler */ static function setWarningHandler(callable $warningHandler = null) /** * Suppress warning by id (has no effect when custom warning handler is set) * * Usage example: * Warning::suppress(Warning::WARNING_NOT_A_TYPE) * * When passing true - suppresses all warnings. * * @api * @param bool|int $suppress */ static function suppress($suppress = true) /** * Re-enable previously suppressed warning by id * * Usage example: * Warning::suppress(Warning::WARNING_NOT_A_TYPE) * * When passing true - re-enables all warnings. * * @api * @param bool|int $enable */ static 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() ) will be formatted with original error message. All other errors will be formatted with generic \"Internal server error\". Interface Methods: /** * Returns true when exception message is safe to be displayed to a client. * * @api * @return bool */ function isClientSafe() /** * Returns string describing a category of the error. * * Value \"graphql\" is reserved for errors produced by query parsing or validation, do not use it. * * @api * @return string */ function getCategory()","title":"GraphQL\\Error\\ClientAware"},{"location":"reference/#graphqlerrordebug","text":"Collection of flags for error debugging . Class Constants: const INCLUDE_DEBUG_MESSAGE = 1; const INCLUDE_TRACE = 2; const RETHROW_INTERNAL_EXCEPTIONS = 4;","title":"GraphQL\\Error\\Debug"},{"location":"reference/#graphqlerrorformattederror","text":"This class is used for default error formatting . It converts PHP exceptions to spec-compliant errors and provides tools for error debugging. Class Methods: /** * Set default error message for internal errors formatted using createFormattedError(). * This value can be overridden by passing 3rd argument to `createFormattedError()`. * * @api * @param string $msg */ static function setInternalErrorMessage($msg) /** * Standard GraphQL error formatter. Converts any exception to array * conforming to GraphQL spec. * * This method only exposes exception message when exception implements ClientAware interface * (or when debug flags are passed). * * For a list of available debug flags see GraphQL\\Error\\Debug constants. * * @api * @param \\Throwable $e * @param bool|int $debug * @param string $internalErrorMessage * @return array * @throws \\Throwable */ static function createFromException($e, $debug = false, $internalErrorMessage = null) /** * Returns error trace as serializable array * * @api * @param \\Throwable $error * @return array */ static function toSafeTrace($error)","title":"GraphQL\\Error\\FormattedError"},{"location":"reference/#graphqlserverstandardserver","text":"GraphQL server compatible with both: express-graphql and Apollo Server . Usage Example: $server = new StandardServer([ 'schema' => $mySchema ]); $server->handleRequest(); Or using ServerConfig instance: $config = GraphQL\\Server\\ServerConfig::create() ->setSchema($mySchema) ->setContext($myContext); $server = new GraphQL\\Server\\StandardServer($config); $server->handleRequest(); See dedicated section in docs for details. Class Methods: /** * Converts and exception to error and sends spec-compliant HTTP 500 error. * Useful when an exception is thrown somewhere outside of server execution context * (e.g. during schema instantiation). * * @api * @param \\Throwable $error * @param bool $debug * @param bool $exitWhenDone */ static function send500Error($error, $debug = false, $exitWhenDone = false) /** * Creates new instance of a standard GraphQL HTTP server * * @api * @param ServerConfig|array $config */ function __construct($config) /** * Parses HTTP request, executes and emits response (using standard PHP `header` function and `echo`) * * By default (when $parsedBody is not set) it uses PHP globals to parse a request. * It is possible to implement request parsing elsewhere (e.g. using framework Request instance) * and then pass it to the server. * * See `executeRequest()` if you prefer to emit response yourself * (e.g. using Response object of some framework) * * @api * @param OperationParams|OperationParams[] $parsedBody * @param bool $exitWhenDone */ function handleRequest($parsedBody = null, $exitWhenDone = false) /** * Executes GraphQL operation and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter). * * By default (when $parsedBody is not set) it uses PHP globals to parse a request. * It is possible to implement request parsing elsewhere (e.g. using framework Request instance) * and then pass it to the server. * * PSR-7 compatible method executePsrRequest() does exactly this. * * @api * @param OperationParams|OperationParams[] $parsedBody * @return ExecutionResult|ExecutionResult[]|Promise * @throws InvariantViolation */ function executeRequest($parsedBody = null) /** * Executes PSR-7 request and fulfills PSR-7 response. * * See `executePsrRequest()` if you prefer to create response yourself * (e.g. using specific JsonResponse instance of some framework). * * @api * @param ServerRequestInterface $request * @param ResponseInterface $response * @param StreamInterface $writableBodyStream * @return ResponseInterface|Promise */ function processPsrRequest( Psr\\Http\\Message\\ServerRequestInterface $request, Psr\\Http\\Message\\ResponseInterface $response, Psr\\Http\\Message\\StreamInterface $writableBodyStream ) /** * Executes GraphQL operation and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * * @api * @param ServerRequestInterface $request * @return ExecutionResult|ExecutionResult[]|Promise */ function executePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /** * Returns an instance of Server helper, which contains most of the actual logic for * parsing / validating / executing request (which could be re-used by other server implementations) * * @api * @return Helper */ function getHelper()","title":"GraphQL\\Server\\StandardServer"},{"location":"reference/#graphqlserverserverconfig","text":"Server configuration class. Could be passed directly to server constructor. List of options accepted by create method is described in docs . Usage example: $config = GraphQL\\Server\\ServerConfig::create() ->setSchema($mySchema) ->setContext($myContext); $server = new GraphQL\\Server\\StandardServer($config); Class Methods: /** * Converts an array of options to instance of ServerConfig * (or just returns empty config when array is not passed). * * @api * @param array $config * @return ServerConfig */ static function create(array $config = []) /** * @api * @param Schema $schema * @return $this */ function setSchema(GraphQL\\Type\\Schema $schema) /** * @api * @param mixed|\\Closure $context * @return $this */ function setContext($context) /** * @api * @param mixed|\\Closure $rootValue * @return $this */ function setRootValue($rootValue) /** * Expects function(Throwable $e) : array * * @api * @param callable $errorFormatter * @return $this */ function setErrorFormatter(callable $errorFormatter) /** * Expects function(array $errors, callable $formatter) : array * * @api * @param callable $handler * @return $this */ function setErrorsHandler(callable $handler) /** * Set validation rules for this server. * * @api * @param array|callable * @return $this */ function setValidationRules($validationRules) /** * @api * @param callable $fieldResolver * @return $this */ function setFieldResolver(callable $fieldResolver) /** * Expects function($queryId, OperationParams $params) : string|DocumentNode * * This function must return query string or valid DocumentNode. * * @api * @param callable $persistentQueryLoader * @return $this */ function setPersistentQueryLoader(callable $persistentQueryLoader) /** * Set response debug flags. See GraphQL\\Error\\Debug class for a list of all available flags * * @api * @param bool|int $set * @return $this */ function setDebug($set = true) /** * Allow batching queries (disabled by default) * * @api * @param bool $enableBatching * @return $this */ function setQueryBatching($enableBatching) /** * @api * @param PromiseAdapter $promiseAdapter * @return $this */ function 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: /** * Parses HTTP request using PHP globals and returns GraphQL OperationParams * contained in this request. For batched requests it returns an array of OperationParams. * * This function does not check validity of these params * (validation is performed separately in validateOperationParams() method). * * If $readRawBodyFn argument is not provided - will attempt to read raw request body * from `php://input` stream. * * Internally it normalizes input to $method, $bodyParams and $queryParams and * calls `parseRequestParams()` to produce actual return value. * * For PSR-7 request parsing use `parsePsrRequest()` instead. * * @api * @param callable|null $readRawBodyFn * @return OperationParams|OperationParams[] * @throws RequestError */ function parseHttpRequest(callable $readRawBodyFn = null) /** * Parses normalized request params and returns instance of OperationParams * or array of OperationParams in case of batch operation. * * Returned value is a suitable input for `executeOperation` or `executeBatch` (if array) * * @api * @param string $method * @param array $bodyParams * @param array $queryParams * @return OperationParams|OperationParams[] * @throws RequestError */ function parseRequestParams($method, array $bodyParams, array $queryParams) /** * Checks validity of OperationParams extracted from HTTP request and returns an array of errors * if params are invalid (or empty array when params are valid) * * @api * @param OperationParams $params * @return Error[] */ function validateOperationParams(GraphQL\\Server\\OperationParams $params) /** * Executes GraphQL operation with given server configuration and returns execution result * (or promise when promise adapter is different from SyncPromiseAdapter) * * @api * @param ServerConfig $config * @param OperationParams $op * * @return ExecutionResult|Promise */ function executeOperation(GraphQL\\Server\\ServerConfig $config, GraphQL\\Server\\OperationParams $op) /** * Executes batched GraphQL operations with shared promise queue * (thus, effectively batching deferreds|promises of all queries at once) * * @api * @param ServerConfig $config * @param OperationParams[] $operations * @return ExecutionResult[]|Promise */ function executeBatch(GraphQL\\Server\\ServerConfig $config, array $operations) /** * Send response using standard PHP `header()` and `echo`. * * @api * @param Promise|ExecutionResult|ExecutionResult[] $result * @param bool $exitWhenDone */ function sendResponse($result, $exitWhenDone = false) /** * Converts PSR-7 request to OperationParams[] * * @api * @param ServerRequestInterface $request * @return array|Helper * @throws RequestError */ function parsePsrRequest(Psr\\Http\\Message\\ServerRequestInterface $request) /** * Converts query execution result to PSR-7 response * * @api * @param Promise|ExecutionResult|ExecutionResult[] $result * @param ResponseInterface $response * @param StreamInterface $writableBodyStream * @return Promise|ResponseInterface */ function toPsrResponse( $result, Psr\\Http\\Message\\ResponseInterface $response, Psr\\Http\\Message\\StreamInterface $writableBodyStream )","title":"GraphQL\\Server\\Helper"},{"location":"reference/#graphqlserveroperationparams","text":"Structure representing parsed HTTP parameters for GraphQL operation Class Props: /** * Id of the query (when using persistent queries). * * Valid aliases (case-insensitive): * - id * - queryId * - documentId * * @api * @var string */ public $queryId; /** * @api * @var string */ public $query; /** * @api * @var string */ public $operation; /** * @api * @var array */ public $variables; Class Methods: /** * Creates an instance from given array * * @api * @param array $params * @param bool $readonly * @return OperationParams */ static function create(array $params, $readonly = false) /** * @api * @param string $key * @return mixed */ function getOriginalInput($key) /** * Indicates that operation is executed in read-only context * (e.g. via HTTP GET request) * * @api * @return bool */ function isReadOnly()","title":"GraphQL\\Server\\OperationParams"},{"location":"reference/#graphqlutilsbuildschema","text":"Build instance of GraphQL\\Type\\Schema out of type language definition (string or parsed AST) See section in docs for details. Class Methods: /** * This takes the ast of a schema document produced by the parse function in * GraphQL\\Language\\Parser. * * If no schema definition is provided, then it will look for types named Query * and Mutation. * * Given that AST it constructs a GraphQL\\Type\\Schema. The resulting schema * has no resolve methods, so execution will use default resolvers. * * Accepts options as a second argument: * * - commentDescriptions: * Provide true to use preceding comments as the description. * * * @api * @param DocumentNode $ast * @param array $options * @return Schema * @throws Error */ static function buildAST(GraphQL\\Language\\AST\\DocumentNode $ast, array $options = []) /** * A helper function to build a GraphQLSchema directly from a source * document. * * @api * @param DocumentNode|Source|string $source * @param array $options * @return Schema */ static function build($source, array $options = [])","title":"GraphQL\\Utils\\BuildSchema"},{"location":"reference/#graphqlutilsast","text":"Various utilities dealing with AST Class Methods: /** * Convert representation of AST as an associative array to instance of GraphQL\\Language\\AST\\Node. * * For example: * * ```php * AST::fromArray([ * 'kind' => 'ListValue', * 'values' => [ * ['kind' => 'StringValue', 'value' => 'my str'], * ['kind' => 'StringValue', 'value' => 'my other str'] * ], * 'loc' => ['start' => 21, 'end' => 25] * ]); * ``` * * Will produce instance of `ListValueNode` where `values` prop is a lazily-evaluated `NodeList` * returning instances of `StringValueNode` on access. * * This is a reverse operation for AST::toArray($node) * * @api * @param array $node * @return Node */ static function fromArray(array $node) /** * Convert AST node to serializable array * * @api * @param Node $node * @return array */ static function toArray(GraphQL\\Language\\AST\\Node $node) /** * Produces a GraphQL Value AST given a PHP value. * * Optionally, a GraphQL type may be provided, which will be used to * disambiguate between value primitives. * * | PHP Value | GraphQL Value | * | ------------- | -------------------- | * | Object | Input Object | * | Assoc Array | Input Object | * | Array | List | * | Boolean | Boolean | * | String | String / Enum Value | * | Int | Int | * | Float | Int / Float | * | Mixed | Enum Value | * | null | NullValue | * * @api * @param $value * @param InputType $type * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode */ static function astFromValue($value, GraphQL\\Type\\Definition\\InputType $type) /** * Produces a PHP value given a GraphQL Value AST. * * A GraphQL type must be provided, which will be used to interpret different * GraphQL Value literals. * * Returns `null` when the value could not be validly coerced according to * the provided type. * * | GraphQL Value | PHP Value | * | -------------------- | ------------- | * | Input Object | Assoc Array | * | List | Array | * | Boolean | Boolean | * | String | String | * | Int / Float | Int / Float | * | Enum Value | Mixed | * | Null Value | null | * * @api * @param $valueNode * @param InputType $type * @param null $variables * @return array|null|\\stdClass * @throws \\Exception */ static function valueFromAST($valueNode, GraphQL\\Type\\Definition\\InputType $type, $variables = null) /** * Produces a PHP value given a GraphQL Value AST. * * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value * will reflect the provided GraphQL value AST. * * | GraphQL Value | PHP Value | * | -------------------- | ------------- | * | Input Object | Assoc Array | * | List | Array | * | Boolean | Boolean | * | String | String | * | Int / Float | Int / Float | * | Enum | Mixed | * | Null | null | * * @api * @param Node $valueNode * @param array|null $variables * @return mixed * @throws \\Exception */ static function valueFromASTUntyped($valueNode, array $variables = null) /** * Returns type definition for given AST Type node * * @api * @param Schema $schema * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * @return Type * @throws \\Exception */ static function typeFromAST(GraphQL\\Type\\Schema $schema, $inputTypeNode) /** * Returns operation type (\"query\", \"mutation\" or \"subscription\") given a document and operation name * * @api * @param DocumentNode $document * @param string $operationName * @return bool */ static 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: /** * Accepts options as a second argument: * * - commentDescriptions: * Provide true to use preceding comments as the description. * @api * @param Schema $schema * @return string */ static function doPrint(GraphQL\\Type\\Schema $schema, array $options = []) /** * @api * @param Schema $schema * @return string */ static function printIntrosepctionSchema(GraphQL\\Type\\Schema $schema, array $options = [])","title":"GraphQL\\Utils\\SchemaPrinter"},{"location":"security/","text":"Query Complexity Analysis 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. Every field in the query gets a default score 1 (including ObjectType nodes). Total complexity of the query 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 use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\QueryComplexity; use GraphQL\\Validator\\DocumentValidator; $rule = new QueryComplexity($maxQueryComplexity = 100); DocumentValidator::addRule($rule); GraphQL::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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $type = new ObjectType([ 'name' => 'MyType', 'fields' => [ 'someList' => [ 'type' => Type::listOf(Type::string()), 'args' => [ 'limit' => [ 'type' => Type::int(), 'defaultValue' => 10 ] ], 'complexity' => function($childrenComplexity, $args) { return $childrenComplexity * $args['limit']; } ] ] ]); Limiting Query Depth This is a PHP port of Limiting Query Depth in Sangria implementation. For example, max depth of the introspection query is 7 . It is disabled by default. To enable it, add following validation rule: <?php use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\QueryDepth; use GraphQL\\Validator\\DocumentValidator; $rule = new QueryDepth($maxDepth = 10); DocumentValidator::addRule($rule); GraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution . Disabling Introspection Introspection is a mechanism for fetching schema structure. It 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 sending 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 use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\DisableIntrospection; use GraphQL\\Validator\\DocumentValidator; DocumentValidator::addRule(new DisableIntrospection()); GraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution .","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. Every field in the query gets a default score 1 (including ObjectType nodes). Total complexity of the query 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 use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\QueryComplexity; use GraphQL\\Validator\\DocumentValidator; $rule = new QueryComplexity($maxQueryComplexity = 100); DocumentValidator::addRule($rule); GraphQL::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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $type = new ObjectType([ 'name' => 'MyType', 'fields' => [ 'someList' => [ 'type' => Type::listOf(Type::string()), 'args' => [ 'limit' => [ 'type' => Type::int(), 'defaultValue' => 10 ] ], 'complexity' => function($childrenComplexity, $args) { return $childrenComplexity * $args['limit']; } ] ] ]);","title":"Query Complexity Analysis"},{"location":"security/#limiting-query-depth","text":"This is a PHP port of Limiting Query Depth in Sangria implementation. For example, max depth of the introspection query is 7 . It is disabled by default. To enable it, add following validation rule: <?php use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\QueryDepth; use GraphQL\\Validator\\DocumentValidator; $rule = new QueryDepth($maxDepth = 10); DocumentValidator::addRule($rule); GraphQL::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. It 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 sending 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 use GraphQL\\GraphQL; use GraphQL\\Validator\\Rules\\DisableIntrospection; use GraphQL\\Validator\\DocumentValidator; DocumentValidator::addRule(new DisableIntrospection()); GraphQL::executeQuery(/*...*/); This will set the rule globally. Alternatively, you can provide validation rules per execution .","title":"Disabling Introspection"},{"location":"type-system/","text":"Type System 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 . Type Definition Styles Several styles of type definitions are supported depending on your preferences. Inline definitions: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $myType = new ObjectType([ 'name' => 'MyType', 'fields' => [ 'id' => Type::id() ] ]); Class per type: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; class MyType extends ObjectType { public function __construct() { $config = [ // Note: 'name' is not needed in this form: // it will be inferred from class name by omitting namespace and dropping \"Type\" suffix 'fields' => [ 'id' => Type::id() ] ]; parent::__construct($config); } } Using GraphQL Type language : schema { query: Query mutation: Mutation } type Query { greetings(input: HelloInput!): String! } input HelloInput { firstName: String! lastName: String } Read more about type language definitions in a dedicated docs section . Type Registry Every type must be presented in Schema by a single instance ( graphql-php throws 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 instance of that class is added to the schema. The typical way to do this is to create a registry of your types: <?php namespace MyApp; class TypeRegistry { private $myAType; private $myBType; public function myAType() { return $this->myAType ?: ($this->myAType = new MyAType($this)); } public function myBType() { return $this->myBType ?: ($this->myBType = new MyBType($this)); } } And use this registry in type definition: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; class MyAType extends ObjectType { public function __construct(TypeRegistry $types) { parent::__construct([ 'fields' => [ 'b' => $types->myBType() ] ]); } } Obviously, you can automate this registry as you wish to reduce boilerplate or even introduce Dependency Injection Container if your types have other dependencies. Alternatively, all methods of the registry could be static - then there is no need to pass it in constructor - instead just use use TypeRegistry::myAType() in your type 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 namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $myType = new ObjectType([ 'name' => 'MyType', 'fields' => [ 'id' => Type::id() ] ]); Class per type: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; class MyType extends ObjectType { public function __construct() { $config = [ // Note: 'name' is not needed in this form: // it will be inferred from class name by omitting namespace and dropping \"Type\" suffix 'fields' => [ 'id' => Type::id() ] ]; parent::__construct($config); } } Using GraphQL Type language : schema { query: Query mutation: Mutation } type Query { greetings(input: HelloInput!): String! } input HelloInput { firstName: String! lastName: String } 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 throws 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 instance of that class is added to the schema. The typical way to do this is to create a registry of your types: <?php namespace MyApp; class TypeRegistry { private $myAType; private $myBType; public function myAType() { return $this->myAType ?: ($this->myAType = new MyAType($this)); } public function myBType() { return $this->myBType ?: ($this->myBType = new MyBType($this)); } } And use this registry in type definition: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; class MyAType extends ObjectType { public function __construct(TypeRegistry $types) { parent::__construct([ 'fields' => [ 'b' => $types->myBType() ] ]); } } Obviously, you can automate this registry as you wish to reduce boilerplate or even introduce Dependency Injection Container if your types have other dependencies. Alternatively, all methods of the registry could be static - then there is no need to pass it in constructor - instead just use use TypeRegistry::myAType() in your type definitions.","title":"Type Registry"},{"location":"type-system/directives/","text":"Built-in directives The directive is a way for a client to give GraphQL server additional context and hints on how to execute the query. The directive can be attached to a field or fragment and can affect the execution of the query 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!) { hero(episode: $episode) { name friends @include(if: $withFriends) { name } } } Here if $withFriends variable is set to false - friends section will be ignored and excluded from the response. Important implementation detail: those fields will never be executed (not just removed from response after execution). Custom directives graphql-php supports custom directives even though their presence does not affect the execution of fields. But you can use GraphQL\\Type\\Definition\\ResolveInfo in 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 (or one of its subclasses) which accepts an array of following options: <?php use GraphQL\\Language\\DirectiveLocation; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\Directive; use GraphQL\\Type\\Definition\\FieldArgument; $trackDirective = new Directive([ 'name' => 'track', 'description' => 'Instruction to record usage of the field by client', 'locations' => [ DirectiveLocation::FIELD, ], 'args' => [ new FieldArgument([ 'name' => 'details', 'type' => Type::string(), 'description' => 'String with additional details of field usage scenario', 'defaultValue' => '' ]) ] ]); See possible directive locations in GraphQL\\Language\\DirectiveLocation .","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 the query. The directive can be attached to a field or fragment and can affect the execution of the query 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!) { hero(episode: $episode) { name friends @include(if: $withFriends) { name } } } Here if $withFriends variable is set to false - friends section will be ignored and excluded from the response. Important implementation detail: those fields will never be executed (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. But you can use GraphQL\\Type\\Definition\\ResolveInfo in 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 (or one of its subclasses) which accepts an array of following options: <?php use GraphQL\\Language\\DirectiveLocation; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\Directive; use GraphQL\\Type\\Definition\\FieldArgument; $trackDirective = new Directive([ 'name' => 'track', 'description' => 'Instruction to record usage of the field by client', 'locations' => [ DirectiveLocation::FIELD, ], 'args' => [ new FieldArgument([ 'name' => 'details', 'type' => Type::string(), 'description' => 'String with additional details of field usage scenario', 'defaultValue' => '' ]) ] ]); See possible directive locations in GraphQL\\Language\\DirectiveLocation .","title":"Custom directives"},{"location":"type-system/enum-types/","text":"Enum Type Definition Enumeration types are a special kind of scalar that is restricted to a particular set of allowed values. In graphql-php enum type is an instance of GraphQL\\Type\\Definition\\EnumType which accepts configuration array in constructor: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => [ 'value' => 4, 'description' => 'Released in 1977.' ], 'EMPIRE' => [ 'value' => 5, 'description' => 'Released in 1980.' ], 'JEDI' => [ 'value' => 6, 'description' => 'Released in 1983.' ], ] ]); This example uses an inline style for Enum Type definition, but you can also use inheritance or type language . Configuration options 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) Shorthand definitions If internal representation of enumerated item is the same as item name, then you can use following shorthand for definition: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => ['NEWHOPE', 'EMPIRE', 'JEDI'] ]); which is equivalent of: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => ['value' => 'NEWHOPE'], 'EMPIRE' => ['value' => 'EMPIRE'], 'JEDI' => ['value' => 'JEDI'] ] ]); which is in turn equivalent of the full form: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ ['name' => 'NEWHOPE', 'value' => 'NEWHOPE'], ['name' => 'EMPIRE', 'value' => 'EMPIRE'], ['name' => 'JEDI', 'value' => 'JEDI'] ] ]); Field Resolution When object field is of Enum Type, field resolver is expected to return an internal representation of corresponding Enum item ( value in config). graphql-php will then serialize this value to name to include in response: <?php use GraphQL\\Type\\Definition\\EnumType; use GraphQL\\Type\\Definition\\ObjectType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => [ 'value' => 4, 'description' => 'Released in 1977.' ], 'EMPIRE' => [ 'value' => 5, 'description' => 'Released in 1980.' ], 'JEDI' => [ 'value' => 6, 'description' => 'Released in 1983.' ], ] ]); $heroType = new ObjectType([ 'name' => 'Hero', 'fields' => [ 'appearsIn' => [ 'type' => $episodeEnum, 'resolve' => function() { return 5; // Actual entry in response will be 'appearsIn' => 'EMPIRE' } ] ] ]); The Reverse is true when the enum is used as input type (e.g. as field argument). GraphQL will treat enum input as name and convert it into value before passing to your app. For example, given object type definition: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $heroType = new ObjectType([ 'name' => 'Hero', 'fields' => [ 'appearsIn' => [ 'type' => Type::boolean(), 'args' => [ 'episode' => Type::nonNull($enumType) ], 'resolve' => function($_value, $args) { return $args['episode'] === 5 ? true : false; } ] ] ]); Then following query: fragment on Hero { appearsInNewHope: appearsIn(NEWHOPE) appearsInEmpire: appearsIn(EMPIRE) } will return: [ 'appearsInNewHope' => false, 'appearsInEmpire' => true ]","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 of allowed values. In graphql-php enum type is an instance of GraphQL\\Type\\Definition\\EnumType which accepts configuration array in constructor: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => [ 'value' => 4, 'description' => 'Released in 1977.' ], 'EMPIRE' => [ 'value' => 5, 'description' => 'Released in 1980.' ], 'JEDI' => [ 'value' => 6, 'description' => 'Released in 1983.' ], ] ]); 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 following shorthand for definition: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => ['NEWHOPE', 'EMPIRE', 'JEDI'] ]); which is equivalent of: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => ['value' => 'NEWHOPE'], 'EMPIRE' => ['value' => 'EMPIRE'], 'JEDI' => ['value' => 'JEDI'] ] ]); which is in turn equivalent of the full form: <?php use GraphQL\\Type\\Definition\\EnumType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ ['name' => 'NEWHOPE', 'value' => 'NEWHOPE'], ['name' => 'EMPIRE', 'value' => 'EMPIRE'], ['name' => 'JEDI', 'value' => 'JEDI'] ] ]);","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 representation of corresponding Enum item ( value in config). graphql-php will then serialize this value to name to include in response: <?php use GraphQL\\Type\\Definition\\EnumType; use GraphQL\\Type\\Definition\\ObjectType; $episodeEnum = new EnumType([ 'name' => 'Episode', 'description' => 'One of the films in the Star Wars Trilogy', 'values' => [ 'NEWHOPE' => [ 'value' => 4, 'description' => 'Released in 1977.' ], 'EMPIRE' => [ 'value' => 5, 'description' => 'Released in 1980.' ], 'JEDI' => [ 'value' => 6, 'description' => 'Released in 1983.' ], ] ]); $heroType = new ObjectType([ 'name' => 'Hero', 'fields' => [ 'appearsIn' => [ 'type' => $episodeEnum, 'resolve' => function() { return 5; // Actual entry in response will be 'appearsIn' => 'EMPIRE' } ] ] ]); The Reverse is true when the enum is used as input type (e.g. as field argument). GraphQL will treat enum input as name and convert it into value before passing to your app. For example, given object type definition: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $heroType = new ObjectType([ 'name' => 'Hero', 'fields' => [ 'appearsIn' => [ 'type' => Type::boolean(), 'args' => [ 'episode' => Type::nonNull($enumType) ], 'resolve' => function($_value, $args) { return $args['episode'] === 5 ? true : false; } ] ] ]); Then following query: fragment on Hero { appearsInNewHope: appearsIn(NEWHOPE) appearsInEmpire: appearsIn(EMPIRE) } will return: [ 'appearsInNewHope' => false, 'appearsInEmpire' => true ]","title":"Field Resolution"},{"location":"type-system/input-types/","text":"Mutations Mutation is just a field of a regular Object Type with arguments. For GraphQL PHP runtime there is no difference between query fields with arguments and mutations. They are executed almost identically. To 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!) { createReview(episode: $ep, review: $review) { stars commentary } } To execute such a mutation, you need Mutation type at the root of your schema : <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $myMutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ // List of mutations: 'createReview' => [ 'args' => [ 'episode' => Type::nonNull($episodeInputType), 'review' => Type::nonNull($reviewInputType) ], 'type' => new ObjectType([ 'name' => 'CreateReviewOutput', 'fields' => [ 'stars' => ['type' => Type::int()], 'commentary' => ['type' => Type::string()] ] ]), ], // ... other mutations ] ]); As you can see, the only difference from regular object type is the semantics of field names (verbs vs nouns). Also as we see arguments can be of complex types. To leverage the full power of mutations (and field arguments in general) you must learn how to create complex input types. About Input and Output Types 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 inner 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. Input Object Type GraphQL specification defines Input Object Type for complex inputs. It is similar to ObjectType except 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 (or one of it subclasses) which accepts configuration array in constructor: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\InputObjectType; $filters = new InputObjectType([ 'name' => 'StoryFiltersInput', 'fields' => [ 'author' => [ 'type' => Type::id(), 'description' => 'Only show stories with this author id' ], 'popular' => [ 'type' => Type::boolean(), 'description' => 'Only show popular stories (liked by several people)' ], 'tags' => [ 'type' => Type::listOf(Type::string()), 'description' => 'Only show stories which contain all of those tags' ] ] ]); Every field may be of other InputObjectType (thus complex hierarchies of inputs are possible) Configuration options 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 Using Input Object Type In the example above we defined our InputObjectType. Now let's use it in one of field arguments: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'stories' => [ 'type' => Type::listOf($storyType), 'args' => [ 'filters' => [ 'type' => Type::nonNull($filters), 'defaultValue' => [ 'popular' => true ] ] ], 'resolve' => function($rootValue, $args) { return DataSource::filterStories($args['filters']); } ] ] ]); (note that you can define defaultValue for fields with complex inputs as associative array). Then GraphQL query could include filters as literal value: { stories(filters: {author: \"1\", popular: false}) } Or as query variable: query($filters: StoryFiltersInput!) { stories(filters: $filters) } $variables = [ 'filters' => [ \"author\" => \"1\", \"popular\" => false ] ]; graphql-php will validate the input against your InputObjectType definition and pass it to your resolver as $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. For GraphQL PHP runtime there is no difference between query fields with arguments and mutations. They are executed almost identically. To 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!) { createReview(episode: $ep, review: $review) { stars commentary } } To execute such a mutation, you need Mutation type at the root of your schema : <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $myMutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ // List of mutations: 'createReview' => [ 'args' => [ 'episode' => Type::nonNull($episodeInputType), 'review' => Type::nonNull($reviewInputType) ], 'type' => new ObjectType([ 'name' => 'CreateReviewOutput', 'fields' => [ 'stars' => ['type' => Type::int()], 'commentary' => ['type' => Type::string()] ] ]), ], // ... other mutations ] ]); As you can see, the only difference from regular object type is the semantics of field names (verbs vs nouns). Also as we see arguments can be of complex types. To leverage the full power of mutations (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 inner 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 except 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 (or one of it subclasses) which accepts configuration array in constructor: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\InputObjectType; $filters = new InputObjectType([ 'name' => 'StoryFiltersInput', 'fields' => [ 'author' => [ 'type' => Type::id(), 'description' => 'Only show stories with this author id' ], 'popular' => [ 'type' => Type::boolean(), 'description' => 'Only show popular stories (liked by several people)' ], 'tags' => [ 'type' => Type::listOf(Type::string()), 'description' => 'Only show stories which contain all of those tags' ] ] ]); 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'stories' => [ 'type' => Type::listOf($storyType), 'args' => [ 'filters' => [ 'type' => Type::nonNull($filters), 'defaultValue' => [ 'popular' => true ] ] ], 'resolve' => function($rootValue, $args) { return DataSource::filterStories($args['filters']); } ] ] ]); (note that you can define defaultValue for fields with complex inputs as associative array). Then GraphQL query could include filters as literal value: { stories(filters: {author: \"1\", popular: false}) } Or as query variable: query($filters: StoryFiltersInput!) { stories(filters: $filters) } $variables = [ 'filters' => [ \"author\" => \"1\", \"popular\" => false ] ]; graphql-php will validate the input against your InputObjectType definition and pass it to your resolver as $args['filters']","title":"Using Input Object Type"},{"location":"type-system/interfaces/","text":"Interface Type Definition An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface. In graphql-php interface type is an instance of GraphQL\\Type\\Definition\\InterfaceType (or one of its subclasses) which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Definition\\InterfaceType; use GraphQL\\Type\\Definition\\Type; $character = new InterfaceType([ 'name' => 'Character', 'description' => 'A character in the Star Wars Trilogy', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::string()), 'description' => 'The id of the character.', ], 'name' => [ 'type' => Type::string(), 'description' => 'The name of the character.' ] ], 'resolveType' => function ($value) { if ($value->type === 'human') { return MyTypes::human(); } else { return MyTypes::droid(); } } ]); This example uses inline style for Interface definition, but you can also use inheritance or type language . Configuration options 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 . Implementing interface To implement the Interface simply add it to interfaces array of Object Type definition: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'Human', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::string()), 'description' => 'The id of the character.', ], 'name' => [ 'type' => Type::string(), 'description' => 'The name of the character.' ] ], 'interfaces' => [ $character ] ]); Note that Object Type must include all fields of interface with exact same types (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 (see Covariant return types for interface fields below) Covariant return types for interface fields Object types implementing interface may change the field type to more specific. Example: interface A { field1: A } type B implements A { field1: B } Sharing Interface fields Since every Object Type implementing an Interface must have the same set of fields - it often makes sense to reuse field definitions of Interface in Object Types: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'Human', 'interfaces' => [ $character ], 'fields' => [ 'height' => Type::float(), $character->getField('id'), $character->getField('name') ] ]); In this case, field definitions are created only once (as a part of Interface Type) and then reused by all interface implementors. It can save several microseconds and kilobytes + ensures that field 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 be 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 option in Object Type config and handle field resolutions there (Note: resolve option in field definition has precedence over resolveField option in object type definition) Interface role in data fetching The only responsibility of interface in Data Fetching process is to return concrete Object Type for given $value in resolveType . Then resolution of fields is delegated to resolvers of this concrete Object Type. If a resolveType option is omitted, graphql-php will loop through all interface implementors and use their isTypeOf callback to pick the first suitable one. This is obviously less efficient than single resolveType call. So it is recommended to define resolveType 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 type must include to implement the interface. In graphql-php interface type is an instance of GraphQL\\Type\\Definition\\InterfaceType (or one of its subclasses) which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Definition\\InterfaceType; use GraphQL\\Type\\Definition\\Type; $character = new InterfaceType([ 'name' => 'Character', 'description' => 'A character in the Star Wars Trilogy', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::string()), 'description' => 'The id of the character.', ], 'name' => [ 'type' => Type::string(), 'description' => 'The name of the character.' ] ], 'resolveType' => function ($value) { if ($value->type === 'human') { return MyTypes::human(); } else { return MyTypes::droid(); } } ]); 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 use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'Human', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::string()), 'description' => 'The id of the character.', ], 'name' => [ 'type' => Type::string(), 'description' => 'The name of the character.' ] ], 'interfaces' => [ $character ] ]); Note that Object Type must include all fields of interface with exact same types (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 (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. Example: interface A { field1: A } type B implements A { field1: B }","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 sense to reuse field definitions of Interface in Object Types: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'Human', 'interfaces' => [ $character ], 'fields' => [ 'height' => Type::float(), $character->getField('id'), $character->getField('name') ] ]); In this case, field definitions are created only once (as a part of Interface Type) and then reused by all interface implementors. It can save several microseconds and kilobytes + ensures that field 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 be 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 option in Object Type config and handle field resolutions there (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 for given $value in resolveType . Then resolution of fields is delegated to resolvers of this concrete Object Type. If a resolveType option is omitted, graphql-php will loop through all interface implementors and use their isTypeOf callback to pick the first suitable one. This is obviously less efficient than single resolveType call. So it is recommended to define resolveType whenever possible.","title":"Interface role in data fetching"},{"location":"type-system/lists-and-nonnulls/","text":"Lists graphql-php provides built-in support for lists. In order to create list type - wrap existing type with GraphQL\\Type\\Definition\\Type::listOf() modifier: <?php namespace MyApp; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'emails' => [ 'type' => Type::listOf(Type::string()), 'resolve' => function() { return ['jon@example.com', 'jonny@example.com']; } ] ] ]); Resolvers for such fields are expected to return array or instance of PHP's built-in Traversable interface ( null is allowed by default too). If returned value is not of one of these types - graphql-php will add an error to result and set the field value to null (only if the field is nullable, see below for non-null fields). Non-Null fields By default in GraphQL, every field can have a null value. To indicate that some field always returns non-null value - use GraphQL\\Type\\Definition\\Type::nonNull() modifier: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::id()), 'resolve' => function() { return uniqid(); } ], 'emails' => [ 'type' => Type::nonNull(Type::listOf(Type::string())), 'resolve' => function() { return ['jon@example.com', 'jonny@example.com']; } ] ] ]); If resolver of non-null field returns null , graphql-php will add an error to result and exclude the whole object from the output (an error will bubble to first nullable parent field which will be set to null ). Read the section on Data Fetching 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 existing type with GraphQL\\Type\\Definition\\Type::listOf() modifier: <?php namespace MyApp; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'emails' => [ 'type' => Type::listOf(Type::string()), 'resolve' => function() { return ['jon@example.com', 'jonny@example.com']; } ] ] ]); Resolvers for such fields are expected to return array or instance of PHP's built-in Traversable interface ( null is allowed by default too). If returned value is not of one of these types - graphql-php will add an error to result and 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 returns non-null value - use GraphQL\\Type\\Definition\\Type::nonNull() modifier: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $humanType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => [ 'type' => Type::nonNull(Type::id()), 'resolve' => function() { return uniqid(); } ], 'emails' => [ 'type' => Type::nonNull(Type::listOf(Type::string())), 'resolve' => function() { return ['jon@example.com', 'jonny@example.com']; } ] ] ]); If resolver of non-null field returns null , graphql-php will add an error to result and exclude the whole object from the output (an error will bubble to first nullable parent field which will be set to null ). Read the section on Data Fetching for details.","title":"Non-Null fields"},{"location":"type-system/object-types/","text":"Object Type Definition 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, has its own type which allows building complex hierarchies. In graphql-php object type is an instance of GraphQL\\Type\\Definition\\ObjectType (or one of it subclasses) which accepts configuration array in constructor: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Examples\\Blog\\Data\\DataSource; use GraphQL\\Examples\\Blog\\Data\\Story; $userType = new ObjectType([ 'name' => 'User', 'description' => 'Our blog visitor', 'fields' => [ 'firstName' => [ 'type' => Type::string(), 'description' => 'User first name' ], 'email' => Type::string() ] ]); $blogStory = new ObjectType([ 'name' => 'Story', 'fields' => [ 'body' => Type::string(), 'author' => [ 'type' => $userType, 'description' => 'Story author', 'resolve' => function(Story $blogStory) { return DataSource::findUser($blogStory->authorId); } ], 'likes' => [ 'type' => Type::listOf($userType), 'description' => 'List of users who liked the story', 'args' => [ 'limit' => [ 'type' => Type::int(), 'description' => 'Limit the number of recent likes returned', 'defaultValue' => 10 ] ], 'resolve' => function(Story $blogStory, $args) { return DataSource::findLikes($blogStory->id, $args['limit']); } ] ] ]); This example uses inline style for Object Type definitions, but you can also use inheritance or type language . Configuration options 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. Field configuration options 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) Field arguments Every field on a GraphQL object type can have zero or more arguments, defined in args option of field definition. Each 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 Shorthand field definitions Fields can be also defined in shorthand notation (with only name and type options): 'fields' => [ 'id' => Type::id(), 'fieldName' => $fieldType ] which is equivalent of: 'fields' => [ 'id' => ['type' => Type::id()], 'fieldName' => ['type' => $fieldName] ] which is in turn equivalent of the full form: 'fields' => [ ['name' => 'id', 'type' => Type::id()], ['name' => 'fieldName', 'type' => $fieldName] ] Same shorthand notation applies to field arguments as well. Recurring and circular types Almost all real-world applications contain recurring or circular types. Think user friends or nested comments for example. graphql-php allows such types, but you have to use callable in option fields (and/or interfaces ). For example: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = null; $userType = new ObjectType([ 'name' => 'User', 'fields' => function() use (&$userType) { return [ 'email' => [ 'type' => Type::string() ], 'friends' => [ 'type' => Type::listOf($userType) ] ]; } ]); Same example for inheritance style of type definitions using TypeRegistry : <?php namespace MyApp; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; class UserType extends ObjectType { public function __construct() { $config = [ 'fields' => function() { return [ 'email' => MyTypes::string(), 'friends' => MyTypes::listOf(MyTypes::user()) ]; } ]; parent::__construct($config); } } class MyTypes { private static $user; public static function user() { return self::$user ?: (self::$user = new UserType()); } public static function string() { return Type::string(); } public static function listOf($type) { return Type::listOf($type); } } Field Resolution Field resolution is the primary mechanism in graphql-php for returning actual data for your fields. It is implemented using resolveField callable in type definition or resolve callable in field definition (which has precedence). Read the section on Data Fetching for a complete description of this process. Custom Metadata All types in graphql-php accept configuration array. In some cases, you may be interested in passing your own metadata for type or field definition. graphql-php preserves original configuration array in every type or field instance in public property $config . 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, has its own type which allows building complex hierarchies. In graphql-php object type is an instance of GraphQL\\Type\\Definition\\ObjectType (or one of it subclasses) which accepts configuration array in constructor: <?php namespace MyApp; use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Examples\\Blog\\Data\\DataSource; use GraphQL\\Examples\\Blog\\Data\\Story; $userType = new ObjectType([ 'name' => 'User', 'description' => 'Our blog visitor', 'fields' => [ 'firstName' => [ 'type' => Type::string(), 'description' => 'User first name' ], 'email' => Type::string() ] ]); $blogStory = new ObjectType([ 'name' => 'Story', 'fields' => [ 'body' => Type::string(), 'author' => [ 'type' => $userType, 'description' => 'Story author', 'resolve' => function(Story $blogStory) { return DataSource::findUser($blogStory->authorId); } ], 'likes' => [ 'type' => Type::listOf($userType), 'description' => 'List of users who liked the story', 'args' => [ 'limit' => [ 'type' => Type::int(), 'description' => 'Limit the number of recent likes returned', 'defaultValue' => 10 ] ], 'resolve' => function(Story $blogStory, $args) { return DataSource::findLikes($blogStory->id, $args['limit']); } ] ] ]); 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. Each 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' => [ 'id' => Type::id(), 'fieldName' => $fieldType ] which is equivalent of: 'fields' => [ 'id' => ['type' => Type::id()], 'fieldName' => ['type' => $fieldName] ] which is in turn equivalent of the full form: 'fields' => [ ['name' => 'id', 'type' => Type::id()], ['name' => 'fieldName', 'type' => $fieldName] ] 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. Think user friends or nested comments for example. graphql-php allows such types, but you have to use callable in option fields (and/or interfaces ). For example: <?php use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; $userType = null; $userType = new ObjectType([ 'name' => 'User', 'fields' => function() use (&$userType) { return [ 'email' => [ 'type' => Type::string() ], 'friends' => [ 'type' => Type::listOf($userType) ] ]; } ]); Same example for inheritance style of type definitions using TypeRegistry : <?php namespace MyApp; use GraphQL\\Type\\Definition\\Type; use GraphQL\\Type\\Definition\\ObjectType; class UserType extends ObjectType { public function __construct() { $config = [ 'fields' => function() { return [ 'email' => MyTypes::string(), 'friends' => MyTypes::listOf(MyTypes::user()) ]; } ]; parent::__construct($config); } } class MyTypes { private static $user; public static function user() { return self::$user ?: (self::$user = new UserType()); } public static function string() { return Type::string(); } public static function listOf($type) { return Type::listOf($type); } }","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. It is implemented using resolveField callable in type definition or resolve callable 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 passing your own metadata for type or field definition. graphql-php preserves original configuration array in every type or field instance in public property $config . Use it to implement app-level mappings and definitions.","title":"Custom Metadata"},{"location":"type-system/scalar-types/","text":"Built-in Scalar Types GraphQL specification describes several built-in scalar types. In graphql-php they are exposed as static methods of GraphQL\\Type\\Definition\\Type class: <?php use GraphQL\\Type\\Definition\\Type; // Built-in Scalar types: Type::string(); // String type Type::int(); // Int type Type::float(); // Float type Type::boolean(); // Boolean type Type::id(); // ID type Those methods return instances of GraphQL\\Type\\Definition\\ScalarType (actually one of subclasses). Use them directly in type definitions, or wrap in your TypeRegistry (if you use one). Writing Custom Scalar Types In addition to built-in scalars, you can define your own scalar types with additional validation. Typical 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. GraphQL deals with scalars in following cases: When converting internal representation of value returned by your app (e.g. stored in a database or 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 the internal representation of your app. Those cases are covered by methods serialize , parseValue and parseLiteral of abstract ScalarType class respectively. Here is an example of a simple Email type: <?php namespace MyApp; use GraphQL\\Error\\Error; use GraphQL\\Error\\InvariantViolation; use GraphQL\\Language\\AST\\StringValueNode; use GraphQL\\Type\\Definition\\ScalarType; use GraphQL\\Utils\\Utils; class EmailType extends ScalarType { // Note: name can be omitted. In this case it will be inferred from class name // (suffix \"Type\" will be dropped) public $name = 'Email'; /** * Serializes an internal value to include in a response. * * @param string $value * @return string */ public function serialize($value) { // Assuming internal representation of email is always correct: return $value; // If it might be incorrect and you want to make sure that only correct values are included // in response - use following line instead: // if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { // throw new InvariantViolation(\"Could not serialize following value as email: \" . Utils::printSafe($value)); // } // return $this->parseValue($value); } /** * Parses an externally provided value (query variable) to use as an input * * @param mixed $value * @return mixed */ public function parseValue($value) { if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { throw new Error(\"Cannot represent following value as email: \" . Utils::printSafeJson($value)); } return $value; } /** * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input. * * E.g. * { * user(email: \"user@example.com\") * } * * @param \\GraphQL\\Language\\AST\\Node $valueNode * @return string * @throws Error */ public function parseLiteral($valueNode) { // Note: throwing GraphQL\\Error\\Error vs \\UnexpectedValueException to benefit from GraphQL // error location in query: if (!$valueNode instanceof StringValueNode) { throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]); } if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { throw new Error(\"Not a valid email\", [$valueNode]); } return $valueNode->value; } } Or with inline style: <?php use GraphQL\\Type\\Definition\\CustomScalarType; $emailType = new CustomScalarType([ 'name' => 'Email', 'serialize' => function($value) {/* See function body above */}, 'parseValue' => function($value) {/* See function body above */}, 'parseLiteral' => function($valueNode) {/* See function body above */}, ]);","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 exposed as static methods of GraphQL\\Type\\Definition\\Type class: <?php use GraphQL\\Type\\Definition\\Type; // Built-in Scalar types: Type::string(); // String type Type::int(); // Int type Type::float(); // Float type Type::boolean(); // Boolean type Type::id(); // ID type Those methods return instances of GraphQL\\Type\\Definition\\ScalarType (actually one of subclasses). Use them directly in type definitions, or wrap in your TypeRegistry (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. Typical 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. GraphQL deals with scalars in following cases: When converting internal representation of value returned by your app (e.g. stored in a database or 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 the internal representation of your app. Those cases are covered by methods serialize , parseValue and parseLiteral of abstract ScalarType class respectively. Here is an example of a simple Email type: <?php namespace MyApp; use GraphQL\\Error\\Error; use GraphQL\\Error\\InvariantViolation; use GraphQL\\Language\\AST\\StringValueNode; use GraphQL\\Type\\Definition\\ScalarType; use GraphQL\\Utils\\Utils; class EmailType extends ScalarType { // Note: name can be omitted. In this case it will be inferred from class name // (suffix \"Type\" will be dropped) public $name = 'Email'; /** * Serializes an internal value to include in a response. * * @param string $value * @return string */ public function serialize($value) { // Assuming internal representation of email is always correct: return $value; // If it might be incorrect and you want to make sure that only correct values are included // in response - use following line instead: // if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { // throw new InvariantViolation(\"Could not serialize following value as email: \" . Utils::printSafe($value)); // } // return $this->parseValue($value); } /** * Parses an externally provided value (query variable) to use as an input * * @param mixed $value * @return mixed */ public function parseValue($value) { if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { throw new Error(\"Cannot represent following value as email: \" . Utils::printSafeJson($value)); } return $value; } /** * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input. * * E.g. * { * user(email: \"user@example.com\") * } * * @param \\GraphQL\\Language\\AST\\Node $valueNode * @return string * @throws Error */ public function parseLiteral($valueNode) { // Note: throwing GraphQL\\Error\\Error vs \\UnexpectedValueException to benefit from GraphQL // error location in query: if (!$valueNode instanceof StringValueNode) { throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]); } if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { throw new Error(\"Not a valid email\", [$valueNode]); } return $valueNode->value; } } Or with inline style: <?php use GraphQL\\Type\\Definition\\CustomScalarType; $emailType = new CustomScalarType([ 'name' => 'Email', 'serialize' => function($value) {/* See function body above */}, 'parseValue' => function($value) {/* See function body above */}, 'parseLiteral' => function($valueNode) {/* See function body above */}, ]);","title":"Writing Custom Scalar Types"},{"location":"type-system/schema/","text":"Schema Definition The schema is a container of your type hierarchy, which accepts root types in a constructor and provides methods for receiving information about your types to internal GrahpQL tools. In graphql-php schema is an instance of GraphQL\\Type\\Schema which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Schema; $schema = new Schema([ 'query' => $queryType, 'mutation' => $mutationType, ]); See possible constructor options below . Query and Mutation types 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 of your API: <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'hello' => [ 'type' => Type::string(), 'resolve' => function() { return 'Hello World!'; } ], 'hero' => [ 'type' => $characterInterface, 'args' => [ 'episode' => [ 'type' => $episodeEnum ] ], 'resolve' => function ($rootValue, $args) { return StarWarsData::getHero(isset($args['episode']) ? $args['episode'] : null); }, ] ] ]); $mutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ 'createReview' => [ 'type' => $createReviewOutput, 'args' => [ 'episode' => $episodeEnum, 'review' => $reviewInputObject ], 'resolve' => function($val, $args) { // TODOC } ] ] ]); Keep in mind that other than the special meaning of declaring a surface area of your API, those types are the same as any other object type , and their fields work exactly the same way. Mutation type is also just a regular object type. The difference is in semantics. Field names of Mutation type are usually verbs and they almost always have arguments - quite often with complex input values (see Mutations and Input Types for details). Configuration Options Schema constructor expects an instance of GraphQL\\Type\\SchemaConfig or 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. Using config class If you prefer fluid interface for config with auto-completion in IDE and static time validation, use GraphQL\\Type\\SchemaConfig instead of an array: <?php use GraphQL\\Type\\SchemaConfig; use GraphQL\\Type\\Schema; $config = SchemaConfig::create() ->setQuery($myQueryType) ->setTypeLoader($myTypeLoader); $schema = new Schema($config); Lazy loading of types By default, the schema will scan all of your type, field and argument definitions to serve GraphQL queries. It 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 of your object fields as callbacks. Type loading concept is very similar to PHP class loading, but keep in mind that typeLoader must always return the same instance of a type. Usage example: <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Schema; class Types { private $types = []; public function get($name) { if (!isset($this->types[$name])) { $this->types[$name] = $this->{$name}(); } return $this->types[$name]; } private function MyTypeA() { return new ObjectType([ 'name' => 'MyTypeA', 'fields' => function() { return [ 'b' => ['type' => $this->get('MyTypeB')] ]; } ]); } private function MyTypeB() { // ... } } $registry = new Types(); $schema = new Schema([ 'query' => $registry->get('Query'), 'typeLoader' => function($name) use ($registry) { return $registry->get($name); } ]); Schema Validation By default, the schema is created with only shallow validation of type and field definitions (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. Don't call it in web requests in production. Usage example: <?php try { $schema = new GraphQL\\Type\\Schema([ 'query' => $myQueryType ]); $schema->assertValid(); } catch (GraphQL\\Error\\InvariantViolation $e) { echo $e->getMessage(); }","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 methods for receiving information about your types to internal GrahpQL tools. In graphql-php schema is an instance of GraphQL\\Type\\Schema which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Schema; $schema = new Schema([ 'query' => $queryType, 'mutation' => $mutationType, ]); 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 of your API: <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Definition\\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'hello' => [ 'type' => Type::string(), 'resolve' => function() { return 'Hello World!'; } ], 'hero' => [ 'type' => $characterInterface, 'args' => [ 'episode' => [ 'type' => $episodeEnum ] ], 'resolve' => function ($rootValue, $args) { return StarWarsData::getHero(isset($args['episode']) ? $args['episode'] : null); }, ] ] ]); $mutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ 'createReview' => [ 'type' => $createReviewOutput, 'args' => [ 'episode' => $episodeEnum, 'review' => $reviewInputObject ], 'resolve' => function($val, $args) { // TODOC } ] ] ]); Keep in mind that other than the special meaning of declaring a surface area of your API, those types are the same as any other object type , and their fields work exactly the same way. Mutation type is also just a regular object type. The difference is in semantics. Field names of Mutation type are usually verbs and they almost always have arguments - quite often with 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 or 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, use GraphQL\\Type\\SchemaConfig instead of an array: <?php use GraphQL\\Type\\SchemaConfig; use GraphQL\\Type\\Schema; $config = SchemaConfig::create() ->setQuery($myQueryType) ->setTypeLoader($myTypeLoader); $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. It 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 of your object fields as callbacks. Type loading concept is very similar to PHP class loading, but keep in mind that typeLoader must always return the same instance of a type. Usage example: <?php use GraphQL\\Type\\Definition\\ObjectType; use GraphQL\\Type\\Schema; class Types { private $types = []; public function get($name) { if (!isset($this->types[$name])) { $this->types[$name] = $this->{$name}(); } return $this->types[$name]; } private function MyTypeA() { return new ObjectType([ 'name' => 'MyTypeA', 'fields' => function() { return [ 'b' => ['type' => $this->get('MyTypeB')] ]; } ]); } private function MyTypeB() { // ... } } $registry = new Types(); $schema = new Schema([ 'query' => $registry->get('Query'), 'typeLoader' => function($name) use ($registry) { return $registry->get($name); } ]);","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 (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. Don't call it in web requests in production. Usage example: <?php try { $schema = new GraphQL\\Type\\Schema([ 'query' => $myQueryType ]); $schema->assertValid(); } catch (GraphQL\\Error\\InvariantViolation $e) { echo $e->getMessage(); }","title":"Schema Validation"},{"location":"type-system/type-language/","text":"Defining your schema Since 0.9.0 Type language is a convenient way to define your schema, especially 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 { query: Query mutation: Mutation } type Query { greetings(input: HelloInput!): String! } input HelloInput { firstName: String! lastName: String } In order to create schema instance out of this file, use GraphQL\\Utils\\BuildSchema : <?php use GraphQL\\Utils\\BuildSchema; $contents = file_get_contents('schema.graphql'); $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 order to execute a query against this schema. Performance considerations Since 0.10.0 Method build() produces a lazy schema automatically, 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 intermediate parsed representation of the schema for the production environment: <?php use GraphQL\\Language\\Parser; use GraphQL\\Utils\\BuildSchema; use GraphQL\\Utils\\AST; $cacheFilename = 'cached_schema.php'; if (!file_exists($cacheFilename)) { $document = Parser::parse(file_get_contents('./schema.graphql')); file_put_contents($cacheFilename, \"<?php\\nreturn \" . var_export(AST::toArray($document), true)); } else { $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well } $typeConfigDecorator = function () {}; $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, especially 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 { query: Query mutation: Mutation } type Query { greetings(input: HelloInput!): String! } input HelloInput { firstName: String! lastName: String } In order to create schema instance out of this file, use GraphQL\\Utils\\BuildSchema : <?php use GraphQL\\Utils\\BuildSchema; $contents = file_get_contents('schema.graphql'); $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 order 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 automatically, 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 intermediate parsed representation of the schema for the production environment: <?php use GraphQL\\Language\\Parser; use GraphQL\\Utils\\BuildSchema; use GraphQL\\Utils\\AST; $cacheFilename = 'cached_schema.php'; if (!file_exists($cacheFilename)) { $document = Parser::parse(file_get_contents('./schema.graphql')); file_put_contents($cacheFilename, \"<?php\\nreturn \" . var_export(AST::toArray($document), true)); } else { $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well } $typeConfigDecorator = function () {}; $schema = BuildSchema::build($document, $typeConfigDecorator);","title":"Performance considerations"},{"location":"type-system/unions/","text":"Union Type Definition A Union is an abstract type that simply enumerates other Object Types. The 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 (or one of its subclasses) which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Definition\\UnionType; $searchResultType = new UnionType([ 'name' => 'SearchResult', 'types' => [ MyTypes::story(), MyTypes::user() ], 'resolveType' => function($value) { if ($value->type === 'story') { return MyTypes::story(); } else { return MyTypes::user(); } } ]); This example uses inline style for Union definition, but you can also use inheritance or type language . Configuration options 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":"Unions"},{"location":"type-system/unions/#union-type-definition","text":"A Union is an abstract type that simply enumerates other Object Types. The 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 (or one of its subclasses) which accepts configuration array in a constructor: <?php use GraphQL\\Type\\Definition\\UnionType; $searchResultType = new UnionType([ 'name' => 'SearchResult', 'types' => [ MyTypes::story(), MyTypes::user() ], 'resolveType' => function($value) { if ($value->type === 'story') { return MyTypes::story(); } else { return MyTypes::user(); } } ]); 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"}]} |