Skip to content

Instantly share code, notes, and snippets.

@bummzack
Forked from unclecheese/FluentQueryPlugin.php
Last active February 19, 2021 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bummzack/cf71fa2e2311a8f5fd5d45f5e1e9f873 to your computer and use it in GitHub Desktop.
Save bummzack/cf71fa2e2311a8f5fd5d45f5e1e9f873 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\PluginRegistry:
constructor:
- MyProject\GraphQL\FluentQueryPlugin
<?php
namespace MyProject\GraphQL;
use SilverStripe\GraphQL\Schema\Field\ModelQuery;
use SilverStripe\GraphQL\Schema\Interfaces\ModelQueryPlugin;
use SilverStripe\GraphQL\Schema\Interfaces\SchemaUpdater;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\Type\Enum;
use TractorCow\Fluent\Model\Locale;
use TractorCow\Fluent\State\FluentState;
class FluentQueryPlugin implements ModelQueryPlugin, SchemaUpdater
{
public function getIdentifier(): string
{
return 'fluentLocale';
}
public static function updateSchema(Schema $schema): void
{
$locales = Locale::getLocales()->map('ID', 'Locale')->values();
$locales = array_combine($locales, $locales);
$enum = Enum::create('FluentLocale', $locales, 'The locales available');
$schema->addEnum($enum);
}
public function apply(ModelQuery $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)
{
FluentState::singleton()->setLocale($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