diff --git a/CHANGELOG.md b/CHANGELOG.md index e89faf71d..e1078834f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased - Add schema validation: Input Objects must not contain non-nullable circular references (#492) +- Added retrieving query complexity once query has been completed (#316) #### v0.13.5 - Fix coroutine executor when using with promise (#486) diff --git a/src/Validator/Rules/QueryComplexity.php b/src/Validator/Rules/QueryComplexity.php index fe469cd0a..972eff18f 100644 --- a/src/Validator/Rules/QueryComplexity.php +++ b/src/Validator/Rules/QueryComplexity.php @@ -41,6 +41,9 @@ class QueryComplexity extends QuerySecurityRule /** @var ValidationContext */ private $context; + /** @var int */ + private $complexity; + public function __construct($maxQueryComplexity) { $this->setMaxQueryComplexity($maxQueryComplexity); @@ -52,7 +55,7 @@ public function getVisitor(ValidationContext $context) $this->variableDefs = new ArrayObject(); $this->fieldNodeAndDefs = new ArrayObject(); - $complexity = 0; + $this->complexity = 0; return $this->invokeIfNeeded( $context, @@ -79,16 +82,16 @@ public function getVisitor(ValidationContext $context) return; } - $complexity = $this->fieldComplexity($operationDefinition, $complexity); + $this->complexity = $this->fieldComplexity($operationDefinition, $complexity); - if ($complexity <= $this->getMaxQueryComplexity()) { + if ($this->getQueryComplexity() <= $this->getMaxQueryComplexity()) { return; } $context->reportError( new Error(self::maxQueryComplexityErrorMessage( $this->getMaxQueryComplexity(), - $complexity + $this->getQueryComplexity() )) ); }, @@ -259,6 +262,11 @@ static function ($error) { return $args; } + public function getQueryComplexity() + { + return $this->complexity; + } + public function getMaxQueryComplexity() { return $this->maxQueryComplexity; diff --git a/tests/Validator/QueryComplexityTest.php b/tests/Validator/QueryComplexityTest.php index 998b751ff..24836d04b 100644 --- a/tests/Validator/QueryComplexityTest.php +++ b/tests/Validator/QueryComplexityTest.php @@ -25,6 +25,21 @@ public function testSimpleQueries() : void $this->assertDocumentValidators($query, 2, 3); } + public function testGetQueryComplexity() : void + { + $query = 'query MyQuery { human { firstName } }'; + + $rule = $this->getRule(5); + + DocumentValidator::validate( + QuerySecuritySchema::buildSchema(), + Parser::parse($query), + [$rule] + ); + + self::assertEquals(2, $rule->getQueryComplexity(), $query); + } + private function assertDocumentValidators($query, $queryComplexity, $startComplexity) { for ($maxComplexity = $startComplexity; $maxComplexity >= 0; --$maxComplexity) {