Skip to content
This repository has been archived by the owner on Jul 8, 2022. It is now read-only.

Latest commit

 

History

History
2231 lines (2037 loc) · 50.9 KB

reference.md

File metadata and controls

2231 lines (2037 loc) · 50.9 KB

Sage\Sage

This is the primary facade for fulfilling Sage operations. See related documentation.

Class Methods:

static function execute(
    Sage\Type\Schema $schema,
    Sage\Document $document,
    $context = null,
    array $options = null
): Sage\Executor\ExecutionResult
/**
 * Same as execute(), but requires PromiseAdapter and always returns a Promise.
 * Useful for Async PHP platforms.
 *
 * @param Document   $source
 * @param mixed                 $rootValue
 * @param mixed                 $context
 * @param mixed[]|null          $variableValues
 * @param ValidationRule[]|null $validationRules
 *
 * @api
 */
static function promiseToExecute(
    Sage\Executor\Promise\PromiseAdapter $promiseAdapter,
    Sage\Type\Schema $schema,
    $source,
    $rootValue = null,
    $context = null,
    $variableValues = null,
    string $operationName = null,
    callable $fieldResolver = null,
    array $validationRules = null
): Sage\Executor\Promise\Promise

Sage\Type\Definition\Type

Registry of standard Sage types and a base class for all other types.

Class Methods:

/**
 * @api
 */
static function id(): Sage\Type\Definition\ScalarType
/**
 * @api
 */
static function string(): Sage\Type\Definition\ScalarType
/**
 * @api
 */
static function boolean(): Sage\Type\Definition\ScalarType
/**
 * @api
 */
static function int(): Sage\Type\Definition\ScalarType
/**
 * @api
 */
static function float(): Sage\Type\Definition\ScalarType
/**
 * @api
 */
static function listOf(Sage\Type\Definition\Type $wrappedType): Sage\Type\Definition\ListOfType
/**
 * @param callable|NullableType $wrappedType
 *
 * @api
 */
static function nonNull($wrappedType): Sage\Type\Definition\NonNull
/**
 * @param Type $type
 *
 * @api
 */
static function isInputType($type): bool
/**
 * @param Type $type
 *
 * @api
 */
static function getNamedType($type): Sage\Type\Definition\Type
/**
 * @param Type $type
 *
 * @api
 */
static function isOutputType($type): bool
/**
 * @param Type $type
 *
 * @api
 */
static function isLeafType($type): bool
/**
 * @param Type $type
 *
 * @api
 */
static function isCompositeType($type): bool
/**
 * @param Type $type
 *
 * @api
 */
static function isAbstractType($type): bool
/**
 * @api
 */
static function getNullableType(Sage\Type\Definition\Type $type): Sage\Type\Definition\Type

Sage\Type\Definition\ResolveInfo

Structure containing information useful for field resolution process.

Passed as 4th argument to every field resolver. See docs on field resolving (data fetching).

Class Props:

/**
 * The definition of the field being resolved.
 *
 * @api
 * @var FieldDefinition
 */
public $fieldDefinition;

/**
 * The name of the field being resolved.
 *
 * @api
 * @var string
 */
public $fieldName;

/**
 * Expected return type of the field being resolved.
 *
 * @api
 * @var Type
 */
public $returnType;

/**
 * AST of all nodes referencing this field in the query.
 *
 * @api
 * @var FieldNode[]
 */
public $fieldNodes;

/**
 * Parent type of the field being resolved.
 *
 * @api
 * @var ObjectType
 */
public $parentType;

/**
 * Path to this field from the very root value.
 *
 * @api
 * @var string[]
 */
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|null
 */
public $operation;

/**
 * Array of variables passed to query execution.
 *
 * @api
 * @var mixed[]
 */
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.
 *
 * @param int $depth How many levels to include in output
 *
 * @return array<string, mixed>
 *
 * @api
 */
function getFieldSelection($depth = 0)

Sage\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 VARIABLE_DEFINITION = "VARIABLE_DEFINITION";
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";

Sage\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:

$settings = SchemaConfig::create()
    ->setQuery($myQueryType)
    ->setTypeLoader($myTypeLoader);

