Example #1
0
    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);
    }
Example #2
0
 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;
     }
 }
Example #3
0
 /**
  * @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;
 }
Example #5
0
 /**
  * @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!'));
 }
Example #6
0
 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);
 }
Example #7
0
 /**
  * @return Schema
  */
 public static function getDefaultSchema()
 {
     $FurColor = null;
     $Being = new InterfaceType(['name' => 'Being', 'fields' => ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]]]]);
     $Pet = new InterfaceType(['name' => 'Pet', 'fields' => ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]]]]);
     $Canine = new InterfaceType(['name' => 'Canine', 'fields' => function () {
         return ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]]];
     }]);
     $DogCommand = new EnumType(['name' => 'DogCommand', 'values' => ['SIT' => ['value' => 0], 'HEEL' => ['value' => 1], 'DOWN' => ['value' => 2]]]);
     $Dog = new ObjectType(['name' => 'Dog', 'isTypeOf' => function () {
         return true;
     }, 'fields' => ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]], 'nickname' => ['type' => Type::string()], 'barkVolume' => ['type' => Type::int()], 'barks' => ['type' => Type::boolean()], 'doesKnowCommand' => ['type' => Type::boolean(), 'args' => ['dogCommand' => ['type' => $DogCommand]]], 'isHousetrained' => ['type' => Type::boolean(), 'args' => ['atOtherHomes' => ['type' => Type::boolean(), 'defaultValue' => true]]], 'isAtLocation' => ['type' => Type::boolean(), 'args' => ['x' => ['type' => Type::int()], 'y' => ['type' => Type::int()]]]], 'interfaces' => [$Being, $Pet, $Canine]]);
     $Cat = new ObjectType(['name' => 'Cat', 'isTypeOf' => function () {
         return true;
     }, 'fields' => function () use(&$FurColor) {
         return ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]], 'nickname' => ['type' => Type::string()], 'meows' => ['type' => Type::boolean()], 'meowVolume' => ['type' => Type::int()], 'furColor' => $FurColor];
     }, 'interfaces' => [$Being, $Pet]]);
     $CatOrDog = new UnionType(['name' => 'CatOrDog', 'types' => [$Dog, $Cat], 'resolveType' => function ($value) {
         // not used for validation
         return null;
     }]);
     $Intelligent = new InterfaceType(['name' => 'Intelligent', 'fields' => ['iq' => ['type' => Type::int()]]]);
     $Human = null;
     $Human = new ObjectType(['name' => 'Human', 'isTypeOf' => function () {
         return true;
     }, 'interfaces' => [$Being, $Intelligent], 'fields' => function () use(&$Human, $Pet) {
         return ['name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]], 'pets' => ['type' => Type::listOf($Pet)], 'relatives' => ['type' => Type::listOf($Human)], 'iq' => ['type' => Type::int()]];
     }]);
     $Alien = new ObjectType(['name' => 'Alien', 'isTypeOf' => function () {
         return true;
     }, 'interfaces' => [$Being, $Intelligent], 'fields' => ['iq' => ['type' => Type::int()], 'name' => ['type' => Type::string(), 'args' => ['surname' => ['type' => Type::boolean()]]], 'numEyes' => ['type' => Type::int()]]]);
     $DogOrHuman = new UnionType(['name' => 'DogOrHuman', 'types' => [$Dog, $Human], 'resolveType' => function () {
         // not used for validation
         return null;
     }]);
     $HumanOrAlien = new UnionType(['name' => 'HumanOrAlien', 'types' => [$Human, $Alien], 'resolveType' => function () {
         // not used for validation
         return null;
     }]);
     $FurColor = new EnumType(['name' => 'FurColor', 'values' => ['BROWN' => ['value' => 0], 'BLACK' => ['value' => 1], 'TAN' => ['value' => 2], 'SPOTTED' => ['value' => 3]]]);
     $ComplexInput = new InputObjectType(['name' => 'ComplexInput', 'fields' => ['requiredField' => ['type' => Type::nonNull(Type::boolean())], 'intField' => ['type' => Type::int()], 'stringField' => ['type' => Type::string()], 'booleanField' => ['type' => Type::boolean()], 'stringListField' => ['type' => Type::listOf(Type::string())]]]);
     $ComplicatedArgs = new ObjectType(['name' => 'ComplicatedArgs', 'fields' => ['intArgField' => ['type' => Type::string(), 'args' => ['intArg' => ['type' => Type::int()]]], 'nonNullIntArgField' => ['type' => Type::string(), 'args' => ['nonNullIntArg' => ['type' => Type::nonNull(Type::int())]]], 'stringArgField' => ['type' => Type::string(), 'args' => ['stringArg' => ['type' => Type::string()]]], 'booleanArgField' => ['type' => Type::string(), 'args' => ['booleanArg' => ['type' => Type::boolean()]]], 'enumArgField' => ['type' => Type::string(), 'args' => ['enumArg' => ['type' => $FurColor]]], 'floatArgField' => ['type' => Type::string(), 'args' => ['floatArg' => ['type' => Type::float()]]], 'idArgField' => ['type' => Type::string(), 'args' => ['idArg' => ['type' => Type::id()]]], 'stringListArgField' => ['type' => Type::string(), 'args' => ['stringListArg' => ['type' => Type::listOf(Type::string())]]], 'complexArgField' => ['type' => Type::string(), 'args' => ['complexArg' => ['type' => $ComplexInput]]], 'multipleReqs' => ['type' => Type::string(), 'args' => ['req1' => ['type' => Type::nonNull(Type::int())], 'req2' => ['type' => Type::nonNull(Type::int())]]], 'multipleOpts' => ['type' => Type::string(), 'args' => ['opt1' => ['type' => Type::int(), 'defaultValue' => 0], 'opt2' => ['type' => Type::int(), 'defaultValue' => 0]]], 'multipleOptAndReq' => ['type' => Type::string(), 'args' => ['req1' => ['type' => Type::nonNull(Type::int())], 'req2' => ['type' => Type::nonNull(Type::int())], 'opt1' => ['type' => Type::int(), 'defaultValue' => 0], 'opt2' => ['type' => Type::int(), 'defaultValue' => 0]]]]]);
     $queryRoot = new ObjectType(['name' => 'QueryRoot', 'fields' => ['human' => ['args' => ['id' => ['type' => Type::id()]], 'type' => $Human], 'alien' => ['type' => $Alien], 'dog' => ['type' => $Dog], 'cat' => ['type' => $Cat], 'pet' => ['type' => $Pet], 'catOrDog' => ['type' => $CatOrDog], 'dogOrHuman' => ['type' => $DogOrHuman], 'humanOrAlien' => ['type' => $HumanOrAlien], 'complicatedArgs' => ['type' => $ComplicatedArgs]]]);
     $defaultSchema = new Schema(['query' => $queryRoot, 'directives' => array_merge(GraphQL::getInternalDirectives(), [new Directive(['name' => 'operationOnly', 'locations' => ['QUERY']])])]);
     return $defaultSchema;
 }
 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);
 }
