Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NEW: custom filter fields #431

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions src/Schema/DataObject/Plugin/QueryFilter/QueryFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace SilverStripe\GraphQL\Schema\DataObject\Plugin\QueryFilter;

use GraphQL\Type\Definition\ResolveInfo;
use SilverStripe\GraphQL\Schema\DataObject\FieldAccessor;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\GraphQL\Schema\Type\Type;
Expand Down Expand Up @@ -36,6 +37,7 @@ public function getIdentifier(): string
}

/**
* @param array $config
* @return array
*/
protected function getResolver(array $config): array
Expand Down Expand Up @@ -71,9 +73,14 @@ protected function updateInputBuilder(NestedInputBuilder $builder): void
if (!$type instanceof ModelType) {
return false;
}

$dataObject = DataObject::singleton($type->getModel()->getSourceClass());
$fieldName = $field instanceof ModelField ? $field->getPropertyName() : $field->getName();
return FieldAccessor::singleton()->hasNativeField($dataObject, $fieldName);
$isNative = FieldAccessor::singleton()->hasNativeField($dataObject, $fieldName);

// If the field has its own resolver, then we'll allow anything it because the user is
// handling all the computation.
return $isNative || $field->getResolver();
});
}

Expand All @@ -85,8 +92,9 @@ public static function filter(array $context)
{
$fieldName = $context['fieldName'];
$rootType = $context['rootType'];
$resolvers = $context['resolvers'] ?? [];

return function (?Filterable $list, array $args, array $context) use ($fieldName, $rootType) {
return function (?Filterable $list, array $args, array $context, ResolveInfo $info) use ($fieldName, $rootType, $resolvers) {
if ($list === null) {
return null;
}
Expand All @@ -109,16 +117,29 @@ public static function filter(array $context)
$fieldParts = explode('.', $path);
$filterID = array_pop($fieldParts);
$fieldPath = implode('.', $fieldParts);

$filter = $registry->getFilterByIdentifier($filterID);
Schema::invariant(
$filter,
'No registered filters match the identifier "%s". Did you register it with %s?',
$filterID,
FilterRegistryInterface::class
);
if (isset($resolvers[$fieldPath])) {
$newContext = $context;
$newContext['filterComparator'] = $filterID;
$newContext['filterValue'] = $value;
$list = call_user_func_array($resolvers[$fieldPath], [$list, $args, $newContext, $info]);
continue;
}
$normalised = $schemaContext->mapPath($rootType, $fieldPath);
Schema::invariant(
$normalised,
'Plugin %s could not map path %s on %s',
'Plugin %s could not map path %s on %s. If this is a custom filter field, make sure you included
a resolver.',
static::IDENTIFIER,
$fieldPath,
$rootType
);
$filter = $registry->getFilterByIdentifier($filterID);
if ($filter) {
$list = $filter->apply($list, $normalised, $value);
}
Expand Down
20 changes: 14 additions & 6 deletions src/Schema/Plugin/AbstractQueryFilterPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace SilverStripe\GraphQL\Schema\Plugin;

use Psr\Container\NotFoundExceptionInterface;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
Expand All @@ -18,7 +19,6 @@
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\Services\NestedInputBuilder;
use SilverStripe\GraphQL\Schema\Type\InputType;
use SilverStripe\GraphQL\Schema\Type\ModelType;
use SilverStripe\GraphQL\Schema\Type\Type;

/**
Expand Down Expand Up @@ -47,6 +47,7 @@ protected function getFieldName(): string
* Creates all the { eq: String, lte: String }, { eq: Int, lte: Int } etc types for comparisons
* @param Schema $schema
* @throws SchemaBuilderException
* @throws NotFoundExceptionInterface
*/
public static function updateSchema(Schema $schema): void
{
Expand Down Expand Up @@ -82,7 +83,8 @@ public static function updateSchema(Schema $schema): void
public function apply(ModelQuery $query, Schema $schema, array $config = []): void
{
$fields = $config['fields'] ?? Schema::ALL;
$builder = NestedInputBuilder::create($query, $schema, $fields);
$resolvers = $config['resolve'] ?? [];
$builder = NestedInputBuilder::create($query, $schema, $fields, $resolvers);
$this->updateInputBuilder($builder);
$builder->populateSchema();
if (!$builder->getRootType()) {
Expand All @@ -91,12 +93,18 @@ public function apply(ModelQuery $query, Schema $schema, array $config = []): vo
$query->addArg($this->getFieldName(), $builder->getRootType()->getName());
$canonicalType = $schema->getCanonicalType($query->getNamedType());
$rootType = $canonicalType ? $canonicalType->getName() : $query->getNamedType();
$resolvers = $builder->getResolvers();
$context = [
'fieldName' => $this->getFieldName(),
'rootType' => $rootType,
];
if (!empty($resolvers)) {
$context['resolvers'] = $resolvers;
}

$query->addResolverAfterware(
$this->getResolver($config),
[
'fieldName' => $this->getFieldName(),
'rootType' => $rootType,
]
$context
);
}

Expand Down
91 changes: 88 additions & 3 deletions src/Schema/Services/NestedInputBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,20 @@ class NestedInputBuilder
*/
private $rootType;

/**
* @var array
*/
private $resolveConfig;

/**
* NestedInputBuilder constructor.
* @param Field $root
* @param Schema $schema
* @param string $fields
* @param array $resolveConfig
* @throws SchemaBuilderException
*/
public function __construct(Field $root, Schema $schema, $fields = Schema::ALL)
public function __construct(Field $root, Schema $schema, $fields = Schema::ALL, $resolveConfig = [])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add param types e.g. array $resolveConfig = []

{
$this->schema = $schema;
$this->root = $root;
Expand All @@ -87,6 +94,7 @@ public function __construct(Field $root, Schema $schema, $fields = Schema::ALL)
);

$this->fields = $fields;
$this->setResolveConfig($resolveConfig);
}

/**
Expand All @@ -106,6 +114,9 @@ public function populateSchema()

if ($this->fields === Schema::ALL) {
$this->fields = $this->buildAllFieldsConfig($type);
} elseif (isset($this->fields[Schema::ALL]) && $this->fields[Schema::ALL]) {
unset($this->fields[Schema::ALL]);
$this->fields = array_merge($this->fields, $this->buildAllFieldsConfig($type));
}
$this->addInputTypesToSchema($type, $this->fields, null, null, $prefix);
$rootTypeName = $prefix . $this->getTypeName($type);
Expand Down Expand Up @@ -181,6 +192,9 @@ protected function addInputTypesToSchema(
$inputType = InputType::create($inputTypeName);
}
foreach ($fields as $fieldName => $data) {
if ($fieldName === Schema::ALL) {
$this->buildAllFieldsConfig($type);
}
if ($data === false) {
continue;
}
Expand All @@ -197,13 +211,25 @@ protected function addInputTypesToSchema(
if (!$fieldObj && $type instanceof ModelType) {
$fieldObj = $type->getModel()->getField($fieldName);
}

$customResolver = $this->getResolver($fieldName);
$customType = $this->getResolveType($fieldName);

Schema::invariant(
$fieldObj,
'Could not find field "%s" on type "%s"',
$fieldObj || ($customResolver && $customType),
'Could not find field "%s" on type "%s". If it is a custom filter field, you will need to provide a
resolver function in the "resolver" config for that field along with an explicit type.',
$fieldName,
$type->getName()
);

if (!$fieldObj) {
$fieldObj = Field::create($fieldName, [
'type' => $customType,
'resolver' => $customResolver,
]);
}

if (!$this->shouldAddField($type, $fieldObj)) {
continue;
}
Expand Down Expand Up @@ -281,6 +307,65 @@ public function getRootType(): ?InputType
return $this->rootType;
}

/**
* @param array $config
* @return $this
* @throws SchemaBuilderException
*/
public function setResolveConfig(array $config): self
{
foreach ($config as $fieldName => $data) {
Schema::invariant(
is_string($fieldName) && isset($data['resolver']) && isset($data['type']),
'"resolve" setting for nested input must be a map of field name keys to an array that contains
a "resolver" field and "type" key'
);
}

$this->resolveConfig = $config;

return $this;
}

/**
* @return array
*/
public function getResolveConfig(): array
{
return $this->resolveConfig;
}

/**
* @param string $name
* @return string|array|null
*/
public function getResolver(string $name)
{
return $this->resolveConfig[$name]['resolver'] ?? null;
}

/**
* @param string $name
* @return string|null
*/
public function getResolveType(string $name): ?string
{
return $this->resolveConfig[$name]['type'] ?? null;
}

/**
* @return array
*/
public function getResolvers(): array
{
$resolvers = [];
foreach ($this->resolveConfig as $fieldName => $config) {
$resolvers[$fieldName] = $config['resolver'];
}

return $resolvers;
}

/**
* Public API that can be used by a resolver to flatten the input argument into
* dot.separated.paths that can be normalised
Expand Down
24 changes: 20 additions & 4 deletions src/Schema/Storage/CodeGenerationStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ class CodeGenerationStore implements SchemaStorageInterface
*/
private $obfuscator;

/**
* @var bool
*/
private $verbose = true;

/**
* @param string $name
* @param CacheInterface $cache
Expand Down Expand Up @@ -277,21 +282,21 @@ public function persistSchema(StorableSchema $schema): void
$logger->info(sprintf('Types built: %s', count($built)));
$snapshot = array_slice($built, 0, 10);
foreach ($snapshot as $type) {
$logger->output('*' . $type);
$logger->info('*' . $type);
}
$diff = count($built) - count($snapshot);
if ($diff > 0) {
$logger->output(sprintf('(... and %s more)', $diff));
$logger->info(sprintf('(... and %s more)', $diff));
}

$logger->info(sprintf('Types deleted: %s', count($deleted)));
$snapshot = array_slice($deleted, 0, 10);
foreach ($snapshot as $type) {
$logger->output('*' . $type);
$logger->info('*' . $type);
}
$diff = count($deleted) - count($snapshot);
if ($diff > 0) {
$logger->output(sprintf('(... and %s more)', $diff));
$logger->info(sprintf('(... and %s more)', $diff));
}
}

Expand Down Expand Up @@ -427,6 +432,17 @@ public function setObfuscator(NameObfuscator $obfuscator): CodeGenerationStore
return $this;
}

/**
* If true, s
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this is missing some text

* @param bool $bool
* @return $this
*/
public function setVerbose(bool $bool): self
{
$this->verbose = $bool;

return $this;
}

/**
* @return string
Expand Down
Loading