$schema = new Schema($settings);

Class Methods:

/**
 * Converts an array of options to instance of SchemaConfig
 * (or just returns empty config when array is not passed).
 *
 * @param mixed[] $options
 *
 * @return SchemaConfig
 *
 * @api
 */
static function create(array $options = [])
/**
 * @return ObjectType|null
 *
 * @api
 */
function getQuery()
/**
 * @param ObjectType|null $query
 *
 * @return SchemaConfig
 *
 * @api
 */
function setQuery($query)
/**
 * @return ObjectType|null
 *
 * @api
 */
function getMutation()
/**
 * @param ObjectType|null $mutation
 *
 * @return SchemaConfig
 *
 * @api
 */
function setMutation($mutation)
/**
 * @return ObjectType|null
 *
 * @api
 */
function getSubscription()
/**
 * @param ObjectType|null $subscription
 *
 * @return SchemaConfig
 *
 * @api
 */
function setSubscription($subscription)
/**
 * @return Type[]|callable
 *
 * @api
 */
function getTypes()
/**
 * @param Type[]|callable $types
 *
 * @return SchemaConfig
 *
 * @api
 */
function setTypes($types)
/**
 * @return Directive[]|null
 *
 * @api
 */
function getDirectives()
/**
 * @param Directive[] $directives
 *
 * @return SchemaConfig
 *
 * @api
 */
function setDirectives(array $directives)
/**
 * @return callable(string $name):Type|null
 *
 * @api
 */
function getTypeLoader()
/**
 * @return SchemaConfig
 *
 * @api
 */
function setTypeLoader(callable $typeLoader)

Sage\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 Sage\Type\Schema([
  'query' => $MyAppQueryRootType,
  'mutation' => $MyAppMutationRootType,
]);

Or using Schema Config instance:

$settings = Sage\Type\SchemaConfig::create()
    ->setQuery($MyAppQueryRootType)
    ->setMutation($MyAppMutationRootType);

$schema = new Sage\Type\Schema($settings);

Class Methods:

/**
 * @param mixed[]|SchemaConfig $settings
 *
 * @api
 */
function __construct($settings)
/**
 * 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.
 *
 * @return Type[]
 *
 * @api
 */
function getTypeMap()
/**
 * Returns a list of directives supported by this schema
 *
 * @return Directive[]
 *
 * @api
 */
function getDirectives()
/**
 * Returns schema query type
 *
 * @return ObjectType
 *
 * @api
 */
function getQueryType(): Sage\Type\Definition\Type
/**
 * Returns schema mutation type
 *
 * @return ObjectType|null
 *
 * @api
 */
function getMutationType(): Sage\Type\Definition\Type
/**
 * Returns schema subscription
 *
 * @return ObjectType|null
 *
 * @api
 */
function getSubscriptionType(): Sage\Type\Definition\Type
/**
 * @return SchemaConfig
 *
 * @api
 */
function getConfig()
/**
 * Returns type by its name
 *
 * @api
 */
function getType(string $name): Sage\Type\Definition\Type
/**
 * 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.
 *
 * @param InterfaceType|UnionType $abstractType
 *
 * @return array<Type&ObjectType>
 *
 * @api
 */
function getPossibleTypes(Sage\Type\Definition\Type $abstractType): array
/**
 * Returns true if object type is concrete type of given abstract type
 * (implementation for interfaces and members of union type for unions)
 *
 * @api
 */
function isPossibleType(
    Sage\Type\Definition\AbstractType $abstractType,
    Sage\Type\Definition\ObjectType $possibleType
): bool
/**
 * Returns instance of directive by name
 *
 * @api
 */
function getDirective(string $name): Sage\Type\Definition\Directive
/**
 * Validates schema.
 *
 * This operation requires full schema scan. Do not use in production environment.
 *
 * @throws InvariantViolation
 *
 * @api
 */
function assertValid()
/**
 * Validates schema.
 *
 * This operation requires full schema scan. Do not use in production environment.
 *
 * @return InvariantViolation[]|Error[]
 *
 * @api
 */
function validate()

Sage\Language\Parser

Parses string containing Sage query or type definition to Abstract Syntax Tree.

