Skip to content

Instantly share code, notes, and snippets.

@bummzack
Last active August 19, 2021 13:13
Show Gist options
  • Save bummzack/a060035fa075bcc38cc0023c8202770e to your computer and use it in GitHub Desktop.
Save bummzack/a060035fa075bcc38cc0023c8202770e to your computer and use it in GitHub Desktop.
Fluent query plugin for SilverStripe GraphQL
SilverStripe\Core\Injector\Injector:
SilverStripe\GraphQL\Schema\Registry\PluginRegistry:
constructor:
- Mutoco\GraphQL\FluentQueryPlugin
<?php
namespace Mutoco\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 'locale';
}
public static function updateSchema(Schema $schema, array $config = []): void
{
$locales = Locale::getLocales()->map('ID', 'Locale')->values();
$locales = array_combine($locales, $locales);
if (empty($locales)) {
$locales = ['de_CH' => 'de_CH'];
}
$enum = Enum::create('Locale', $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', 'Locale');
$query->addResolverMiddleware([static::class, 'setLocale']);
}
public static function setLocale($obj, $args, $context)
{
FluentState::singleton()->setLocale($args['locale'] ?? 'de_CH');
return $obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment