graphql.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. // Test this using following command
  3. // php -S localhost:8080 ./graphql.php &
  4. // curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
  5. // curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
  6. require_once __DIR__ . '/../../vendor/autoload.php';
  7. use GraphQL\Type\Definition\ObjectType;
  8. use GraphQL\Type\Definition\Type;
  9. use GraphQL\Type\Schema;
  10. use GraphQL\GraphQL;
  11. try {
  12. $queryType = new ObjectType([
  13. 'name' => 'Query',
  14. 'fields' => [
  15. 'echo' => [
  16. 'type' => Type::string(),
  17. 'args' => [
  18. 'message' => ['type' => Type::string()],
  19. ],
  20. 'resolve' => function ($root, $args) {
  21. return $root['prefix'] . $args['message'];
  22. }
  23. ],
  24. ],
  25. ]);
  26. $mutationType = new ObjectType([
  27. 'name' => 'Calc',
  28. 'fields' => [
  29. 'sum' => [
  30. 'type' => Type::int(),
  31. 'args' => [
  32. 'x' => ['type' => Type::int()],
  33. 'y' => ['type' => Type::int()],
  34. ],
  35. 'resolve' => function ($root, $args) {
  36. return $args['x'] + $args['y'];
  37. },
  38. ],
  39. ],
  40. ]);
  41. // See docs on schema options:
  42. // http://webonyx.github.io/graphql-php/type-system/schema/#configuration-options
  43. $schema = new Schema([
  44. 'query' => $queryType,
  45. 'mutation' => $mutationType,
  46. ]);
  47. $rawInput = file_get_contents('php://input');
  48. $input = json_decode($rawInput, true);
  49. $query = $input['query'];
  50. $variableValues = isset($input['variables']) ? $input['variables'] : null;
  51. $rootValue = ['prefix' => 'You said: '];
  52. $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
  53. $output = $result->toArray();
  54. } catch (\Exception $e) {
  55. $output = [
  56. 'error' => [
  57. 'message' => $e->getMessage()
  58. ]
  59. ];
  60. }
  61. header('Content-Type: application/json; charset=UTF-8');
  62. echo json_encode($output);