Those magic functions allow partial parsing:

@method static DocumentNode document(Source|string $source, bool[] $options = []) @method static ExecutableDefinitionNode executableDefinition(Source|string $source, bool[] $options = []) @method static string operationType(Source|string $source, bool[] $options = []) @method static VariableDefinitionNode variableDefinition(Source|string $source, bool[] $options = []) @method static SelectionSetNode selectionSet(Source|string $source, bool[] $options = []) @method static FieldNode field(Source|string $source, bool[] $options = []) @method static NodeList constArguments(Source|string $source, bool[] $options = []) @method static ArgumentNode constArgument(Source|string $source, bool[] $options = []) @method static FragmentDefinitionNode fragmentDefinition(Source|string $source, bool[] $options = []) @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|NullValueNode|ObjectValueNode|StringValueNode|VariableNode valueLiteral(Source|string $source, bool[] $options = []) @method static StringValueNode stringLiteral(Source|string $source, bool[] $options = []) @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode variableValue(Source|string $source, bool[] $options = []) @method static ListValueNode constArray(Source|string $source, bool[] $options = []) @method static ObjectValueNode constObject(Source|string $source, bool[] $options = []) @method static ObjectFieldNode constObjectField(Source|string $source, bool[] $options = []) @method static NodeList constDirectives(Source|string $source, bool[] $options = []) @method static DirectiveNode constDirective(Source|string $source, bool[] $options = []) @method static NamedTypeNode namedType(Source|string $source, bool[] $options = []) @method static StringValueNode|null description(Source|string $source, bool[] $options = []) @method static OperationTypeDefinitionNode operationTypeDefinition(Source|string $source, bool[] $options = []) @method static ObjectTypeDefinitionNode objectTypeDefinition(Source|string $source, bool[] $options = []) @method static NodeList fieldsDefinition(Source|string $source, bool[] $options = []) @method static NodeList argumentsDefinition(Source|string $source, bool[] $options = []) @method static InterfaceTypeDefinitionNode interfaceTypeDefinition(Source|string $source, bool[] $options = []) @method static NamedTypeNode[] unionMemberTypes(Source|string $source, bool[] $options = []) @method static NodeList enumValuesDefinition(Source|string $source, bool[] $options = []) @method static InputObjectTypeDefinitionNode inputObjectTypeDefinition(Source|string $source, bool[] $options = []) @method static TypeExtensionNode typeExtension(Source|string $source, bool[] $options = []) @method static ScalarTypeExtensionNode scalarTypeExtension(Source|string $source, bool[] $options = []) @method static InterfaceTypeExtensionNode interfaceTypeExtension(Source|string $source, bool[] $options = []) @method static EnumTypeExtensionNode enumTypeExtension(Source|string $source, bool[] $options = []) @method static DirectiveDefinitionNode directiveDefinition(Source|string $source, bool[] $options = []) @method static DirectiveLocation directiveLocation(Source|string $source, bool[] $options = [])

Class Methods:

/**
 * Given a Sage source, parses it into a `Sage\Language\AST\DocumentNode`.
 * Throws `Sage\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.)
 *
 * allowLegacySDLEmptyFields: boolean
 *   If enabled, the parser will parse empty fields sets in the Schema
 *   Definition Language. Otherwise, the parser will follow the current
 *   specification.
 *
 *   This option is provided to ease adoption of the final SDL specification
 *   and will be removed in a future major release.
 *
 * allowLegacySDLImplementsInterfaces: boolean
 *   If enabled, the parser will parse implemented interfaces with no `&`
 *   character between each interface. Otherwise, the parser will follow the
 *   current specification.
 *
 *   This option is provided to ease adoption of the final SDL specification
 *   and will be removed in a future major release.
 *
 * 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.)
 *
 * @param Source|string $source
 * @param bool[]        $options
 *
 * @return DocumentNode
 *
 * @throws SyntaxError
 *
 * @api
 */
static function parse($source, array $options = [])
/**
 * Given a string containing a Sage value (ex. `[42]`), parse the AST for
 * that value.
 * Throws `Sage\Error\SyntaxError` if a syntax error is encountered.
 *
 * This is useful within tools that operate upon Sage Values directly and
 * in isolation of complete Sage documents.
 *
 * Consider providing the results to the utility function: `Sage\Utils\AST::valueFromAST()`.
 *
 * @param Source|string $source
 * @param bool[]        $options
 *
 * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode
 *
 * @api
 */
static function parseValue($source, array $options = [])
/**
 * Given a string containing a Sage Type (ex. `[Int!]`), parse the AST for
 * that type.
 * Throws `Sage\Error\SyntaxError` if a syntax error is encountered.
 *
 * This is useful within tools that operate upon Sage Types directly and
 * in isolation of complete Sage documents.
 *
 * Consider providing the results to the utility function: `Sage\Utils\AST::typeFromAST()`.
 *
 * @param Source|string $source
 * @param bool[]        $options
 *
 * @return ListTypeNode|NamedTypeNode|NonNullTypeNode
 *
 * @api
 */
static function parseType($source, array $options = [])

Sage\Language\Printer

Prints AST to string. Capable of printing Sage 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 = Sage\Language\Parser::parse($query);
$printed = Sage\Language\Printer::doPrint($ast);

Class Methods:

/**
 * Prints AST to string. Capable of printing Sage queries and Type definition language.
 *
 * @param Node $ast
 *
 * @return string
 *
 * @api
 */
static function doPrint($ast)

Sage\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)
 *
 * @param Node|ArrayObject|stdClass $root
 * @param callable[]                $visitor
 * @param mixed[]|null              $keyMap
 *
 * @return Node|mixed
 *
 * @throws Exception
 *
 * @api
 */
static function visit($root, $visitor, $keyMap = null)
/**
 * Returns marker for visitor break
 *
 * @return VisitorOperation
 *
 * @api
 */
static function stop()
/**
 * Returns marker for skipping current node
 *
 * @return VisitorOperation
 *
 * @api
 */
static function skipNode()
/**
 * Returns marker for removing a node
 *
 * @return VisitorOperation
 *
 * @api
 */
static function removeNode()

Sage\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";
const SCHEMA_EXTENSION = "SchemaExtension";

Sage\Executor\Executor

