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

redo validation for fields #630

Merged
merged 3 commits into from
Jun 8, 2020
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ CHANGELOG

[Next release](https://github.com/rebing/graphql-laravel/compare/5.1.1...master)
--------------
### Added
- Readded support for validation in field arguments (with breaking change fix) [\#630 / crissi](https://github.com/rebing/graphql-laravel/pull/630)

2019-04-23, 5.1.1
-----------------
Expand Down
15 changes: 0 additions & 15 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,6 @@ parameters:
count: 1
path: src/Support/Field.php

-
message: "#^Method Rebing\\\\GraphQL\\\\Support\\\\Field\\:\\:instanciateSelectFields\\(\\) has parameter \\$arguments with no value type specified in iterable type array\\.$#"
count: 1
path: src/Support/Field.php

-
message: "#^Method Rebing\\\\GraphQL\\\\Support\\\\Field\\:\\:aliasArgs\\(\\) has parameter \\$arguments with no value type specified in iterable type array\\.$#"
count: 1
Expand Down Expand Up @@ -306,16 +301,6 @@ parameters:
count: 1
path: src/Support/SelectFields.php

-
message: "#^Method Rebing\\\\GraphQL\\\\Support\\\\SelectFields\\:\\:getFieldSelection\\(\\) has parameter \\$args with no value type specified in iterable type array\\.$#"
count: 1
path: src/Support/SelectFields.php

-
message: "#^Method Rebing\\\\GraphQL\\\\Support\\\\SelectFields\\:\\:getFieldSelection\\(\\) return type has no value type specified in iterable type array\\.$#"
count: 1
path: src/Support/SelectFields.php

-
message: "#^Method Rebing\\\\GraphQL\\\\Support\\\\SelectFields\\:\\:getSelectableFieldsAndRelations\\(\\) has parameter \\$queryArgs with no value type specified in iterable type array\\.$#"
count: 1
Expand Down
50 changes: 44 additions & 6 deletions src/Support/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@
*/
abstract class Field
{
/**
* The depth the SelectField and ResolveInfoFieldsAndArguments classes traverse.
*
* @var int
*/
protected $depth = 5;

protected $attributes = [];

/**
Expand Down Expand Up @@ -86,6 +93,21 @@ public function getRules(array $arguments = []): array
return array_merge($argsRules, $rules);
}

/**
* @param array<string,mixed> $fieldsAndArgumentsSelection
* @return void
*/
public function validateFieldArguments(array $fieldsAndArgumentsSelection): void
{
$argsRules = (new RulesInFields($this->type(), $fieldsAndArgumentsSelection))->get();
if (count($argsRules)) {
$validator = $this->getValidator($fieldsAndArgumentsSelection, $argsRules);
if ($validator->fails()) {
throw new ValidationError('validation', $validator);
}
}
}

public function getValidator(array $args, array $rules): ValidatorContract
{
// allow our error messages to be customised
Expand Down Expand Up @@ -123,6 +145,11 @@ protected function getResolver(): ?Closure
}
}

$fieldsAndArguments = (new ResolveInfoFieldsAndArguments($arguments[3]))->getFieldsAndArgumentsSelection($this->depth);

// Validate arguments in fields
$this->validateFieldArguments($fieldsAndArguments);

$arguments[1] = $this->getArgs($arguments);

// Authorize
Expand All @@ -134,21 +161,21 @@ protected function getResolver(): ?Closure

$additionalParams = array_slice($method->getParameters(), 3);

$additionalArguments = array_map(function ($param) use ($arguments) {
$additionalArguments = array_map(function ($param) use ($arguments, $fieldsAndArguments) {
$className = null !== $param->getClass() ? $param->getClass()->getName() : null;

if (null === $className) {
throw new InvalidArgumentException("'{$param->name}' could not be injected");
}

if (Closure::class === $param->getType()->getName()) {
return function (int $depth = null) use ($arguments): SelectFields {
return $this->instanciateSelectFields($arguments, $depth);
return function (int $depth = null) use ($arguments, $fieldsAndArguments): SelectFields {
return $this->instanciateSelectFields($arguments, $fieldsAndArguments, $depth);
};
}

if (SelectFields::class === $className) {
return $this->instanciateSelectFields($arguments);
return $this->instanciateSelectFields($arguments, $fieldsAndArguments, null);
}

if (ResolveInfo::class === $className) {
Expand All @@ -165,11 +192,22 @@ protected function getResolver(): ?Closure
};
}

protected function instanciateSelectFields(array $arguments, int $depth = null): SelectFields
/**
* @param array<int,mixed> $arguments
* @param int $depth
* @param array<string,mixed> $fieldsAndArguments
* @return SelectFields
*/
private function instanciateSelectFields(array $arguments, array $fieldsAndArguments, int $depth = null): SelectFields
{
$ctx = $arguments[2] ?? null;

return new SelectFields($arguments[3], $this->type(), $arguments[1], $depth ?? 5, $ctx);
if ($depth !== null && $depth !== $this->depth) {
$fieldsAndArguments = (new ResolveInfoFieldsAndArguments($arguments[3]))
->getFieldsAndArgumentsSelection($depth);
}

return new SelectFields($this->type(), $arguments[1], $ctx, $fieldsAndArguments);
}

protected function aliasArgs(array $arguments): array
Expand Down
96 changes: 96 additions & 0 deletions src/Support/RulesInFields.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

namespace Rebing\GraphQL\Support;

use GraphQL\Error\InvariantViolation;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\WrappingType;

class RulesInFields
{
/**
* @var Type
*/
protected $parentType;

/**
* @var array<string,mixed>
*/
protected $fieldsAndArguments;

/**
* @param Type $parentType
* @param array<string,mixed> $fieldsAndArgumentsSelection
*/
public function __construct(Type $parentType, array $fieldsAndArgumentsSelection)
{
$this->parentType = $parentType instanceof WrappingType
? $parentType->getWrappedType(true)
: $parentType;
$this->fieldsAndArguments = $fieldsAndArgumentsSelection;
}

/**
* @return array<array>
*/
public function get(): array
{
return $this->getRules($this->fieldsAndArguments, null, $this->parentType);
}

/**
* @param array<string,mixed>|string|callable $rules
* @param array<string,mixed> $arguments
* @return array<string,mixed>|string
*/
protected function resolveRules($rules, array $arguments)
{
if (is_callable($rules)) {
return $rules($arguments);
}

return $rules;
}

/**
* Get rules from fields.
*
* @param array<string,mixed> $fields
* @param string|null $prefix
* @param Type $parentType
* @return array<string,mixed>
*/
protected function getRules(array $fields, ?string $prefix, Type $parentType): array
{
$rules = [];

foreach ($fields as $name => $field) {
$key = $prefix === null ? $name : "{$prefix}.{$name}";

try {
if (! method_exists($parentType, 'getField')) {
continue;
}
$fieldObject = $parentType->getField($name);
} catch (InvariantViolation $e) {
continue;
}

if (is_array($field['fields'])) {
$rules = $rules + $this->getRules($field['fields'], $key.'.fields', $fieldObject->getType());
}

$args = $fieldObject->config['args'] ?? [];

foreach ($args as $argName => $info) {
if (isset($info['rules'])) {
$rules[$key.'.args.'.$argName] = $this->resolveRules($info['rules'], $field['args']);
}
}
}

return $rules;
}
}
24 changes: 8 additions & 16 deletions src/Support/SelectFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Closure;
use GraphQL\Error\InvariantViolation;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type as GraphqlType;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Definition\WrappingType;
Expand All @@ -32,35 +31,28 @@ class SelectFields
const ALWAYS_RELATION_KEY = 'ALWAYS_RELATION_KEY';

/**
* @param ResolveInfo $info
* @param GraphqlType $parentType
* @param array $queryArgs Arguments given with the query/mutation
* @param int $depth The depth to walk the AST and introspect for nested relations
* @param mixed $ctx The GraphQL context; can be anything and is only passed through
* Can be created/overridden by \Rebing\GraphQL\GraphQLController::queryContext
* @param array<string,mixed> $fieldsAndArguments Field and argument tree
*/
public function __construct(ResolveInfo $info, GraphqlType $parentType, array $queryArgs, int $depth, $ctx)
public function __construct(GraphqlType $parentType, array $queryArgs, $ctx, array $fieldsAndArguments)
{
if ($parentType instanceof WrappingType) {
$parentType = $parentType->getWrappedType(true);
}

$requestedFields = $this->getFieldSelection($info, $queryArgs, $depth);
$fields = static::getSelectableFieldsAndRelations($queryArgs, $requestedFields, $parentType, null, true, $ctx);
$requestedFields = [
'args' => $queryArgs,
'fields' => $fieldsAndArguments,
];

$fields = self::getSelectableFieldsAndRelations($queryArgs, $requestedFields, $parentType, null, true, $ctx);
$this->select = $fields[0];
$this->relations = $fields[1];
}

protected function getFieldSelection(ResolveInfo $resolveInfo, array $args, int $depth): array
{
$resolveInfoFieldsAndArguments = new ResolveInfoFieldsAndArguments($resolveInfo);

return [
'args' => $args,
'fields' => $resolveInfoFieldsAndArguments->getFieldsAndArgumentsSelection($depth),
];
}

/**
* Retrieve the fields (top level) and relations that
* will be selected with the query.
Expand Down
11 changes: 10 additions & 1 deletion tests/Unit/FieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Rebing\GraphQL\Tests\Unit;

use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use PHPUnit\Framework\MockObject\MockObject;
use Rebing\GraphQL\Tests\Support\Objects\ExampleField;
use Rebing\GraphQL\Tests\TestCase;

Expand All @@ -15,6 +17,13 @@ protected function getFieldClass()
return ExampleField::class;
}

protected function resolveInfoMock(): MockObject
{
return $this->getMockBuilder(ResolveInfo::class)
->disableOriginalConstructor()
->getMock();
}

/**
* Test get attributes.
*/
Expand Down Expand Up @@ -47,7 +56,7 @@ public function testResolve(): void
->method('resolve');

$attributes = $field->getAttributes();
$attributes['resolve'](null, [], [], null);
$attributes['resolve'](null, [], [], $this->resolveInfoMock());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/GraphQLQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public function testQueryWithValidationError(): void
$this->assertArrayHasKey('errors', $result);
$this->assertArrayHasKey('extensions', $result['errors'][0]);
$this->assertArrayHasKey('validation', $result['errors'][0]['extensions']);
$this->assertTrue($result['errors'][0]['extensions']['validation']->has('index'));
$this->assertTrue($result['errors'][0]['extensions']['validation']->has('test_validation.args.index'));
}

/**
Expand Down
Loading