Skip to content
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
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ before_script:
- phpenv config-rm xdebug.ini || true

install:
- composer self-update --snapshot
- |
# Due to version incompatiblity with older Laravels we test, we remove it
composer remove --dev matt-allan/laravel-code-style --no-interaction --no-update
Expand Down
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.0.0...master)
--------------
### Added
- Add support for validation in field arguments [\#608 / crissi](https://github.com/rebing/graphql-laravel/pull/608)

2019-04-03, 5.0.0
-----------------
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);
Copy link
Collaborator

Choose a reason for hiding this comment

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

No the big prize question: how can we avoid resolving this if there aren't going to be any validations (they're optional after all)? Do you see any way to achieve this?

Seems like a catch-22: only when we run RulesInFields for which we already have to extract "fields and arguments" we can then know that we wouldn't have to run it 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I could probably write a function that checks if any arguments exists that would be less costly than the ResolveInfoFieldsAndArguments, and then only run ResolveInfoFieldsAndArguments if using selectfields and arguments... but not sure how much it will actually give.

Copy link
Collaborator

Choose a reason for hiding this comment

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

You're right, let's scrap that for now!


// 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
};
}

private 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
93 changes: 93 additions & 0 deletions src/Support/RulesInFields.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

namespace Rebing\GraphQL\Support;

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}";

//If field doesn't exist on definition we don't select it
if (! method_exists($parentType, 'getField')) {
continue;
}

$fieldObject = $parentType->getField($name);

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;
}
}
22 changes: 7 additions & 15 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);
$requestedFields = [
'args' => $queryArgs,
'fields' => $fieldsAndArguments,
];

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

private 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