graphql.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. // Test this using following command
  3. // php -S localhost:8080 ./graphql.php
  4. require_once __DIR__ . '/../../vendor/autoload.php';
  5. use \GraphQL\Examples\Blog\Types;
  6. use \GraphQL\Examples\Blog\AppContext;
  7. use \GraphQL\Examples\Blog\Data\DataSource;
  8. use \GraphQL\Type\Schema;
  9. use \GraphQL\GraphQL;
  10. use \GraphQL\Error\FormattedError;
  11. use \GraphQL\Error\Debug;
  12. // Disable default PHP error reporting - we have better one for debug mode (see bellow)
  13. ini_set('display_errors', 0);
  14. $debug = false;
  15. if (!empty($_GET['debug'])) {
  16. set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
  17. throw new ErrorException($message, 0, $severity, $file, $line);
  18. });
  19. $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE;
  20. }
  21. try {
  22. // Initialize our fake data source
  23. DataSource::init();
  24. // Prepare context that will be available in all field resolvers (as 3rd argument):
  25. $appContext = new AppContext();
  26. $appContext->viewer = DataSource::findUser('1'); // simulated "currently logged-in user"
  27. $appContext->rootUrl = 'http://localhost:8080';
  28. $appContext->request = $_REQUEST;
  29. // Parse incoming query and variables
  30. if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
  31. $raw = file_get_contents('php://input') ?: '';
  32. $data = json_decode($raw, true) ?: [];
  33. } else {
  34. $data = $_REQUEST;
  35. }
  36. $data += ['query' => null, 'variables' => null];
  37. if (null === $data['query']) {
  38. $data['query'] = '{hello}';
  39. }
  40. // GraphQL schema to be passed to query executor:
  41. $schema = new Schema([
  42. 'query' => Types::query()
  43. ]);
  44. $result = GraphQL::executeQuery(
  45. $schema,
  46. $data['query'],
  47. null,
  48. $appContext,
  49. (array) $data['variables']
  50. );
  51. $output = $result->toArray($debug);
  52. $httpStatus = 200;
  53. } catch (\Exception $error) {
  54. $httpStatus = 500;
  55. $output['errors'] = [
  56. FormattedError::createFromException($error, $debug)
  57. ];
  58. }
  59. header('Content-Type: application/json', true, $httpStatus);
  60. echo json_encode($output);