Example #9
0
 /**
  * @param array $config
  */
 protected function init(array $config)
 {
     $config += ['query' => null, 'mutation' => null, 'subscription' => null, 'types' => [], 'directives' => [], 'validate' => true];
     if ($config['query'] instanceof DefinitionContainer) {
         $config['query'] = $config['query']->getDefinition();
     }
     if ($config['mutation'] instanceof DefinitionContainer) {
         $config['mutation'] = $config['mutation']->getDefinition();
     }
     if ($config['subscription'] instanceof DefinitionContainer) {
         $config['subscription'] = $config['subscription']->getDefinition();
     }
     Utils::invariant($config['query'] instanceof ObjectType, "Schema query must be Object Type but got: " . Utils::getVariableType($config['query']));
     $this->queryType = $config['query'];
     Utils::invariant(!$config['mutation'] || $config['mutation'] instanceof ObjectType, "Schema mutation must be Object Type if provided but got: " . Utils::getVariableType($config['mutation']));
     $this->mutationType = $config['mutation'];
     Utils::invariant(!$config['subscription'] || $config['subscription'] instanceof ObjectType, "Schema subscription must be Object Type if provided but got: " . Utils::getVariableType($config['subscription']));
     $this->subscriptionType = $config['subscription'];
     Utils::invariant(!$config['types'] || is_array($config['types']), "Schema types must be Array if provided but got: " . Utils::getVariableType($config['types']));
     Utils::invariant(!$config['directives'] || is_array($config['directives']) && Utils::every($config['directives'], function ($d) {
         return $d instanceof Directive;
     }), "Schema directives must be Directive[] if provided but got " . Utils::getVariableType($config['directives']));
     $this->directives = $config['directives'] ?: GraphQL::getInternalDirectives();
     // Build type map now to detect any errors within this schema.
     $initialTypes = [$config['query'], $config['mutation'], $config['subscription'], Introspection::_schema()];
     if (!empty($config['types'])) {
         $initialTypes = array_merge($initialTypes, $config['types']);
     }
     foreach ($initialTypes as $type) {
         $this->extractTypes($type);
     }
     $this->typeMap += Type::getInternalTypes();
     // Keep track of all implementations by interface name.
     $this->implementations = [];
     foreach ($this->typeMap as $typeName => $type) {
         if ($type instanceof ObjectType) {
             foreach ($type->getInterfaces() as $iface) {
                 $this->implementations[$iface->name][] = $type;
             }
         }
     }
 }