Implements the "Evaluating requests" section of the Sage 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`.
 *
 * @param mixed|null               $rootValue
 * @param mixed|null               $contextValue
 * @param mixed[]|ArrayAccess|null $variableValues
 * @param string|null              $operationName
 *
 * @return ExecutionResult|Promise
 *
 * @api
 */
static function execute(
    Sage\Type\Schema $schema,
    Sage\Language\AST\DocumentNode $documentNode,
    $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.
 *
 * @param mixed|null   $rootValue
 * @param mixed|null   $contextValue
 * @param mixed[]|null $variableValues
 * @param string|null  $operationName
 *
 * @return Promise
 *
 * @api
 */
static function promiseToExecute(
    Sage\Executor\Promise\PromiseAdapter $promiseAdapter,
    Sage\Type\Schema $schema,
    Sage\Language\AST\DocumentNode $documentNode,
    $rootValue = null,
    $contextValue = null,
    $variableValues = null,
    $operationName = null,
    callable $fieldResolver = null
)

Sage\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 mixed[]
 */
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 Error[]
 */
public $errors;

/**
 * User-defined serializable array of extensions included in serialized result.
 * Conforms to
 *
 * @api
 * @var mixed[]
 */
public $extensions;

Class Methods:

/**
 * Define custom error formatting (must conform to http://facebook.github.io/Sage/#sec-Errors)
 *
 * Expected signature is: function (Sage\Error\Error $error): array
 *
 * Default formatter is "Sage\Error\FormattedError::createFromException"
 *
 * Expected returned value must be an array:
 * array(
 *    'message' => 'errorMessage',
 *    // ... other keys
 * );
 *
 * @return self
 *
 * @api
 */
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);
 * }
 *
 * @return self
 *
 * @api
 */
function setErrorsHandler(callable $handler)
/**
 * Converts Sage 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 sum of flags from @see \Sage\Error\DebugFlag
 *
 * @return mixed[]
 *
 * @api
 */
function toArray(int $debug = "Sage\Error\DebugFlag::NONE"): array

Sage\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
 *
 * @param mixed $value
 *
 * @return bool
 *
 * @api
 */
function isThenable($value)
/**
 * Converts thenable of the underlying platform into Sage\Executor\Promise\Promise instance
 *
 * @param object $thenable
 *
 * @return Promise
 *
 * @api
 */
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 Sage\Executor\Promise\Promise.
 *
 * @return Promise
 *
 * @api
 */
function then(
    Sage\Executor\Promise\Promise $promise,
    callable $onFulfilled = null,
    callable $onRejected = null
)
/**
 * Creates a Promise
 *
 * Expected resolver signature:
 *     function(callable $resolve, callable $reject)
 *
 * @return Promise
 *
 * @api
 */
function create(callable $resolver)
/**
 * Creates a fulfilled Promise for a value if the value is not a promise.
 *
 * @param mixed $value
 *
 * @return Promise
 *
 * @api
 */
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.
 *
 * @param Throwable $reason
 *
 * @return Promise
 *
 * @api
 */
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.
 *
 * @param Promise[]|mixed[] $promisesOrValues Promises or values.
 *
 * @return Promise
 *
 * @api
 */
function all(array $promisesOrValues)

Sage\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 Sage specification will be used.

Each validation rule is an instance of Sage\Validator\Rules\ValidationRule which returns a visitor (see the Sage\Language\Visitor API).

Visitor methods are expected to return an instance of Sage\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.
 *
 * @param ValidationRule[]|null $rules
 *
 * @return Error[]
 *
 * @api
 */
static function validate(
    Sage\Type\Schema $schema,
    Sage\Language\AST\DocumentNode $ast,
    array $rules = null,
    Sage\Utils\TypeInfo $typeInfo = null
)
/**
 * Returns all global validation rules.
 *
 * @return ValidationRule[]
 *
 * @api
 */
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(Sage\Validator\Rules\QueryComplexity::class);
 *
 * @param string $name
 *
 * @return ValidationRule
 *
 * @api
 */
static function getRule($name)
/**
 * Add rule to list of global validation rules
 *
 * @api
 */
static function addRule(Sage\Validator\Rules\ValidationRule $rule)

Sage\Error\Error

Describes an Error found during the parse, validate, or execute phases of performing a Sage operation. In addition to a message and stack trace, it also includes information about the locations in a Sage 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_Sage = "Sage";
const CATEGORY_INTERNAL = "internal";

Class Methods:

/**
 * An array of locations within the source Sage document which correspond to this error.
 *
 * Each entry has information about `line` and `column` within source Sage 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.
 *
 * @return SourceLocation[]
 *
 * @api
 */
function getLocations()
/**
 * Returns an array describing the path from the root value to the field which produced this error.
 * Only included for execution errors.
 *
 * @return mixed[]|null
 *
 * @api
 */
function getPath()

Sage\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
 */
static function setWarningHandler(callable $warningHandler = null): void
/**
 * 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.
 *
 * @param bool|int $suppress
 *
 * @api
 */
static function suppress($suppress = true): void
/**
 * Re-enable previously suppressed warning by id
 *
 * Usage example:
 * Warning::suppress(Warning::WARNING_NOT_A_TYPE)
 *
 * When passing true - re-enables all warnings.
 *
 * @param bool|int $enable
 *
 * @api
 */
static function enable($enable = true): void

Sage\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.
 *
 * @return bool
 *
 * @api
 */
function isClientSafe()
/**
 * Returns string describing a category of the error.
 *
 * Value "Sage" is reserved for errors produced by query parsing or validation, do not use it.
 *
 * @return string
 *
 * @api
 */
function getCategory()

Sage\Error\DebugFlag

Collection of flags for error debugging.

Class Constants:

const NONE = 0;
const INCLUDE_DEBUG_MESSAGE = 1;
const INCLUDE_TRACE = 2;
const RETHROW_INTERNAL_EXCEPTIONS = 4;
const RETHROW_UNSAFE_EXCEPTIONS = 8;

Sage\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()`.
 *
 * @param string $msg
 *
 * @api
 */
