I've setup a laravel 8 site, with php 7.4.
I prefer Twig frontend templating to Blade. I've installed twigbridge to enable Twig usage. Templating works great.
I've a backend app that serves up content via GraphQL.
I want to access/reference the backend content, via GraphQL query, in my Twig templates.
I've composer-installed 'PHP GraphQL Client' (https://github.com/mghoneimy/php-graphql-client) into the Laravel app.
It provides php GraphQL query access of the form:
$gql = (new Query('companies'))
->setSelectionSet(
[
'name',
'serialNumber'
]
);
To inject query results into my Laravel/Twig templates, I'm creating a TwigExtension
I'm piecing together the Extension from scattered online posts and not much documentation. So far I've got (not yet functional / WIP)
edit app/Twig/GraphqlQuery.php
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use GraphQL\Client;
use GraphQL\Exception\QueryError;
use GraphQL\Query;
class GraphqlQuery extends AbstractExtension {
protected $client;
protected $query;
public function __construct(
Client $client,
Query $query
) {
$this->client = $client;
$this->query = $query;
}
public function getFunctions(): array {
return [
new TwigFunction(
'gql_query',
[$this, 'gqlQuery']
),
];
}
public function gqlQuery($gql_data) {
$gql = (new Query('twig'))
->setVariables(
[
new Variable('name', 'String', true),
new Variable('limit', 'Int', false, 5)
]
)
->setArguments(
[
'name' => '$name',
'first' => '$limit'
]
)
->setSelectionSet(
[
'name',
'serialNumber'
]
);
try {
$results = $this->gqlClient->runQuery($gql);
}
catch (QueryError $exception) {
print_r($exception->getErrorDetails());
exit;
}
$results = $this->gqlClient->runQuery($gql, true); // array structure
return $results;
}
}
I want to get the array data for
->setVariables(
[
new Variable('name', 'String', true),
new Variable('limit', 'Int', false, 5)
]
)
->setArguments(
[
'name' => '$name',
'first' => '$limit'
]
)
->setSelectionSet(
[
'name',
'serialNumber'
]
);
passed in from my Twig Templates, ideally wrapped in
{#graphql
twig tags.
1st step -- What's the right way to refactor function gqlQuery()
to accept the array contents, properly encoded etc, from Twig Templates?