|
1 | 1 | <?php
|
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
2 | 5 | // Test this using following command
|
3 | 6 | // php -S localhost:8080 ./graphql.php &
|
4 | 7 | // curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
|
5 | 8 | // curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
|
6 | 9 | require_once __DIR__ . '/../../vendor/autoload.php';
|
7 | 10 |
|
| 11 | +use GraphQL\GraphQL; |
8 | 12 | use GraphQL\Type\Definition\ObjectType;
|
9 | 13 | use GraphQL\Type\Definition\Type;
|
10 | 14 | use GraphQL\Type\Schema;
|
11 |
| -use GraphQL\GraphQL; |
12 | 15 |
|
13 | 16 | try {
|
14 | 17 | $queryType = new ObjectType([
|
|
19 | 22 | 'args' => [
|
20 | 23 | 'message' => ['type' => Type::string()],
|
21 | 24 | ],
|
22 |
| - 'resolve' => function ($rootValue, $args) { |
| 25 | + 'resolve' => static function ($rootValue, array $args): string { |
23 | 26 | return $rootValue['prefix'] . $args['message'];
|
24 |
| - } |
| 27 | + }, |
25 | 28 | ],
|
26 | 29 | ],
|
27 | 30 | ]);
|
|
35 | 38 | 'x' => ['type' => Type::int()],
|
36 | 39 | 'y' => ['type' => Type::int()],
|
37 | 40 | ],
|
38 |
| - 'resolve' => function ($calc, $args) { |
| 41 | + 'resolve' => static function ($calc, array $args): int { |
39 | 42 | return $args['x'] + $args['y'];
|
40 | 43 | },
|
41 | 44 | ],
|
|
49 | 52 | 'mutation' => $mutationType,
|
50 | 53 | ]);
|
51 | 54 |
|
52 |
| - $rawInput = file_get_contents('php://input'); |
53 |
| - $input = json_decode($rawInput, true); |
54 |
| - $query = $input['query']; |
55 |
| - $variableValues = isset($input['variables']) ? $input['variables'] : null; |
| 55 | + $rawInput = file_get_contents('php://input'); |
| 56 | + $input = json_decode($rawInput, true); |
| 57 | + $query = $input['query']; |
| 58 | + $variableValues = $input['variables'] ?? null; |
56 | 59 |
|
57 | 60 | $rootValue = ['prefix' => 'You said: '];
|
58 |
| - $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues); |
59 |
| - $output = $result->toArray(); |
60 |
| -} catch (\Exception $e) { |
| 61 | + $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues); |
| 62 | + $output = $result->toArray(); |
| 63 | +} catch (Throwable $e) { |
61 | 64 | $output = [
|
62 | 65 | 'error' => [
|
63 |
| - 'message' => $e->getMessage() |
64 |
| - ] |
| 66 | + 'message' => $e->getMessage(), |
| 67 | + ], |
65 | 68 | ];
|
66 | 69 | }
|
| 70 | + |
67 | 71 | header('Content-Type: application/json; charset=UTF-8');
|
68 | 72 | echo json_encode($output);
|
69 |
| - |
|
0 commit comments