static function setInternalErrorMessage($msg)
/**
 * Standard Sage error formatter. Converts any exception to array
 * conforming to Sage 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 \Sage\Error\DebugFlag constants.
 *
 * @param string $internalErrorMessage
 *
 * @return mixed[]
 *
 * @throws Throwable
 *
 * @api
 */
static function createFromException(
    Throwable $exception,
    int $debug = "Sage\Error\DebugFlag::NONE",
    $internalErrorMessage = null
): array
/**
 * Returns error trace as serializable array
 *
 * @param Throwable $error
 *
 * @return mixed[]
 *
 * @api
 */
static function toSafeTrace($error)

Sage\Server\StandardServer

Sage server compatible with both: express-Sage and Apollo Server. Usage Example:

$server = new StandardServer([
  'schema' => $mySchema
]);
$server->handleRequest();

Or using ServerConfig instance:

$settings = Sage\Server\ServerConfig::create()
    ->setSchema($mySchema)
    ->setContext($myContext);

$server = new Sage\Server\StandardServer($settings);
$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).
 *
 * @param Throwable $error
 * @param bool      $debug
 * @param bool      $exitWhenDone
 *
 * @api
 */
static function send500Error($error, $debug = false, $exitWhenDone = false)
/**
 * Creates new instance of a standard Sage HTTP server
 *
 * @param ServerConfig|mixed[] $settings
 *
 * @api
 */
function __construct($settings)
/**
 * 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)
 *
 * @param OperationParams|OperationParams[] $parsedBody
 * @param bool                              $exitWhenDone
 *
 * @api
 */
function handleRequest($parsedBody = null, $exitWhenDone = false)
/**
 * Executes Sage 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.
 *
 * @param OperationParams|OperationParams[] $parsedBody
 *
 * @return ExecutionResult|ExecutionResult[]|Promise
 *
 * @throws InvariantViolation
 *
 * @api
 */
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).
 *
 * @return ResponseInterface|Promise
 *
 * @api
 */
function processPsrRequest(
    Psr\Http\Message\RequestInterface $request,
    Psr\Http\Message\ResponseInterface $response,
    Psr\Http\Message\StreamInterface $writableBodyStream
)
/**
 * Executes Sage operation and returns execution result
 * (or promise when promise adapter is different from SyncPromiseAdapter)
 *
 * @return ExecutionResult|ExecutionResult[]|Promise
 *
 * @api
 */
function executePsrRequest(Psr\Http\Message\RequestInterface $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)
 *
 * @return Helper
 *
 * @api
 */
function getHelper()

Sage\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:

$settings = Sage\Server\ServerConfig::create()
    ->setSchema($mySchema)
    ->setContext($myContext);

$server = new Sage\Server\StandardServer($settings);

Class Methods:

/**
 * Converts an array of options to instance of ServerConfig
 * (or just returns empty config when array is not passed).
 *
 * @param mixed[] $settings
 *
 * @return ServerConfig
 *
 * @api
 */
static function create(array $settings = [])
/**
 * @return self
 *
 * @api
 */
function setSchema(Sage\Type\Schema $schema)
/**
 * @param mixed|callable $context
 *
 * @return self
 *
 * @api
 */
function setContext($context)
/**
 * @param mixed|callable $rootValue
 *
 * @return self
 *
 * @api
 */
function setRootValue($rootValue)
/**
 * Expects function(Throwable $e) : array
 *
 * @return self
 *
 * @api
 */
function setErrorFormatter(callable $errorFormatter)
/**
 * Expects function(array $errors, callable $formatter) : array
 *
 * @return self
 *
 * @api
 */
function setErrorsHandler(callable $handler)
/**
 * Set validation rules for this server.
 *
 * @param ValidationRule[]|callable|null $validationRules
 *
 * @return self
 *
 * @api
 */
function setValidationRules($validationRules)
/**
 * @return self
 *
 * @api
 */
function setFieldResolver(callable $fieldResolver)
/**
 * Expects function($queryId, OperationParams $params) : string|DocumentNode
 *
 * This function must return query string or valid DocumentNode.
 *
 * @return self
 *
 * @api
 */
