Skip to content

Instantly share code, notes, and snippets.

@unclecheese
Last active February 19, 2021 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unclecheese/5459a3405fa94ff672b5883bd5d839e8 to your computer and use it in GitHub Desktop.
Save unclecheese/5459a3405fa94ff672b5883bd5d839e8 to your computer and use it in GitHub Desktop.
config:
modelConfig:
DataObject:
operations:
read:
plugins:
fluentLocale: true
SilverStripe\Core\Injector\Injector:
SilverStripe\GraphQL\Schema\Registry:
constructor:
fluent: MyProject\FluentQueryPlugin
<?php
namespace MyProject;
use SilverStripe\GraphQL\Schema\Field\Query;
use SilverStripe\GraphQL\Schema\Interfaces\QueryPlugin;
use SilverStripe\GraphQL\Schema\Interfaces\SchemaUpdater;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\Type\Enum;
class FluentQueryPlugin implements QueryPlugin, SchemaUpdater
{
public function getIdentifier(): string
{
return 'fluentLocale';
}
public static function updateSchema(Schema $schema): void
{
$locales = Fluent::get_locales();
$enum = Enum::create('FluentLocale', $locales, 'The locales available');
$schema->addEnum($enum);
}
public function apply(Query $query, Schema $schema, array $config = []): void
{
$queryType = $schema->getQueryType();
// Ensure that we only apply the Locale variable to root queries.
// Nested queries with their own locales is super edge-casey and weird.
if (!$queryType->getFieldByName($query->getName())) {
return;
}
$query->addArg('locale', 'FluentLocale!');
$query->addResolverMiddleware([static::class, 'setLocale']);
}
public static function setLocale($obj, $args, $context)
{
Fluent::set_locale($args['locale']);
return $obj;
}
}
query ReadPages($Locale: FluentLocale!) {
readPages(locale: $FluentLocale) {
nodes { title }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment