This commit is contained in:
Kilian Hofmann
2021-06-01 19:56:34 +02:00
parent e74df463f2
commit 499abe195e
284 changed files with 55166 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
# Config Validation
Defining types using arrays may be error-prone, but **graphql-php** provides config validation
tool to report when config has unexpected structure.
This validation tool is **disabled by default** because it is time-consuming operation which only
makes sense during development.
To enable validation - call: `GraphQL\Type\Definition\Config::enableValidation();` in your bootstrap
but make sure to restrict it to debug/development mode only.
# 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:
+25
View File
@@ -0,0 +1,25 @@
# Integrations
* [Standard Server](executing-queries.md/#using-server) Out of the box integration with any PSR-7 compatible framework (like [Slim](http://slimframework.com) or [Zend Expressive](http://zendframework.github.io/zend-expressive/)).
* [Relay Library for graphql-php](https://github.com/ivome/graphql-relay-php) Helps construct Relay related schema definitions.
* [Lighthouse](https://github.com/nuwave/lighthouse) Laravel based, uses Schema Definition Language
* [OverblogGraphQLBundle](https://github.com/overblog/GraphQLBundle) Bundle for Symfony
* [WP-GraphQL](https://github.com/wp-graphql/wp-graphql) - GraphQL API for WordPress
# GraphQL PHP Tools
* [GraphQLite](https://graphqlite.thecodingmachine.io) Define your complete schema with annotations
* [GraphQL Doctrine](https://github.com/Ecodev/graphql-doctrine) Define types with Doctrine ORM annotations
* [DataLoaderPHP](https://github.com/overblog/dataloader-php) as a ready implementation for [deferred resolvers](data-fetching.md#solving-n1-problem)
* [GraphQL Uploads](https://github.com/Ecodev/graphql-upload) A PSR-15 middleware to support file uploads in GraphQL.
* [GraphQL Batch Processor](https://github.com/vasily-kartashov/graphql-batch-processing) Provides a builder interface for defining collection, querying, filtering, and post-processing logic of batched data fetches.
* [GraphQL Utils](https://github.com/simPod/GraphQL-Utils) Objective schema definition builders (no need for arrays anymore) and `DateTime` scalar
* [PSR 15 compliant middleware](https://github.com/phps-cans/psr7-middleware-graphql) for the Standard Server _(experimental)_
# General GraphQL Tools
* [GraphQL Playground](https://github.com/prismagraphql/graphql-playground) GraphQL IDE for better development workflows (GraphQL Subscriptions, interactive docs & collaboration).
* [GraphiQL](https://github.com/graphql/graphiql) An in-browser IDE for exploring GraphQL
* [ChromeiQL](https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij)
or [GraphiQL Feen](https://chrome.google.com/webstore/detail/graphiql-feen/mcbfdonlkfpbfdpimkjilhdneikhfklp)
GraphiQL as Google Chrome extension
+139
View File
@@ -0,0 +1,139 @@
# 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](executing-queries.md#using-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:
```graphql
{
hero {
name
friends {
name
}
}
}
```
It was designed to mirror the structure of expected response:
```json
{
"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](data-fetching.md) 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:
```graphql
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:
```json
// 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
<?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](http://graphql.org/learn/)
To get started with **graphql-php** - continue to next section ["Getting Started"](getting-started.md)
+273
View File
@@ -0,0 +1,273 @@
# 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](type-system/object-types.md#field-configuration-options) or [query execution call](executing-queries.md#overview).
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:
```graphql
{
lastStory {
title
author {
name
}
}
}
```
We need a Schema that can fulfill it. On the very top level the Schema contains Query type:
```php
<?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
<?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
<?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, $info) : $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](executing-queries.md) 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](type-system/object-types.md#configuration-options). For example:
```php
<?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](https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/). <br>
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
<?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](https://github.com/facebook/dataloader)
project. This solution enables very interesting optimizations at no cost. Consider the following query:
```graphql
{
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+](https://promisesaplus.com/) specification.
To start using this feature, switch facade method for query execution from
**executeQuery** to **promiseToExecute**:
```php
<?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](https://github.com/reactphp/react) (requires **react/promise** as composer dependency): <br>
`GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter`
* Other platforms: write your own class implementing interface: <br>
[`GraphQL\Executor\Promise\PromiseAdapter`](reference.md#graphqlexecutorpromisepromiseadapter).
Then your **resolve** functions should return promises of your platform instead of `GraphQL\Deferred`s.
+193
View File
@@ -0,0 +1,193 @@
# 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`](reference.md#graphqlexecutorexecutionresult).
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](#custom-error-handling-and-formatting)
for your specific requirements.
# Default Error formatting
By default, each error entry is converted to an associative array with following structure:
```php
<?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`](reference.md#graphqlerrorclientaware) and claiming themselves as **safe** will
be reported with a full error message.
For example:
```php
<?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
<?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
<?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 the first resolver exception to be re-thrown, use following flags:
```php
<?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);
```
If you only want to re-throw Exceptions that are not marked as safe through the `ClientAware` interface, use
the flag `Debug::RETHROW_UNSAFE_EXCEPTIONS`.
# 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`](reference.md#graphqlerrorerror)
to an array. **Handler** is useful for error filtering and logging.
For example, these are default formatter and handler:
```php
<?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](#debugging-tools) 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
<?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);
```
+208
View File
@@ -0,0 +1,208 @@
# Using Facade Method
Query execution is a complex process involving multiple steps, including query **parsing**,
**validating** and finally **executing** against your [schema](type-system/schema.md).
**graphql-php** provides a convenient facade for this process in class
[`GraphQL\GraphQL`](reference.md#graphqlgraphql):
```php
<?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`](reference.md#graphqlexecutorexecutionresult)
which can be easily converted to array:
```php
$serializableResult = $result->toArray();
```
Returned array contains **data** and **errors** keys, as described by the
[GraphQL spec](http://facebook.github.io/graphql/#sec-Response-Format).
This array is suitable for further serialization (e.g. using **json_encode**).
See also the section on [error handling and formatting](error-handling.md).
Description of **executeQuery** method arguments:
Argument | Type | Notes
------------ | -------- | -----
schema | [`GraphQL\Type\Schema`](#) | **Required.** Instance of your application [Schema](type-system/schema.md)
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](type-system/schema.md#query-and-mutation-types). 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.<br><br>It will be available as the 3rd argument in all field resolvers. (see section on [Field Definitions](type-system/object-types.md#field-configuration-options) 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](http://graphql.org/learn/queries/#variables). Note that while variableValues must be an associative array, the values inside it can be nested using \stdClass if desired.
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](data-fetching.md#default-field-resolver).
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](https://github.com/graphql/express-graphql)).
It supports more features out of the box, including parsing HTTP requests, producing a spec-compliant response; [batched queries](#query-batching); persisted queries.
Usage example (with plain PHP):
```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](http://www.php-fig.org/psr/psr-7/):
```php
<?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](https://laravel.com/docs/5.1/requests#psr7-requests)
- [Symfony PSR-7 Bridge](https://symfony.com/doc/current/components/psr7.html)
- [Slim](https://www.slimframework.com/docs/concepts/value-objects.html)
- [Zend Expressive](http://zendframework.github.io/zend-expressive/)
## Server configuration options
Argument | Type | Notes
------------ | -------- | -----
schema | [`Schema`](reference.md#graphqltypeschema) | **Required.** Instance of your application [Schema](type-system/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](type-system/schema.md#query-and-mutation-types). 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.<br><br>It will be available as the 3rd argument in all field resolvers. (see section on [Field Definitions](type-system/object-types.md#field-configuration-options) 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](data-fetching.md#default-field-resolver).
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).<br><br>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: <br><br> **function ([OperationParams](reference.md#graphqlserveroperationparams) $params, DocumentNode $node, $operationType): array**
queryBatching | `bool` | Flag indicating whether this server supports query batching ([apollo-style](https://dev-blog.apollodata.com/query-batching-in-apollo-63acfd859862)).<br><br> Defaults to **false**
debug | `int` | Debug flags. See [docs on error debugging](error-handling.md#debugging-tools) (flag values are the same).
persistentQueryLoader | `callable` | A function which is called to fetch actual query when server encounters **queryId** in request vs **query**.<br><br> 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.<br><br> Expected function signature:<br> **function ($queryId, [OperationParams](reference.md#graphqlserveroperationparams) $params)** <br><br>Function is expected to return query **string** or parsed **DocumentNode** <br><br> [Read more about persisted queries](https://dev-blog.apollodata.com/persisted-graphql-queries-with-apollo-client-119fd7e6bba5).
errorFormatter | `callable` | Custom error formatter. See [error handling docs](error-handling.md#custom-error-handling-and-formatting).
errorsHandler | `callable` | Custom errors handler. See [error handling docs](error-handling.md#custom-error-handling-and-formatting).
promiseAdapter | [`PromiseAdapter`](reference.md#graphqlexecutorpromisepromiseadapter) | Required for [Async PHP](data-fetching/#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`](reference.md#graphqlserverserverconfig) instead of an array:
```php
<?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](https://dev-blog.apollodata.com/query-batching-in-apollo-63acfd859862)).
One of the major benefits of Server over a sequence of **executeQuery()** calls is that
[Deferred resolvers](data-fetching.md#solving-n1-problem) won't be isolated in queries.
So for example following batch will require single DB request (if user field is deferred):
```json
[
{
"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
<?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
<?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
<?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
<?php
use GraphQL\Server\StandardServer;
$server = new StandardServer([
'validationRules' => $myValiationRules
]);
```
+125
View File
@@ -0,0 +1,125 @@
# Prerequisites
This documentation assumes your familiarity with GraphQL concepts. If it is not the case -
first learn about GraphQL on [the official website](http://graphql.org/learn/).
# Installation
Using [composer](https://getcomposer.org/doc/00-intro.md), run:
```sh
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](https://github.com/webonyx/graphql-php/blob/master/UPGRADE.md).
# 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](https://github.com/graphql/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](https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij)
- [GraphiQL Feen](https://chrome.google.com/webstore/detail/graphiql-feen/mcbfdonlkfpbfdpimkjilhdneikhfklp)
Alternatively, you can follow instructions on [the GraphiQL](https://github.com/graphql/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
<?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](type-system/index.md#type-definition-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
<?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:
```sh
php -S localhost:8080 graphql.php
curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
```
Check out the full [source code](https://github.com/webonyx/graphql-php/blob/master/examples/00-hello-world) 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](type-system/index.md).
# 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](https://github.com/webonyx/graphql-php/tree/master/examples/01-blog).
It is quite close to real-world GraphQL hierarchies. Follow instructions and try it yourself in ~10 minutes.
+35
View File
@@ -0,0 +1,35 @@
# 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.
+55
View File
@@ -0,0 +1,55 @@
[![GitHub stars](https://img.shields.io/github/stars/webonyx/graphql-php.svg?style=social&label=Star)](https://github.com/webonyx/graphql-php)
[![Build Status](https://travis-ci.org/webonyx/graphql-php.svg?branch=master)](https://travis-ci.org/webonyx/graphql-php)
[![Coverage Status](https://coveralls.io/repos/github/webonyx/graphql-php/badge.svg)](https://coveralls.io/github/webonyx/graphql-php)
[![Latest Stable Version](https://poser.pugx.org/webonyx/graphql-php/version)](https://packagist.org/packages/webonyx/graphql-php)
[![License](https://poser.pugx.org/webonyx/graphql-php/license)](https://packagist.org/packages/webonyx/graphql-php)
# About GraphQL
GraphQL is a modern way to build HTTP APIs consumed by the web and mobile clients.
It is intended to be an alternative to REST and SOAP APIs (even for **existing applications**).
GraphQL itself is a [specification](https://github.com/facebook/graphql) designed by Facebook
engineers. Various implementations of this specification were written
[in different languages and environments](http://graphql.org/code/).
Great overview of GraphQL features and benefits is presented on [the official website](http://graphql.org/).
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](https://github.com/graphql/graphql-js)
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](type-system/index.md)
- Validation and introspection of this Type System (for compatibility with tools like [GraphiQL](complementary-tools.md#tools))
- Parsing, validating and [executing GraphQL queries](executing-queries.md) against this Type System
- Rich [error reporting](error-handling.md), including query validation and execution errors
- Optional tools for [parsing GraphQL Type language](type-system/type-language.md)
- Tools for [batching requests](data-fetching.md#solving-n1-problem) to backend storage
- [Async PHP platforms support](data-fetching.md#async-php) via promises
- [Standard HTTP server](executing-queries.md#using-server)
Also, several [complementary tools](complementary-tools.md) 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](type-system/type-language.md) and
[Schema printer](reference.md#graphqlutilsschemaprinter).
Ready for real-world usage.
## GitHub
Project source code is [hosted on GitHub](https://github.com/webonyx/graphql-php).
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
# Query Complexity Analysis
This is a PHP port of [Query Complexity Analysis](http://sangria-graphql.org/learn/#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
<?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](executing-queries.md#custom-validation-rules).
To customize field score add **complexity** function to field definition:
```php
<?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](http://sangria-graphql.org/learn/#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
<?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](executing-queries.md#custom-validation-rules).
# Disabling Introspection
[Introspection](http://graphql.org/learn/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
<?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](executing-queries.md#custom-validation-rules).
@@ -0,0 +1,61 @@
# 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:
```graphql
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`](../reference.md#graphqltypedefinitionresolveinfo)
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
<?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`](../reference.md#graphqllanguagedirectivelocation).
@@ -0,0 +1,182 @@
# 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
<?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](index.md#type-definition-styles).
# 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](#shorthand-definitions) below)
description | `string` | Plain-text description of the type for clients (e.g. used by [GraphiQL](https://github.com/graphql/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](#shorthand-definitions) 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](https://github.com/graphql/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
<?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
<?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
<?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
<?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
<?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:
```graphql
fragment on Hero {
appearsInNewHope: appearsIn(NEWHOPE)
appearsInEmpire: appearsIn(EMPIRE)
}
```
will return:
```php
[
'appearsInNewHope' => false,
'appearsInEmpire' => true
]
```
+127
View File
@@ -0,0 +1,127 @@
# Type System
To start using GraphQL you are expected to implement a type hierarchy and expose it as [Schema](schema.md).
In graphql-php **type** is an instance of internal class from
`GraphQL\Type\Definition` namespace: [`ObjectType`](object-types.md),
[`InterfaceType`](interfaces.md), [`UnionType`](unions.md), [`InputObjectType`](input-types.md),
[`ScalarType`](scalar-types.md), [`EnumType`](enum-types.md) (or one of subclasses).
But most of the types in your schema will be [object types](object-types.md).
# Type Definition Styles
Several styles of type definitions are supported depending on your preferences.
Inline definitions:
```php
<?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
<?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](http://graphql.org/learn/schema/#type-language):
```graphql
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-language.md).
# 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
<?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
<?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.
@@ -0,0 +1,172 @@
# Mutations
Mutation is just a field of a regular [Object Type](object-types.md) with arguments.
For GraphQL PHP runtime there is no difference between query fields with arguments and mutations.
They are executed [almost](http://facebook.github.io/graphql/#sec-Mutation) identically.
To some extent, Mutation is just a convention described in the GraphQL spec.
Here is an example of a mutation operation:
```graphql
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](schema.md):
```php
<?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](scalar-types.md), [Enum](enum-types.md), [Object](object-types.md),
[Interface](interfaces.md), [Union](unions.md)
* **Input** types (or argument types) are: [Scalar](scalar-types.md), [Enum](enum-types.md), InputObject
Obviously, [NonNull and List](lists-and-nonnulls.md) types belong to both categories depending on their
inner type.
Until now all examples of field **arguments** in this documentation were of [Scalar](scalar-types.md) or
[Enum](enum-types.md) 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
<?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](https://github.com/graphql/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](input-types.md) (**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](https://github.com/graphql/graphiql) for auto-generated documentation)
defaultValue | `scalar` | Default value of this input field. Use the internal value if specifying a default for an **enum** type
# Using Input Object Type
In the example above we defined our InputObjectType. Now let's use it in one of field arguments:
```php
<?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:
```graphql
{
stories(filters: {author: "1", popular: false})
}
```
Or as query variable:
```graphql
query($filters: StoryFiltersInput!) {
stories(filters: $filters)
}
```
```php
$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']`
@@ -0,0 +1,136 @@
# 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
<?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](index.md#type-definition-styles).
# 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](object-types.md#field-configuration-options)
description | `string` | Plain-text description of this type for clients (e.g. used by [GraphiQL](https://github.com/graphql/graphiql) for auto-generated documentation)
resolveType | `callback` | **function($value, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**<br> 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
<?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](#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
<?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:
1. If field resolution algorithm is the same for all Interface implementors - you can simply add
**resolve** option to field definition in Interface itself.
2. If field resolution varies for different implementations - you can specify **resolveField**
option in [Object Type config](object-types.md#configuration-options) 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.
@@ -0,0 +1,62 @@
# 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
<?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
<?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](../data-fetching.md) for details.
@@ -0,0 +1,210 @@
# 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
<?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](index.md#type-definition-styles).
# 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](#field-definitions) section below for expected structure of each array entry. See also the section on [Circular types](#recurring-and-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](https://github.com/graphql/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](interfaces.md) for details. See also the section on [Circular types](#recurring-and-circular-types) for an explanation of when to use callable for this option.
isTypeOf | `callable` | **function($value, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**<br> Expected to return **true** if **$value** qualifies for this type (see section about [Abstract Type Resolution](interfaces.md#interface-role-in-data-fetching) for explanation).
resolveField | `callable` | **function($value, $args, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**<br> 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](../data-fetching.md) 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](#shorthand-field-definitions) 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](index.md#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](#field-arguments) section below.
resolve | `callable` | **function($value, $args, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**<br> Given the **$value** of this type, it is expected to return actual value of the current field. See section on [Data Fetching](../data-fetching.md) for details
complexity | `callable` | **function($childrenComplexity, $args)**<br> Used to restrict query complexity. The feature is disabled by default, read about [Security](../security.md#query-complexity-analysis) to use it.
description | `string` | Plain-text description of this field for clients (e.g. used by [GraphiQL](https://github.com/graphql/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](input-types.md) (**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](https://github.com/graphql/graphiql) for auto-generated documentation)
defaultValue | `scalar` | Default value for this argument. Use the internal value if specifying a default for an **enum** type
# Shorthand field definitions
Fields can be also defined in **shorthand** notation (with only **name** and **type** options):
```php
'fields' => [
'id' => Type::id(),
'fieldName' => $fieldType
]
```
which is equivalent of:
```php
'fields' => [
'id' => ['type' => Type::id()],
'fieldName' => ['type' => $fieldName]
]
```
which is in turn equivalent of the full form:
```php
'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
<?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](index.md#type-definition-styles) using [TypeRegistry](index.md#type-registry):
```php
<?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](../data-fetching.md) 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.
@@ -0,0 +1,130 @@
# 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`](../reference.md#graphqltypedefinitiontype) class:
```php
<?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](index.md#type-registry)
(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:
1. 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.
2. When converting **input value** passed by a client in variables along with GraphQL query to
**internal representation** of your app.
3. 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
<?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
* @param array|null $variables
* @return string
* @throws Error
*/
public function parseLiteral($valueNode, array $variables = null)
{
// 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
<?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, array $variables = null) {/* See function body above */},
]);
```
+194
View File
@@ -0,0 +1,194 @@
# 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`](../reference.md#graphqltypeschema)
which accepts configuration array in a constructor:
```php
<?php
use GraphQL\Type\Schema;
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType,
]);
```
See possible constructor options [below](#configuration-options).
# 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](object-types.md) containing root-level fields
of your API:
```php
<?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](object-types.md), 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](input-types.md) for details).
# Configuration Options
Schema constructor expects an instance of [`GraphQL\Type\SchemaConfig`](../reference.md#graphqltypeschemaconfig)
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](directives.md) supported by your schema. By default, contains built-in **@skip** and **@include** directives.<br><br> If you pass your own directives and still want to use built-in directives - add them explicitly. For example:<br><br> *array_merge(GraphQL::getStandardDirectives(), [$myCustomDirective]);*
types | `ObjectType[]` | List of object types which cannot be detected by **graphql-php** during static schema analysis.<br><br>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. <br><br> 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`](../reference.md#graphqltypeschemaconfig) instead of an array:
```php
<?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
<?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
<?php
try {
$schema = new GraphQL\Type\Schema([
'query' => $myQueryType
]);
$schema->assertValid();
} catch (GraphQL\Error\InvariantViolation $e) {
echo $e->getMessage();
}
```
@@ -0,0 +1,91 @@
# Defining your schema
Since 0.9.0
[Type language](http://graphql.org/learn/schema/#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):
```graphql
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`](../reference.md#graphqlutilsbuildschema):
```php
<?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](../data-fetching.md#default-field-resolver) and **root value** in
order to execute a query against this schema.
# Defining resolvers
Since 0.10.0
In order to enable **Interfaces**, **Unions** and custom field resolvers you can pass the second argument:
**type config decorator** to schema builder.
It accepts default type config produced by the builder and is expected to add missing options like
[**resolveType**](interfaces.md#configuration-options) for interface types or
[**resolveField**](object-types.md#configuration-options) for object types.
```php
<?php
use GraphQL\Utils\BuildSchema;
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
$name = $typeConfig['name'];
// ... add missing options to $typeConfig based on type $name
return $typeConfig;
};
$contents = file_get_contents('schema.graphql');
$schema = BuildSchema::build($contents, $typeConfigDecorator);
```
# Performance considerations
Since 0.10.0
Method **build()** produces a [lazy schema](schema.md#lazy-loading-of-types)
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
<?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) . ";\n");
} else {
$document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well
}
$typeConfigDecorator = function () {};
$schema = BuildSchema::build($document, $typeConfigDecorator);
```
+39
View File
@@ -0,0 +1,39 @@
# 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
<?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](index.md#type-definition-styles).
# 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](https://github.com/graphql/graphiql) for auto-generated documentation)
resolveType | `callback` | **function($value, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**<br> Receives **$value** from resolver of the parent field and returns concrete Object Type for this **$value**.