graphql-php/src/GraphQL.php

61 lines
2.1 KiB
PHP
Raw Normal View History

2015-07-15 20:05:46 +03:00
<?php
namespace GraphQL;
use GraphQL\Executor\ExecutionResult;
2015-07-15 20:05:46 +03:00
use GraphQL\Executor\Executor;
use GraphQL\Language\AST\Document;
2015-07-15 20:05:46 +03:00
use GraphQL\Language\Parser;
use GraphQL\Language\Source;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\QueryComplexity;
2015-07-15 20:05:46 +03:00
class GraphQL
{
/**
* @param Schema $schema
* @param $requestString
* @param mixed $rootValue
2015-07-15 20:05:46 +03:00
* @param array <string, string>|null $variableValues
* @param string|null $operationName
* @return array
*/
public static function execute(Schema $schema, $requestString, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null)
{
return self::executeAndReturnResult($schema, $requestString, $rootValue, $contextValue, $variableValues, $operationName)->toArray();
}
/**
* @param Schema $schema
* @param $requestString
* @param null $rootValue
* @param null $variableValues
* @param null $operationName
* @return array|ExecutionResult
*/
public static function executeAndReturnResult(Schema $schema, $requestString, $rootValue = null, $contextValue = null, $variableValues = null, $operationName = null)
2015-07-15 20:05:46 +03:00
{
try {
if ($requestString instanceof Document) {
$documentAST = $requestString;
} else {
$source = new Source($requestString ?: '', 'GraphQL request');
$documentAST = Parser::parse($source);
}
/** @var QueryComplexity $queryComplexity */
$queryComplexity = DocumentValidator::getRule('QueryComplexity');
$queryComplexity->setRawVariableValues($variableValues);
$validationErrors = DocumentValidator::validate($schema, $documentAST);
2015-07-15 20:05:46 +03:00
if (!empty($validationErrors)) {
return new ExecutionResult(null, $validationErrors);
2015-07-15 20:05:46 +03:00
} else {
return Executor::execute($schema, $documentAST, $rootValue, $contextValue, $variableValues, $operationName);
2015-07-15 20:05:46 +03:00
}
} catch (Error $e) {
return new ExecutionResult(null, [$e]);
2015-07-15 20:05:46 +03:00
}
}
}