CustomValidationRule.php
2 months ago
DisableIntrospection.php
2 months ago
ExecutableDefinitions.php
2 months ago
FieldsOnCorrectType.php
2 months ago
FragmentsOnCompositeTypes.php
2 months ago
KnownArgumentNames.php
2 months ago
KnownArgumentNamesOnDirectives.php
2 months ago
KnownDirectives.php
2 months ago
KnownFragmentNames.php
2 months ago
KnownTypeNames.php
2 months ago
LoneAnonymousOperation.php
2 months ago
LoneSchemaDefinition.php
2 months ago
NoFragmentCycles.php
2 months ago
NoUndefinedVariables.php
2 months ago
NoUnusedFragments.php
2 months ago
NoUnusedVariables.php
2 months ago
OneOfInputObjectsRule.php
2 months ago
OverlappingFieldsCanBeMerged.php
2 months ago
PossibleFragmentSpreads.php
2 months ago
PossibleTypeExtensions.php
2 months ago
ProvidedRequiredArguments.php
2 months ago
ProvidedRequiredArgumentsOnDirectives.php
2 months ago
QueryComplexity.php
2 months ago
QueryDepth.php
2 months ago
QuerySecurityRule.php
2 months ago
ScalarLeafs.php
2 months ago
SingleFieldSubscription.php
2 months ago
UniqueArgumentDefinitionNames.php
2 months ago
UniqueArgumentNames.php
2 months ago
UniqueDirectiveNames.php
2 months ago
UniqueDirectivesPerLocation.php
2 months ago
UniqueEnumValueNames.php
2 months ago
UniqueFieldDefinitionNames.php
2 months ago
UniqueFragmentNames.php
2 months ago
UniqueInputFieldNames.php
2 months ago
UniqueOperationNames.php
2 months ago
UniqueOperationTypes.php
2 months ago
UniqueTypeNames.php
2 months ago
UniqueVariableNames.php
2 months ago
ValidationRule.php
2 months ago
ValuesOfCorrectType.php
2 months ago
VariablesAreInputTypes.php
2 months ago
VariablesInAllowedPosition.php
2 months ago
QueryComplexity.php
303 lines
| 1 | <?php declare(strict_types=1); |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Vendor\GraphQL\Validator\Rules; |
| 4 | |
| 5 | use Automattic\WooCommerce\Vendor\GraphQL\Error\Error; |
| 6 | use Automattic\WooCommerce\Vendor\GraphQL\Error\InvariantViolation; |
| 7 | use Automattic\WooCommerce\Vendor\GraphQL\Executor\Values; |
| 8 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\DocumentNode; |
| 9 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\FieldNode; |
| 10 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\FragmentSpreadNode; |
| 11 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\InlineFragmentNode; |
| 12 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\NodeKind; |
| 13 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\NodeList; |
| 14 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\OperationDefinitionNode; |
| 15 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\SelectionNode; |
| 16 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\SelectionSetNode; |
| 17 | use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\VariableDefinitionNode; |
| 18 | use Automattic\WooCommerce\Vendor\GraphQL\Language\Visitor; |
| 19 | use Automattic\WooCommerce\Vendor\GraphQL\Language\VisitorOperation; |
| 20 | use Automattic\WooCommerce\Vendor\GraphQL\Type\Definition\Directive; |
| 21 | use Automattic\WooCommerce\Vendor\GraphQL\Type\Definition\FieldDefinition; |
| 22 | use Automattic\WooCommerce\Vendor\GraphQL\Type\Introspection; |
| 23 | use Automattic\WooCommerce\Vendor\GraphQL\Validator\QueryValidationContext; |
| 24 | |
| 25 | /** |
| 26 | * @phpstan-import-type ASTAndDefs from QuerySecurityRule |
| 27 | */ |
| 28 | class QueryComplexity extends QuerySecurityRule |
| 29 | { |
| 30 | protected int $maxQueryComplexity; |
| 31 | |
| 32 | protected int $queryComplexity; |
| 33 | |
| 34 | /** @var array<string, mixed> */ |
| 35 | protected array $rawVariableValues = []; |
| 36 | |
| 37 | /** @var NodeList<VariableDefinitionNode> */ |
| 38 | protected NodeList $variableDefs; |
| 39 | |
| 40 | /** @phpstan-var ASTAndDefs */ |
| 41 | protected \ArrayObject $fieldNodeAndDefs; |
| 42 | |
| 43 | protected QueryValidationContext $context; |
| 44 | |
| 45 | /** @throws \InvalidArgumentException */ |
| 46 | public function __construct(int $maxQueryComplexity) |
| 47 | { |
| 48 | $this->setMaxQueryComplexity($maxQueryComplexity); |
| 49 | } |
| 50 | |
| 51 | public function getVisitor(QueryValidationContext $context): array |
| 52 | { |
| 53 | $this->queryComplexity = 0; |
| 54 | $this->context = $context; |
| 55 | $this->variableDefs = new NodeList([]); |
| 56 | $this->fieldNodeAndDefs = new \ArrayObject(); |
| 57 | |
| 58 | return $this->invokeIfNeeded( |
| 59 | $context, |
| 60 | [ |
| 61 | NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context): void { |
| 62 | $this->fieldNodeAndDefs = $this->collectFieldASTsAndDefs( |
| 63 | $context, |
| 64 | $context->getParentType(), |
| 65 | $selectionSet, |
| 66 | null, |
| 67 | $this->fieldNodeAndDefs |
| 68 | ); |
| 69 | }, |
| 70 | NodeKind::VARIABLE_DEFINITION => function ($def): VisitorOperation { |
| 71 | $this->variableDefs[] = $def; |
| 72 | |
| 73 | return Visitor::skipNode(); |
| 74 | }, |
| 75 | NodeKind::DOCUMENT => [ |
| 76 | 'leave' => function (DocumentNode $document) use ($context): void { |
| 77 | $errors = $context->getErrors(); |
| 78 | |
| 79 | if ($errors !== []) { |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | if ($this->maxQueryComplexity === self::DISABLED) { |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | foreach ($document->definitions as $definition) { |
| 88 | if (! $definition instanceof OperationDefinitionNode) { |
| 89 | continue; |
| 90 | } |
| 91 | |
| 92 | $this->queryComplexity = $this->fieldComplexity($definition->selectionSet); |
| 93 | |
| 94 | if ($this->queryComplexity > $this->maxQueryComplexity) { |
| 95 | $context->reportError( |
| 96 | new Error(static::maxQueryComplexityErrorMessage( |
| 97 | $this->maxQueryComplexity, |
| 98 | $this->queryComplexity |
| 99 | )) |
| 100 | ); |
| 101 | |
| 102 | return; |
| 103 | } |
| 104 | } |
| 105 | }, |
| 106 | ], |
| 107 | ] |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | /** @throws \Exception */ |
| 112 | protected function fieldComplexity(SelectionSetNode $selectionSet): int |
| 113 | { |
| 114 | $complexity = 0; |
| 115 | |
| 116 | foreach ($selectionSet->selections as $selection) { |
| 117 | $complexity += $this->nodeComplexity($selection); |
| 118 | } |
| 119 | |
| 120 | return $complexity; |
| 121 | } |
| 122 | |
| 123 | /** @throws \Exception */ |
| 124 | protected function nodeComplexity(SelectionNode $node): int |
| 125 | { |
| 126 | switch (true) { |
| 127 | case $node instanceof FieldNode: |
| 128 | // Exclude __schema field and all nested content from complexity calculation |
| 129 | if ($node->name->value === Introspection::SCHEMA_FIELD_NAME) { |
| 130 | return 0; |
| 131 | } |
| 132 | |
| 133 | if ($this->directiveExcludesField($node)) { |
| 134 | return 0; |
| 135 | } |
| 136 | |
| 137 | $childrenComplexity = isset($node->selectionSet) |
| 138 | ? $this->fieldComplexity($node->selectionSet) |
| 139 | : 0; |
| 140 | |
| 141 | $fieldDef = $this->fieldDefinition($node); |
| 142 | if ($fieldDef instanceof FieldDefinition && $fieldDef->complexityFn !== null) { |
| 143 | $fieldArguments = $this->buildFieldArguments($node); |
| 144 | |
| 145 | return ($fieldDef->complexityFn)($childrenComplexity, $fieldArguments); |
| 146 | } |
| 147 | |
| 148 | return $childrenComplexity + 1; |
| 149 | |
| 150 | case $node instanceof InlineFragmentNode: |
| 151 | return $this->fieldComplexity($node->selectionSet); |
| 152 | |
| 153 | case $node instanceof FragmentSpreadNode: |
| 154 | $fragment = $this->getFragment($node); |
| 155 | |
| 156 | if ($fragment !== null) { |
| 157 | return $this->fieldComplexity($fragment->selectionSet); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | return 0; |
| 162 | } |
| 163 | |
| 164 | protected function fieldDefinition(FieldNode $field): ?FieldDefinition |
| 165 | { |
| 166 | foreach ($this->fieldNodeAndDefs[$this->getFieldName($field)] ?? [] as [$node, $def]) { |
| 167 | if ($node === $field) { |
| 168 | return $def; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | return null; |
| 173 | } |
| 174 | |
| 175 | /** |
| 176 | * Will the given field be executed at all, given the directives placed upon it? |
| 177 | * |
| 178 | * @throws \Exception |
| 179 | * @throws \ReflectionException |
| 180 | * @throws InvariantViolation |
| 181 | */ |
| 182 | protected function directiveExcludesField(FieldNode $node): bool |
| 183 | { |
| 184 | foreach ($node->directives as $directiveNode) { |
| 185 | if ($directiveNode->name->value === Directive::DEPRECATED_NAME) { |
| 186 | return false; |
| 187 | } |
| 188 | |
| 189 | [$errors, $variableValues] = Values::getVariableValues( |
| 190 | $this->context->getSchema(), |
| 191 | $this->variableDefs, |
| 192 | $this->getRawVariableValues() |
| 193 | ); |
| 194 | if ($errors !== null && $errors !== []) { |
| 195 | throw new Error(implode("\n\n", array_map(static fn (Error $error): string => $error->getMessage(), $errors))); |
| 196 | } |
| 197 | |
| 198 | if ($directiveNode->name->value === Directive::INCLUDE_NAME) { |
| 199 | $includeArguments = Values::getArgumentValues( |
| 200 | Directive::includeDirective(), |
| 201 | $directiveNode, |
| 202 | $variableValues |
| 203 | ); |
| 204 | assert(is_bool($includeArguments['if']), 'ensured by query validation'); |
| 205 | |
| 206 | return ! $includeArguments['if']; |
| 207 | } |
| 208 | |
| 209 | if ($directiveNode->name->value === Directive::SKIP_NAME) { |
| 210 | $skipArguments = Values::getArgumentValues( |
| 211 | Directive::skipDirective(), |
| 212 | $directiveNode, |
| 213 | $variableValues |
| 214 | ); |
| 215 | assert(is_bool($skipArguments['if']), 'ensured by query validation'); |
| 216 | |
| 217 | return $skipArguments['if']; |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | return false; |
| 222 | } |
| 223 | |
| 224 | /** @return array<string, mixed> */ |
| 225 | public function getRawVariableValues(): array |
| 226 | { |
| 227 | return $this->rawVariableValues; |
| 228 | } |
| 229 | |
| 230 | /** @param array<string, mixed>|null $rawVariableValues */ |
| 231 | public function setRawVariableValues(?array $rawVariableValues = null): void |
| 232 | { |
| 233 | $this->rawVariableValues = $rawVariableValues ?? []; |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * @throws \Exception |
| 238 | * @throws Error |
| 239 | * |
| 240 | * @return array<string, mixed> |
| 241 | */ |
| 242 | protected function buildFieldArguments(FieldNode $node): array |
| 243 | { |
| 244 | $rawVariableValues = $this->getRawVariableValues(); |
| 245 | $fieldDef = $this->fieldDefinition($node); |
| 246 | |
| 247 | /** @var array<string, mixed> $args */ |
| 248 | $args = []; |
| 249 | |
| 250 | if ($fieldDef instanceof FieldDefinition) { |
| 251 | [$errors, $variableValues] = Values::getVariableValues( |
| 252 | $this->context->getSchema(), |
| 253 | $this->variableDefs, |
| 254 | $rawVariableValues |
| 255 | ); |
| 256 | |
| 257 | if (is_array($errors) && $errors !== []) { |
| 258 | throw new Error(implode("\n\n", array_map(static fn ($error) => $error->getMessage(), $errors))); |
| 259 | } |
| 260 | |
| 261 | $args = Values::getArgumentValues($fieldDef, $node, $variableValues); |
| 262 | } |
| 263 | |
| 264 | return $args; |
| 265 | } |
| 266 | |
| 267 | public function getMaxQueryComplexity(): int |
| 268 | { |
| 269 | return $this->maxQueryComplexity; |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Complexity of the first operation exceeding the defined limit, or, in case no operation |
| 274 | * exceeds the limit, complexity of the last defined operation. |
| 275 | */ |
| 276 | public function getQueryComplexity(): int |
| 277 | { |
| 278 | return $this->queryComplexity; |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Set max query complexity. If equal to 0 no check is done. Must be greater or equal to 0. |
| 283 | * |
| 284 | * @throws \InvalidArgumentException |
| 285 | */ |
| 286 | public function setMaxQueryComplexity(int $maxQueryComplexity): void |
| 287 | { |
| 288 | $this->checkIfGreaterOrEqualToZero('maxQueryComplexity', $maxQueryComplexity); |
| 289 | |
| 290 | $this->maxQueryComplexity = $maxQueryComplexity; |
| 291 | } |
| 292 | |
| 293 | public static function maxQueryComplexityErrorMessage(int $max, int $count): string |
| 294 | { |
| 295 | return "Max query complexity should be {$max} but got {$count}."; |
| 296 | } |
| 297 | |
| 298 | protected function isEnabled(): bool |
| 299 | { |
| 300 | return $this->maxQueryComplexity !== self::DISABLED; |
| 301 | } |
| 302 | } |
| 303 |