function setPersistentQueryLoader(callable $persistentQueryLoader)
/**
 * Set response debug flags. @see \Sage\Error\DebugFlag class for a list of all available flags
 *
 * @api
 */
function setDebugFlag(int $debugFlag = "Sage\Error\DebugFlag::INCLUDE_DEBUG_MESSAGE"): self
/**
 * Allow batching queries (disabled by default)
 *
 * @api
 */
function setQueryBatching(bool $enableBatching): self
/**
 * @return self
 *
 * @api
 */
function setPromiseAdapter(Sage\Executor\Promise\PromiseAdapter $promiseAdapter)

Sage\Server\Helper

Contains functionality that could be re-used by various server implementations

Class Methods:

/**
 * Parses HTTP request using PHP globals and returns Sage 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.
 *
 * @return OperationParams|OperationParams[]
 *
 * @throws RequestError
 *
 * @api
 */
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)
 *
 * @param string  $method
 * @param mixed[] $bodyParams
 * @param mixed[] $queryParams
 *
 * @return OperationParams|OperationParams[]
 *
 * @throws RequestError
 *
 * @api
 */
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)
 *
 * @return array<int, RequestError>
 *
 * @api
 */
function validateOperationParams(Sage\Server\OperationParams $params)
/**
 * Executes Sage operation with given server configuration and returns execution result
 * (or promise when promise adapter is different from SyncPromiseAdapter)
 *
 * @return ExecutionResult|Promise
 *
 * @api
 */
function executeOperation(Sage\Server\ServerConfig $settings, Sage\Server\OperationParams $op)
/**
 * Executes batched Sage operations with shared promise queue
 * (thus, effectively batching deferreds|promises of all queries at once)
 *
 * @param OperationParams[] $operations
 *
 * @return ExecutionResult|ExecutionResult[]|Promise
 *
 * @api
 */
function executeBatch(Sage\Server\ServerConfig $settings, array $operations)
/**
 * Send response using standard PHP `header()` and `echo`.
 *
 * @param Promise|ExecutionResult|ExecutionResult[] $result
 * @param bool                                      $exitWhenDone
 *
 * @api
 */
function sendResponse($result, $exitWhenDone = false)
/**
 * Converts PSR-7 request to OperationParams[]
 *
 * @return OperationParams[]|OperationParams
 *
 * @throws RequestError
 *
 * @api
 */
function parsePsrRequest(Psr\Http\Message\RequestInterface $request)
/**
 * Converts query execution result to PSR-7 response
 *
 * @param Promise|ExecutionResult|ExecutionResult[] $result
 *
 * @return Promise|ResponseInterface
 *
 * @api
 */
function toPsrResponse(
    $result,
    Psr\Http\Message\ResponseInterface $response,
    Psr\Http\Message\StreamInterface $writableBodyStream
)

Sage\Server\OperationParams

Structure representing parsed HTTP parameters for Sage 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 mixed[]|null
 */
public $variables;

/**
 * @api
 * @var mixed[]|null
 */
public $extensions;

Class Methods:

/**
 * Creates an instance from given array
 *
 * @param mixed[] $params
 *
 * @api
 */
static function create(array $params, bool $readonly = false): Sage\Server\OperationParams
/**
 * @param string $key
 *
 * @return mixed
 *
 * @api
 */
function getOriginalInput($key)
/**
 * Indicates that operation is executed in read-only context
 * (e.g. via HTTP GET request)
 *
 * @return bool
 *
 * @api
 */
function isReadOnly()

Sage\Utils\BuildSchema

Build instance of Sage\Type\Schema out of type language definition (string or parsed AST) See section in docs for details.

Class Methods:

/**
 * A helper function to build a SageSchema directly from a source
 * document.
 *
 * @param DocumentNode|Source|string $source
 * @param bool[]                     $options
 *
 * @return Schema
 *
 * @api
 */
