public static execute ( |
||
$schema | ||
$requestString | ||
$rootValue | mixed | |
$operationName | string | null | |
return | GraphQL\Executor\Promise\Promise | array |
public function testFieldSelection() { $image = new ObjectType(['name' => 'Image', 'fields' => ['url' => ['type' => Type::string()], 'width' => ['type' => Type::int()], 'height' => ['type' => Type::int()]]]); $article = null; $author = new ObjectType(['name' => 'Author', 'fields' => function () use($image, &$article) { return ['id' => ['type' => Type::string()], 'name' => ['type' => Type::string()], 'pic' => ['type' => $image, 'args' => ['width' => ['type' => Type::int()], 'height' => ['type' => Type::int()]]], 'recentArticle' => ['type' => $article]]; }]); $reply = new ObjectType(['name' => 'Reply', 'fields' => ['author' => ['type' => $author], 'body' => ['type' => Type::string()]]]); $article = new ObjectType(['name' => 'Article', 'fields' => ['id' => ['type' => Type::string()], 'isPublished' => ['type' => Type::boolean()], 'author' => ['type' => $author], 'title' => ['type' => Type::string()], 'body' => ['type' => Type::string()], 'image' => ['type' => $image], 'replies' => ['type' => Type::listOf($reply)]]]); $doc = ' query Test { article { author { name pic { url width } } image { width height } replies { body author { id name pic { url width } recentArticle { id title body } } } } } '; $expectedDefaultSelection = ['author' => true, 'image' => true, 'replies' => true]; $expectedDeepSelection = ['author' => ['name' => true, 'pic' => ['url' => true, 'width' => true]], 'image' => ['width' => true, 'height' => true], 'replies' => ['body' => true, 'author' => ['id' => true, 'name' => true, 'pic' => ['url' => true, 'width' => true], 'recentArticle' => ['id' => true, 'title' => true, 'body' => true]]]]; $hasCalled = false; $actualDefaultSelection = null; $actualDeepSelection = null; $blogQuery = new ObjectType(['name' => 'Query', 'fields' => ['article' => ['type' => $article, 'resolve' => function ($value, $args, $context, ResolveInfo $info) use(&$hasCalled, &$actualDefaultSelection, &$actualDeepSelection) { $hasCalled = true; $actualDefaultSelection = $info->getFieldSelection(); $actualDeepSelection = $info->getFieldSelection(5); return null; }]]]); $schema = new Schema(['query' => $blogQuery]); $result = GraphQL::execute($schema, $doc); $this->assertTrue($hasCalled); $this->assertEquals(['data' => ['article' => null]], $result); $this->assertEquals($expectedDefaultSelection, $actualDefaultSelection); $this->assertEquals($expectedDeepSelection, $actualDeepSelection); }
public function extract($query, $params, $output = 'array', $ferretizer = true) { // output array as "array", default or json $result = GraphQL::execute(EditoraSchema::build(), $query, null, null, $params); if ($ferretizer) { $show_metadata = false; if ($params['metadata']) { $show_metadata = true; } $ferretizer_result = Ferretizer::Ferretize($result['data'], $show_metadata); if (!$ferretizer_result) { // en caso de error print_r($result); } else { // todo ok, preparamos el output $result = $ferretizer_result; } } if ($params['debug']) { $this->debug_messages = EditoraData::$debug_messages; } if ($output == 'json') { return json_encode($result); } else { // caso normal, output array return $result; } }
/** * @param string $requestString * @param mixed $rootValue * @param array|null $variableValues * @param string|null $operationName * @return ExecutionResult */ public function query($requestString, $rootValue = null, $variableValues = null, $operationName = null) { $schema = $this->getSchema(); $result = GraphQL::execute($schema, $requestString, $rootValue, $variableValues, $operationName); if (is_array($result) && isset($result['errors'])) { throw new QueryException($result['errors']); } return $result; }
/** * @param string $requestString * @return ExecutionResult */ public function query($requestString) { $schema = $this->getSchema(); $result = GraphQL::execute($schema, $requestString); if (is_array($result) && isset($result['errors'])) { throw new QueryException($result['errors']); } return $result; }
/** * @it uses provided resolve function */ public function testUsesProvidedResolveFunction() { $schema = $this->buildSchema(['type' => Type::string(), 'args' => ['aStr' => ['type' => Type::string()], 'aInt' => ['type' => Type::int()]], 'resolve' => function ($source, $args) { return json_encode([$source, $args]); }]); $this->assertEquals(['data' => ['test' => '[null,[]]']], GraphQL::execute($schema, '{ test }')); $this->assertEquals(['data' => ['test' => '["Source!",[]]']], GraphQL::execute($schema, '{ test }', 'Source!')); $this->assertEquals(['data' => ['test' => '["Source!",{"aStr":"String!"}]']], GraphQL::execute($schema, '{ test(aStr: "String!") }', 'Source!')); $this->assertEquals(['data' => ['test' => '["Source!",{"aStr":"String!","aInt":-123}]']], GraphQL::execute($schema, '{ test(aInt: -123, aStr: "String!") }', 'Source!')); }
public function __invoke() { $request = $this->getRequest(); $type = $request->query->get('type', 'query'); $graph_ql = $request->request->get('graphql'); $schema_query = Types::getType($type); if (!$schema_query) { throw new \Exception('不存在的查询'); } $schema = new Schema(array('query' => $schema_query)); $result = GraphQL::execute($schema, $graph_ql); return new JsonResponse($result); }
public function testMutatesTheDataSet() { $mutation = 'mutation AddBWingQuery($input: IntroduceShipInput!) { introduceShip(input: $input) { ship { id name } faction { name } clientMutationId } }'; $params = array('input' => array('shipName' => 'B-Wing', 'factionId' => '1', 'clientMutationId' => 'abcde')); $expected = array('introduceShip' => array('ship' => array('id' => 'U2hpcDo5', 'name' => 'B-Wing'), 'faction' => array('name' => 'Alliance to Restore the Republic'), 'clientMutationId' => 'abcde')); $result = GraphQL::execute(StarWarsSchema::getSchema(), $mutation, null, null, $params); $this->assertEquals(['data' => $expected], $result); }
public function testAllowsSimpleArrayAsValues() { $q = '{ first: simpleEnum(fromName: "ONE") second: simpleEnum(fromValue: "TWO") third: simpleEnum(fromValue: "WRONG") }'; $this->assertArraySubset(['data' => ['first' => 'ONE', 'second' => 'TWO', 'third' => null], 'errors' => [['message' => 'Expected a value of type "SimpleEnum" but received: WRONG', 'locations' => [['line' => 4, 'column' => 13]]]]], GraphQL::execute($this->schema, $q)); }
public function query($query, $params = []) { $schema = $this->schema(); return GraphQLBase::execute($schema, $query, null, $params); }
/** * Process GraphQL request. * * @param $requestString * @param array <string, string>|null $variableValues * @param string|null $operationName * * @return array */ public function execute($requestString = null, $variableValues = null, $operationName = null) { $this->mainRequestString = $requestString; try { $result = GraphQL::execute($this->schema, $requestString, null, $variableValues, $operationName); } catch (Exception $exception) { $result = ['errors' => [['message' => $exception->getMessage()]]]; } return $result; }
<?php use GraphQL\GraphQL; header('Content-Type: application/json'); if ($_SERVER['REQUEST_METHOD'] !== "POST") { echo json_encode(["error" => "This endpoint only accepts POST requests."]); exit; } if ($_SERVER['HTTP_X_CSRF_TOKEN'] && $_SERVER['HTTP_X_CSRF_TOKEN'] !== $_COOKIE['CSRF_TOKEN']) { echo json_encode(["error" => "CSRF Token is invalid."]); exit; } if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'application/json') { $rawBody = file_get_contents('php://input'); $data = json_decode($rawBody ?: '', true); } else { $data = $_POST; } $requestString = isset($data['query']) ? $data['query'] : null; $operationName = isset($data['operation']) ? $data['operation'] : null; $variableValues = isset($data['variables']) ? $data['variables'] : null; $schema = Pleio\SchemaBuilder::build(); $result = GraphQL::execute($schema, $requestString, null, $variableValues); echo json_encode($result);
/** * @it resolveType allows resolving with type name */ public function testResolveTypeAllowsResolvingWithTypeName() { $PetType = new InterfaceType(['name' => 'Pet', 'resolveType' => function ($obj) { if ($obj instanceof Dog) { return 'Dog'; } if ($obj instanceof Cat) { return 'Cat'; } return null; }, 'fields' => ['name' => ['type' => Type::string()]]]); $DogType = new ObjectType(['name' => 'Dog', 'interfaces' => [$PetType], 'fields' => ['name' => ['type' => Type::string()], 'woofs' => ['type' => Type::boolean()]]]); $CatType = new ObjectType(['name' => 'Cat', 'interfaces' => [$PetType], 'fields' => ['name' => ['type' => Type::string()], 'meows' => ['type' => Type::boolean()]]]); $schema = new Schema(['query' => new ObjectType(['name' => 'Query', 'fields' => ['pets' => ['type' => Type::listOf($PetType), 'resolve' => function () { return [new Dog('Odie', true), new Cat('Garfield', false)]; }]]]), 'types' => [$CatType, $DogType]]); $query = '{ pets { name ... on Dog { woofs } ... on Cat { meows } } }'; $result = GraphQL::execute($schema, $query); $this->assertEquals(['data' => ['pets' => [['name' => 'Odie', 'woofs' => true], ['name' => 'Garfield', 'meows' => false]]]], $result); }
/** * Helper function to test a query and the expected response. */ protected function assertValidQuery($query, $expected) { $result = GraphQL::execute($this->schema, $query); $this->assertEquals(['data' => $expected], $result); }
<?php // Test this using following command // php -S localhost:8080 ./graphql.php require_once '../../vendor/autoload.php'; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Schema; use GraphQL\GraphQL; try { $queryType = new ObjectType(['name' => 'Query', 'fields' => ['echo' => ['type' => Type::string(), 'args' => ['message' => ['type' => Type::string()]], 'resolve' => function ($root, $args) { return $root['prefix'] . $args['message']; }]]]); $mutationType = new ObjectType(['name' => 'Calc', 'fields' => ['sum' => ['type' => Type::int(), 'args' => ['x' => ['type' => Type::int()], 'y' => ['type' => Type::int()]], 'resolve' => function ($root, $args) { return $args['x'] + $args['y']; }]]]); $schema = new Schema(['query' => $queryType, 'mutation' => $mutationType]); $rawInput = file_get_contents('php://input'); $rootValue = ['prefix' => 'You said: ']; $result = GraphQL::execute($schema, $rawInput, $rootValue); } catch (\Exception $e) { $result = ['error' => ['message' => $e->getMessage()]]; } header('Content-Type: application/json; charset=UTF-8'); echo json_encode($result);
/** * @it exposes descriptions on enums */ public function testExposesDescriptionsOnEnums() { $QueryRoot = new ObjectType(['name' => 'QueryRoot', 'fields' => []]); $schema = new Schema(['query' => $QueryRoot]); $request = ' { typeKindType: __type(name: "__TypeKind") { name, description, enumValues { name, description } } } '; $expected = ['data' => ['typeKindType' => ['name' => '__TypeKind', 'description' => 'An enum describing what kind of type a given __Type is.', 'enumValues' => [['description' => 'Indicates this type is a scalar.', 'name' => 'SCALAR'], ['description' => 'Indicates this type is an object. ' . '`fields` and `interfaces` are valid fields.', 'name' => 'OBJECT'], ['description' => 'Indicates this type is an interface. ' . '`fields` and `possibleTypes` are valid fields.', 'name' => 'INTERFACE'], ['description' => 'Indicates this type is a union. ' . '`possibleTypes` is a valid field.', 'name' => 'UNION'], ['description' => 'Indicates this type is an enum. ' . '`enumValues` is a valid field.', 'name' => 'ENUM'], ['description' => 'Indicates this type is an input object. ' . '`inputFields` is a valid field.', 'name' => 'INPUT_OBJECT'], ['description' => 'Indicates this type is a list. ' . '`ofType` is a valid field.', 'name' => 'LIST'], ['description' => 'Indicates this type is a non-null. ' . '`ofType` is a valid field.', 'name' => 'NON_NULL']]]]]; $this->assertEquals($expected, GraphQL::execute($schema, $request)); }
/** * Helper function to test a query with params and the expected response. */ private function assertValidQueryWithParams($query, $params, $expected) { $this->assertEquals(['data' => $expected], GraphQL::execute(StarWarsSchema::build(), $query, null, null, $params)); }
* Author URI: http://www.thefold.co.nz/ * License: BSD */ namespace TheFold\GraphQLWP; require __DIR__ . '/autoload.php'; use GraphQL\GraphQL; use Exception; const ENDPOINT = '/graphql/'; new \TheFold\WordPress\Dispatch([ENDPOINT => function () { if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'application/json') { $rawBody = file_get_contents('php://input'); $data = json_decode($rawBody ?: '', true); } else { $data = $_POST; } $requestString = isset($data['query']) ? $data['query'] : null; $operationName = isset($data['operation']) ? $data['operation'] : null; $variableValues = isset($data['variables']) ? $data['variables'] : null; $Schema = apply_filters('graphql-wp/schema', null) ?: new Schema(); try { // Define your schema: $schema = $Schema->build(); $result = GraphQL::execute($schema, $requestString, null, $variableValues, $operationName); } catch (Exception $exception) { $result = ['errors' => [['message' => $exception->getMessage()]]]; } header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); echo json_encode($result); }]);
/** * Helper function to test a query and the expected response. */ private function assertValidQuery($query, $expected) { $this->assertEquals(['data' => $expected], GraphQL::execute(StarWarsSchema::build(), $query)); }
$appContext->rootUrl = 'http://localhost:8080'; $appContext->request = $_REQUEST; // Parse incoming query and variables if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) { $raw = file_get_contents('php://input') ?: ''; $data = json_decode($raw, true); } else { $data = $_REQUEST; } $data += ['query' => null, 'variables' => null]; if (null === $data['query']) { $data['query'] = '{hello}'; } // GraphQL schema to be passed to query executor: $schema = new Schema(['query' => Types::query()]); $result = GraphQL::execute($schema, $data['query'], null, $appContext, (array) $data['variables']); // Add reported PHP errors to result (if any) if (!empty($_GET['debug']) && !empty($phpErrors)) { $result['extensions']['phpErrors'] = array_map(['GraphQL\\Error\\FormattedError', 'createFromPHPError'], $phpErrors); } $httpStatus = 200; } catch (\Exception $error) { $httpStatus = 500; if (!empty($_GET['debug'])) { $result['extensions']['exception'] = FormattedError::createFromException($error); } else { $result['errors'] = [FormattedError::create('Unexpected Error')]; } } header('Content-Type: application/json', true, $httpStatus); echo json_encode($result);
/** * Helper function to test a query and the expected response. */ private function assertValidQuery($query, $expected) { $result = GraphQL::execute($this->getSchema(), $query); $this->assertEquals(['data' => $expected], $result); }
/** * @it gets execution info in resolver */ public function testGetsExecutionInfoInResolver() { $encounteredContext = null; $encounteredSchema = null; $encounteredRootValue = null; $PersonType2 = null; $NamedType2 = new InterfaceType(['name' => 'Named', 'fields' => ['name' => ['type' => Type::string()]], 'resolveType' => function ($obj, $context, ResolveInfo $info) use(&$encounteredContext, &$encounteredSchema, &$encounteredRootValue, &$PersonType2) { $encounteredContext = $context; $encounteredSchema = $info->schema; $encounteredRootValue = $info->rootValue; return $PersonType2; }]); $PersonType2 = new ObjectType(['name' => 'Person', 'interfaces' => [$NamedType2], 'fields' => ['name' => ['type' => Type::string()], 'friends' => ['type' => Type::listOf($NamedType2)]]]); $schema2 = new Schema(['query' => $PersonType2]); $john2 = new Person('John', [], [$this->liz]); $context = ['authToken' => '123abc']; $ast = Parser::parse('{ name, friends { name } }'); $this->assertEquals(['data' => ['name' => 'John', 'friends' => [['name' => 'Liz']]]], GraphQL::execute($schema2, $ast, $john2, $context)); $this->assertSame($context, $encounteredContext); $this->assertSame($schema2, $encounteredSchema); $this->assertSame($john2, $encounteredRootValue); }