graphql-php/examples/00-hello-world/graphql.php

70 lines
2.1 KiB
PHP
Raw Normal View History

2016-10-23 14:34:51 +03:00
<?php
// Test this using following command
2017-01-06 14:46:37 +03:00
// php -S localhost:8080 ./graphql.php &
2017-05-11 11:05:25 +03:00
// curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
// curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
2017-01-06 14:46:37 +03:00
require_once __DIR__ . '/../../vendor/autoload.php';
2016-10-23 14:34:51 +03:00
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
2017-08-19 22:31:11 +03:00
use GraphQL\Type\Schema;
2016-10-23 14:34:51 +03:00
use GraphQL\GraphQL;
try {
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'echo' => [
'type' => Type::string(),
'args' => [
'message' => ['type' => Type::string()],
],
'resolve' => function ($root, $args) {
2017-08-19 22:31:11 +03:00
return $root['prefix'] . $args['message'];
2016-10-23 14:34:51 +03:00
}
],
],
]);
$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'];
},
],
],
]);
2017-08-19 22:31:11 +03:00
// See docs on schema options:
// http://webonyx.github.io/graphql-php/type-system/schema/#configuration-options
2016-10-23 14:34:51 +03:00
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType,
]);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
2016-10-23 14:34:51 +03:00
$rootValue = ['prefix' => 'You said: '];
2017-08-19 22:31:11 +03:00
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
2016-10-23 14:34:51 +03:00
} catch (\Exception $e) {
2017-08-19 22:31:11 +03:00
$output = [
2016-10-23 14:34:51 +03:00
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json; charset=UTF-8');
2017-08-19 22:31:11 +03:00
echo json_encode($output);
2016-10-23 14:34:51 +03:00