Skip to content

Commit

Permalink
Allow access to calculated query complexity
Browse files Browse the repository at this point in the history
This allows you to read the calculated query complexity.

A use case could be: add a rule that logs when queries are detected with a complexity higher than X.
  • Loading branch information
ruudk authored and spawnia committed Nov 14, 2023
1 parent a393385 commit 7a44e4e
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/Validator/Rules/QueryComplexity.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class QueryComplexity extends QuerySecurityRule
{
protected int $maxQueryComplexity;

protected int $queryComplexity;

/** @var array<string, mixed> */
protected array $rawVariableValues = [];

Expand All @@ -46,6 +48,7 @@ public function __construct(int $maxQueryComplexity)

public function getVisitor(QueryValidationContext $context): array
{
$this->queryComplexity = 0;
$this->context = $context;
$this->variableDefs = new NodeList([]);
$this->fieldNodeAndDefs = new \ArrayObject();
Expand Down Expand Up @@ -79,16 +82,16 @@ public function getVisitor(QueryValidationContext $context): array
return;
}

$complexity = $this->fieldComplexity($operationDefinition->selectionSet);
$this->queryComplexity = $this->fieldComplexity($operationDefinition->selectionSet);

if ($complexity <= $this->maxQueryComplexity) {
if ($this->queryComplexity <= $this->maxQueryComplexity) {
return;
}

$context->reportError(
new Error(static::maxQueryComplexityErrorMessage(
$this->maxQueryComplexity,
$complexity
$this->queryComplexity
))
);
},
Expand Down Expand Up @@ -263,6 +266,11 @@ public function getMaxQueryComplexity(): int
return $this->maxQueryComplexity;
}

public function getQueryComplexity(): int
{
return $this->queryComplexity;
}

/**
* Set max query complexity. If equal to 0 no check is done. Must be greater or equal to 0.
*
Expand Down

0 comments on commit 7a44e4e

Please sign in to comment.