QueryInfoExtractor.php
<?php
declare(strict_types=1);
namespace Automattic\WooCommerce\Api\Infrastructure;
use Automattic\WooCommerce\Api\Infrastructure\Schema\ResolveInfo;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\ArgumentNode;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\FieldNode;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\FragmentDefinitionNode;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\FragmentSpreadNode;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\InlineFragmentNode;
use Automattic\WooCommerce\Vendor\GraphQL\Language\AST\SelectionSetNode;
/**
* Extracts a unified query info tree from a GraphQL ResolveInfo.
*
* The resulting array captures the full query structure: fields, arguments,
* sub-selections, inline fragments, and named fragment spreads.
*
* Structure rules:
* - Leaf field (no args, no sub-selection) => true
* - Field with sub-selections => nested associative array
* - Field arguments => '__args' reserved key
* - Inline fragments with a type condition => '...TypeName' prefix key
* - Inline fragments without a type condition and named fragment spreads =>
* expanded inline (merged into the parent as siblings of the other
* selections), matching how GraphQL evaluates them
* - Top-level query args included via '__args'
*/
class QueryInfoExtractor {
/**
* Extract query info from a resolver's ResolveInfo and top-level args.
*
* @param ResolveInfo $info The GraphQL resolve info.
* @param array $args The top-level query arguments.
* @return array The unified query info tree.
*/
public static function extract_from_info( ResolveInfo $info, array $args ): array {
$result = self::extract( $info->fieldNodes[0]->selectionSet ?? null, $info->variableValues, $info->fragments );
if ( ! empty( $args ) ) {
$result['__args'] = $args;
}
return $result;
}
/**
* Recursively extract query info from a selection set.
*
* @internal Recursive helper exposed only for internal callers and tests;
* the engine-decoupled entry point for autogenerated resolvers
* is {@see self::extract_from_info()}.
*
* @param ?SelectionSetNode $selection_set The selection set to process.
* @param array $variable_values Variable values for resolving arguments.
* @param array<string, FragmentDefinitionNode> $fragments Named fragment definitions from the document.
* @return array The query info tree for the selection set.
*/
public static function extract( ?SelectionSetNode $selection_set, array $variable_values, array $fragments = array() ): array {
$expanded_fragments = array();
return self::extract_selection_set( $selection_set, $variable_values, $fragments, $expanded_fragments );
}
/**
* Recursive worker behind {@see self::extract()}.
*
* Named fragments are expanded once per extract() call and the result is
* reused for every further spread, so the work stays proportional to the
* size of the document. This runs after validation, whose limits don't
* bound how often a fragment is spread.
*
* @param ?SelectionSetNode $selection_set The selection set to process.
* @param array $variable_values Variable values for resolving arguments.
* @param array<string, FragmentDefinitionNode> $fragments Named fragment definitions from the document.
* @param array<string, array> $expanded_fragments Memoized expansions, keyed by fragment name. Passed by reference so the whole walk shares one cache.
* @return array The query info tree for the selection set.
*/
private static function extract_selection_set( ?SelectionSetNode $selection_set, array $variable_values, array $fragments, array &$expanded_fragments ): array {
if ( null === $selection_set ) {
return array();
}
$result = array();
foreach ( $selection_set->selections as $selection ) {
if ( $selection instanceof FieldNode ) {
$field_name = $selection->name->value;
$result[ $field_name ] = self::build_field_entry( $selection, $variable_values, $fragments, $expanded_fragments );
} elseif ( $selection instanceof InlineFragmentNode ) {
$sub = self::extract_selection_set( $selection->selectionSet, $variable_values, $fragments, $expanded_fragments );
if ( null === $selection->typeCondition ) {
// No `on Type` clause (e.g. `... @include(if: $flag) { ... }`):
// the fragment applies to the parent type, so merge it like
// a named fragment spread.
$result = self::merge_selections( $result, $sub );
} else {
$result[ '...' . $selection->typeCondition->name->value ] = $sub;
}
} elseif ( $selection instanceof FragmentSpreadNode ) {
// Expand named fragment spreads inline: their fields become
// siblings of the other selections, matching how GraphQL
// evaluates them. Consumers of _query_info (mappers that
// check array_key_exists for specific fields) see them the
// same as if the fragment had been written inline. Use a
// recursive merge so overlapping selections are unioned
// rather than replaced — `array_merge` would drop the
// existing sub-selection under the same field name.
$spread = self::expand_fragment( $selection->name->value, $variable_values, $fragments, $expanded_fragments );
if ( null === $spread ) {
continue;
}
$result = self::merge_selections( $result, $spread );
}
}
return $result;
}
/**
* Expand a named fragment into its query info tree, memoizing the result.
*
* @param string $name The fragment name.
* @param array $variable_values Variable values for resolving arguments.
* @param array<string, FragmentDefinitionNode> $fragments Named fragment definitions from the document.
* @param array<string, array> $expanded_fragments Memoized expansions, keyed by fragment name.
* @return ?array The expanded tree, or null when the fragment is not defined.
*/
private static function expand_fragment( string $name, array $variable_values, array $fragments, array &$expanded_fragments ): ?array {
if ( array_key_exists( $name, $expanded_fragments ) ) {
return $expanded_fragments[ $name ];
}
$fragment = $fragments[ $name ] ?? null;
if ( null === $fragment ) {
return null;
}
// Seed the entry before recursing so a fragment cycle expands to nothing
// instead of recursing forever (defensive: NoFragmentCycles rejects
// such documents during validation).
$expanded_fragments[ $name ] = array();
$expanded_fragments[ $name ] = self::extract_selection_set( $fragment->selectionSet, $variable_values, $fragments, $expanded_fragments );
return $expanded_fragments[ $name ];
}
/**
* Build the entry for a single field node.
*
* @param FieldNode $field The field node.
* @param array $variable_values Variable values for resolving arguments.
* @param array<string, FragmentDefinitionNode> $fragments Named fragment definitions from the document.
* @param array<string, array> $expanded_fragments Memoized fragment expansions, keyed by fragment name.
* @return array|bool True for leaf fields, associative array otherwise.
*/
private static function build_field_entry( FieldNode $field, array $variable_values, array $fragments, array &$expanded_fragments ): array|bool {
$has_args = ! empty( $field->arguments ) && count( $field->arguments ) > 0;
$has_sub_selection = null !== $field->selectionSet;
if ( ! $has_args && ! $has_sub_selection ) {
return true;
}
$entry = array();
if ( $has_args ) {
$args = array();
foreach ( $field->arguments as $arg ) {
$args[ $arg->name->value ] = self::resolve_argument_value( $arg, $variable_values );
}
$entry['__args'] = $args;
}
if ( $has_sub_selection ) {
$sub = self::extract_selection_set( $field->selectionSet, $variable_values, $fragments, $expanded_fragments );
$entry = self::merge_selections( $entry, $sub );
}
return $entry;
}
/**
* Recursively merge two selection trees produced by extract()/build_field_entry().
*
* Used wherever selections from different sources are combined under
* the same key (notably: named fragment spreads expanded inline). Matches
* GraphQL's selection-set merge semantics — overlapping fields have their
* sub-selections unioned rather than one replacing the other, which a
* shallow `array_merge` would do.
*
* Rules:
* - Key only in one side: kept verbatim.
* - Both sides arrays: recurse, unioning children.
* - One array, one `true` (leaf): keep the array — it carries the
* sub-selection detail, and its presence already implies the field
* was requested.
* - Both `true`: keep `true`.
* - `__args` collisions (same field with different argument values):
* the second operand wins. Conflicting field args are a GraphQL
* validation error upstream of us, so this path is defensive.
*
* @param array $a First selection tree.
* @param array $b Second selection tree, merged into $a.
* @return array The merged tree.
*/
private static function merge_selections( array $a, array $b ): array {
foreach ( $b as $key => $value ) {
if ( ! array_key_exists( $key, $a ) ) {
$a[ $key ] = $value;
continue;
}
$existing = $a[ $key ];
if ( is_array( $existing ) && is_array( $value ) ) {
$a[ $key ] = self::merge_selections( $existing, $value );
} elseif ( is_array( $value ) ) {
// One side is `true`, the other is a sub-selection array — keep the array.
$a[ $key ] = $value;
}
// Both true, or existing-array + new-true: keep existing.
}
return $a;
}
/**
* Resolve the value of a single argument node, handling variables.
*
* @param ArgumentNode $arg The argument node.
* @param array $variable_values Variable values.
* @return mixed The resolved argument value.
*/
private static function resolve_argument_value( ArgumentNode $arg, array $variable_values ): mixed {
$value_node = $arg->value;
if ( $value_node instanceof \Automattic\WooCommerce\Vendor\GraphQL\Language\AST\VariableNode ) {
return $variable_values[ $value_node->name->value ] ?? null;
}
return \Automattic\WooCommerce\Vendor\GraphQL\Utils\AST::valueFromASTUntyped( $value_node, $variable_values );
}
}