static function build($source, callable $typeConfigDecorator = null, array $options = [])
/**
 * This takes the ast of a schema document produced by the parse function in
 * Sage\Language\Parser.
 *
 * If no schema definition is provided, then it will look for types named Query
 * and Mutation.
 *
 * Given that AST it constructs a Sage\Type\Schema. The resulting schema
 * has no resolve methods, so execution will use default resolvers.
 *
 * Accepts options as a third argument:
 *
 *    - commentDescriptions:
 *        Provide true to use preceding comments as the description.
 *        This option is provided to ease adoption and will be removed in v16.
 *
 * @param bool[] $options
 *
 * @return Schema
 *
 * @throws Error
 *
 * @api
 */
static function buildAST(
    Sage\Language\AST\DocumentNode $ast,
    callable $typeConfigDecorator = null,
    array $options = []
)

Sage\Utils\AST

Various utilities dealing with AST

Class Methods:

/**
 * Convert representation of AST as an associative array to instance of Sage\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)
 *
 * @param mixed[] $node
 *
 * @api
 */
static function fromArray(array $node): Sage\Language\AST\Node
/**
 * Convert AST node to serializable array
 *
 * @return mixed[]
 *
 * @api
 */
static function toArray(Sage\Language\AST\Node $node): array
/**
 * Produces a Sage Value AST given a PHP value.
 *
 * Optionally, a Sage type may be provided, which will be used to
 * disambiguate between value primitives.
 *
 * | PHP Value     | Sage 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            |
 *
 * @param Type|mixed|null $value
 *
 * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode|null
 *
 * @api
 */
static function astFromValue($value, Sage\Type\Definition\InputType $type)
/**
 * Produces a PHP value given a Sage Value AST.
 *
 * A Sage type must be provided, which will be used to interpret different
 * Sage Value literals.
 *
 * Returns `null` when the value could not be validly coerced according to
 * the provided type.
 *
 * | Sage Value        | PHP Value     |
 * | -------------------- | ------------- |
 * | Input Object         | Assoc Array   |
 * | List                 | Array         |
 * | Boolean              | Boolean       |
 * | String               | String        |
 * | Int / Float          | Int / Float   |
 * | Enum Value           | Mixed         |
 * | Null Value           | null          |
 *
 * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $valueNode
 * @param mixed[]|null                                                                                                                             $variables
 *
 * @return mixed[]|stdClass|null
 *
 * @throws Exception
 *
 * @api
 */
static function valueFromAST(
    Sage\Language\AST\ValueNode $valueNode,
    Sage\Type\Definition\Type $type,
    array $variables = null
)
/**
 * Produces a PHP value given a Sage Value AST.
 *
 * Unlike `valueFromAST()`, no type is provided. The resulting PHP value
 * will reflect the provided Sage value AST.
 *
 * | Sage Value        | PHP Value     |
 * | -------------------- | ------------- |
 * | Input Object         | Assoc Array   |
 * | List                 | Array         |
 * | Boolean              | Boolean       |
 * | String               | String        |
 * | Int / Float          | Int / Float   |
 * | Enum                 | Mixed         |
 * | Null                 | null          |
 *
 * @param Node         $valueNode
 * @param mixed[]|null $variables
 *
 * @return mixed
 *
 * @throws Exception
 *
 * @api
 */
static function valueFromASTUntyped($valueNode, array $variables = null)
/**
 * Returns type definition for given AST Type node
 *
 * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
 *
 * @return Type|null
 *
 * @throws Exception
 *
 * @api
 */
static function typeFromAST(Sage\Type\Schema $schema, $inputTypeNode)
/**
 * Returns operation type ("query", "mutation" or "subscription") given a document and operation name
 *
 * @param string $operationName
 *
 * @return bool|string
 *
 * @api
 */
static function getOperation(Sage\Language\AST\DocumentNode $document, $operationName = null)

Sage\Utils\SchemaPrinter

Given an instance of Schema, prints it in Sage type language.

Class Methods:

/**
 * @param array<string, bool> $options
 *    Available options:
 *    - commentDescriptions:
 *        Provide true to use preceding comments as the description.
 *        This option is provided to ease adoption and will be removed in v16.
 *
 * @api
 */
static function doPrint(Sage\Type\Schema $schema, array $options = []): string
/**
 * @param array<string, bool> $options
 *
 * @api
 */
static function printIntrospectionSchema(Sage\Type\Schema $schema, array $options = []): string