From bc4b990946cbaf1fca34b3dff0488b46d37af242 Mon Sep 17 00:00:00 2001 From: Vladimir Razuvaev Date: Sat, 3 Jun 2017 17:07:01 +0700 Subject: [PATCH] Do not run query complexity validation if there were other validation errors (as it will throw and mess up previous validation results), see #125 --- src/Validator/Rules/QueryComplexity.php | 12 ++++---- tests/Validator/QueryComplexityTest.php | 37 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/Validator/Rules/QueryComplexity.php b/src/Validator/Rules/QueryComplexity.php index 83e9cad..59ef41f 100644 --- a/src/Validator/Rules/QueryComplexity.php +++ b/src/Validator/Rules/QueryComplexity.php @@ -94,12 +94,14 @@ class QueryComplexity extends AbstractQuerySecurity }, NodeKind::OPERATION_DEFINITION => [ 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context, &$complexity) { - $complexity = $this->fieldComplexity($operationDefinition, $complexity); + if (empty($context->getErrors())) { + $complexity = $this->fieldComplexity($operationDefinition, $complexity); - if ($complexity > $this->getMaxQueryComplexity()) { - $context->reportError( - new Error($this->maxQueryComplexityErrorMessage($this->getMaxQueryComplexity(), $complexity)) - ); + if ($complexity > $this->getMaxQueryComplexity()) { + $context->reportError( + new Error($this->maxQueryComplexityErrorMessage($this->getMaxQueryComplexity(), $complexity)) + ); + } } }, ], diff --git a/tests/Validator/QueryComplexityTest.php b/tests/Validator/QueryComplexityTest.php index 0a75117..1dd3e37 100644 --- a/tests/Validator/QueryComplexityTest.php +++ b/tests/Validator/QueryComplexityTest.php @@ -1,7 +1,12 @@ assertTypeNameMetaFieldQuery(3); } + public function testSkippedWhenThereAreOtherValidationErrors() + { + $query = 'query MyQuery { human(name: INVALID_VALUE) { dogs {name} } }'; + + $reportedError = new Error("OtherValidatorError"); + $otherRule = function(ValidationContext $context) use ($reportedError) { + return [ + NodeKind::OPERATION_DEFINITION => [ + 'leave' => function() use ($context, $reportedError) { + $context->reportError($reportedError); + } + ] + ]; + }; + + $errors = DocumentValidator::validate( + QuerySecuritySchema::buildSchema(), + Parser::parse($query), + [$otherRule, $this->getRule(1)] + ); + + $this->assertEquals(1, count($errors)); + $this->assertSame($reportedError, $errors[0]); + + $this->setExpectedException('GraphQL\Error\Error'); + DocumentValidator::validate( + QuerySecuritySchema::buildSchema(), + Parser::parse($query), + [$this->getRule(1)] + ); + } + private function assertDocumentValidators($query, $queryComplexity, $startComplexity) { for ($maxComplexity = $startComplexity; $maxComplexity >= 0; --$maxComplexity) {