graphql.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\Server\StandardServer;
  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. // See docs on server options:
  48. // http://webonyx.github.io/graphql-php/executing-queries/#server-configuration-options
  49. $server = new StandardServer([
  50. 'schema' => $schema
  51. ]);
  52. $server->handleRequest();
  53. } catch (\Exception $e) {
  54. StandardServer::send500Error($e);
  55. }