Skip to content

Instantly share code, notes, and snippets.

@OssiPesonen
Created May 1, 2020 18:54
Show Gist options
  • Save OssiPesonen/4f29f83d66ad5ee0059856c8889b5a54 to your computer and use it in GitHub Desktop.
Save OssiPesonen/4f29f83d66ad5ee0059856c8889b5a54 to your computer and use it in GitHub Desktop.
PHP GraphQL Query Helper
<?php
require_once('GraphQLHelper.php');
$graphql = new GraphQLHelper();
$args = [
'search' => 'Monkey D. Luffy'
];
$query = <<<'GRAPHQL'
query searchCharacter($search: String) {
Character(search: $search) {
id
name {
first
last
full
}
image {
medium
}
description
}
}
GRAPHQL;
$result = $graphql->query($query, $args);
if (isset($result['code'])) {
http_response_code($result['code']);
}
echo json_encode($result);
<?php
require_once('vendor/autoload.php');
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
/**
* Helper class for GraphQL endpoint queries
*
* Class GraphQL
* @package Xerberus\System\Helpers
*/
class GraphQLHelper
{
/**
* @var string
*/
protected $endpoint;
public function __construct($endpoint = 'https://graphql.anilist.co')
{
$this->endpoint = $endpoint;
}
public function getEndpoint()
{
return $this->endpoint;
}
public function query($query, $vars = [])
{
$client = new Client();
$return = [];
try {
$response = $client->request('POST', $this->endpoint, [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'query' => $query,
'variables' => $vars
]),
]);
$return = json_decode($response->getBody()->getContents(), true);
} catch (ClientException $e) {
$return['code'] = $e->getCode();
$return['error'] = $e->getMessage();
}
return $return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment