Created
May 1, 2020 18:54
-
-
Save OssiPesonen/4f29f83d66ad5ee0059856c8889b5a54 to your computer and use it in GitHub Desktop.
PHP GraphQL Query Helper
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 | |
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); |
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 | |
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