Example #10
0
 /**
  * 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;
 }
Example #11
0
 public function query($query, $params = [])
 {
     $schema = $this->schema();
     return GraphQLBase::execute($schema, $query, null, $params);
 }
Example #12
0
 /**
  * @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);
 }
Example #13
0
<?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);
Example #14
0
 /**
  * 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);
 }
 /**
  * Helper function to test a query and the expected response.
  */
 private function assertValidQuery($query, $expected)
 {
     $this->assertEquals(['data' => $expected], GraphQL::execute(StarWarsSchema::build(), $query));
 }
Example #16
0
    $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);
Example #17
0
 /**
  * Execute GraphQL query.
  *
  * @param  string $query
  * @param  array $variables
  * @param  mixed $rootValue
  * @return array
  */
 public function queryAndReturnResult($query, $context = null, $variables = [], $rootValue = null)
 {
     return GraphQL::executeAndReturnResult($this->buildSchema(), $query, $rootValue, $context, $variables);
 }
Example #18
0
* 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);
}]);
Example #19
0
 private function expectFailure($query, $vars, $err)
 {
     $result = GraphQL::executeAndReturnResult($this->schema, $query, null, null, $vars);
     $this->assertEquals(1, count($result->errors));
     if (is_array($err)) {
         $this->assertEquals($err['message'], $result->errors[0]->getMessage());
         $this->assertEquals($err['locations'], $result->errors[0]->getLocations());
     } else {
         $this->assertEquals($err, $result->errors[0]->getMessage());
     }
 }
Example #20
0
<?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);
Example #21
0
 /**
  * Execute GraphQL query.
  *
  * @param  string $query
  * @param  array $variables
  * @param  mixed $rootValue
  * @return array
  */
 public function queryAndReturnResult($query, $variables = [], $rootValue = null)
 {
     return GraphQLBase::executeAndReturnResult($this->schema(), $query, $rootValue, $variables);
 }
Example #22
0
 /**
  * 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));
 }
Example #23
0
 /**
  * @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));
 }
 /**
  * @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);
 }
Example #25
0
 public function queryAndReturnResult($query, $params = [])
 {
     $schema = $this->schema();
     $result = GraphQLBase::executeAndReturnResult($schema, $query, null, $params);
     return $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);
 }