-
-
Save thovan-bayard/80f37eb470bb5dffd8da10e8c88f7838 to your computer and use it in GitHub Desktop.
A minimalist GraphQL client for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $query = <<<'GRAPHQL' | |
| query GetUser($user: String!) { | |
| user (login: $user) { | |
| name | |
| repositoriesContributedTo { | |
| totalCount | |
| } | |
| } | |
| } | |
| GRAPHQL; | |
| graphql_query('https://api.github.com/graphql', $query, ['user' => 'dunglas'], 'my-oauth-token'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function graphql_query(string $endpoint, string $query, array $variables = [], ?string $token = null): array | |
| { | |
| $headers = ['Content-Type: application/json', 'User-Agent: Dunglas\'s minimal GraphQL client']; | |
| if (null !== $token) { | |
| $headers[] = "Authorization: bearer $token"; | |
| } | |
| if (false === $data = @file_get_contents($endpoint, false, stream_context_create([ | |
| 'http' => [ | |
| 'method' => 'POST', | |
| 'header' => $headers, | |
| 'content' => json_encode(['query' => $query, 'variables' => $variables]), | |
| ] | |
| ]))) { | |
| $error = error_get_last(); | |
| throw new \ErrorException($error['message'], $error['type']); | |
| } | |
| return json_decode($data, true); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment