Automattic\WooCommerce\Internal\OrderReviews

SubmissionHandler{} │ WC 10.8.0

Handles the AJAX submission of the Review Order form.

One comment per rated row, with per-row outcome reported back so a single row's failure cannot block the rest. Guests submit with the order key; logged-in customers must own the order.

Usage

$SubmissionHandler = new SubmissionHandler();
// use class methods

Methods

  1. public clear_auto_rejected_flag( $new_status, $old_status, $comment )
  2. public handle()
  3. public init()
  4. private static find_auto_rejected_review( WC_Order $order, int $product_id, int $variation_id )
  5. private static has_rejected_review( WC_Order $order, int $product_id, int $variation_id )
  6. private index_eligible_order_items( WC_Order $order )
  7. private static insert_review( array $comment_data )
  8. private maybe_mark_order_complete( WC_Order $order )
  9. private static moderate_edited_review( \WP_Comment $existing, string $content, string $ip, string $agent )
  10. private process_rows( WC_Order $order, array $rows_in )
  11. private static update_review_in_place( \WP_Comment $existing, string $content, int $rating, string $ip, string $agent )

Changelog

Since 10.8.0 Introduced.

SubmissionHandler{} code WC 11.1.2

class SubmissionHandler {

	/**
	 * Action name registered with admin-ajax.
	 */
	public const ACTION = 'woocommerce_submit_order_reviews';

	/**
	 * Order meta stamped with the time the Review Order page first had no
	 * actionable rows left.
	 *
	 * Set by the submission handler once every eligible item has a review by
	 * this customer (approved or pending moderation), and also by the Endpoint
	 * when the page is loaded with no actionable rows (e.g. all items are
	 * already-reviewed or skipped because reviews are disabled on the products).
	 */
	public const COMPLETED_META_KEY = '_wc_review_request_completed_at';

	/**
	 * Comment meta flag set on reviews the comment pipeline auto-rejected (spam or
	 * trash, e.g. a disallowed-keys hit), so a later resubmission is not treated as a
	 * moderator's final verdict by has_rejected_review().
	 */
	private const AUTO_REJECTED_META_KEY = '_wc_auto_rejected';

	/**
	 * Wire the AJAX endpoints.
	 *
	 * Auto-called by the WC dependency container after instantiation.
	 *
	 * @internal
	 */
	final public function init(): void {
		add_action( 'wp_ajax_' . self::ACTION, array( $this, 'handle' ) );
		add_action( 'wp_ajax_nopriv_' . self::ACTION, array( $this, 'handle' ) );
		add_action( 'transition_comment_status', array( $this, 'clear_auto_rejected_flag' ), 10, 3 );
	}

	/**
	 * Drop the automatic-rejection tag when a tagged review's status later changes.
	 *
	 * A moderator confirming the rejection (or our own re-moderation approving a
	 * resubmission) is the final word, so the row should no longer be skipped by
	 * has_rejected_review(). Our own auto-rejection sets the tag after the status
	 * transition, so it is not affected.
	 *
	 * @param int|string  $new_status New comment status.
	 * @param int|string  $old_status Old comment status.
	 * @param \WP_Comment $comment    The comment whose status changed.
	 */
	public function clear_auto_rejected_flag( $new_status, $old_status, $comment ): void {
		unset( $new_status, $old_status );
		if ( ! $comment instanceof \WP_Comment || 'review' !== $comment->comment_type ) {
			return;
		}
		if ( get_comment_meta( (int) $comment->comment_ID, self::AUTO_REJECTED_META_KEY, true ) ) {
			delete_comment_meta( (int) $comment->comment_ID, self::AUTO_REJECTED_META_KEY );
		}
	}

	/**
	 * Entry point fired by `admin-ajax.php`.
	 *
	 * Sends a JSON response and exits.
	 */
	public function handle(): void {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce is checked below.
		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$key      = isset( $_POST['key'] ) && is_string( $_POST['key'] ) ? sanitize_text_field( wp_unslash( $_POST['key'] ) ) : '';
		$nonce    = isset( $_POST['_wcnonce'] ) && is_string( $_POST['_wcnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wcnonce'] ) ) : '';
		// Row-level fields are sanitized inside process_rows(); the array as a whole only needs unslashing.
		$rows_in = isset( $_POST['reviews'] ) && is_array( $_POST['reviews'] ) ? wp_unslash( $_POST['reviews'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		if ( ! is_string( $nonce ) || ! wp_verify_nonce( $nonce, self::ACTION ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'woocommerce' ) ), 403 );
		}

		$order = $order_id ? wc_get_order( $order_id ) : false;
		if ( ! $order instanceof WC_Order ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'woocommerce' ) ), 404 );
		}

		if ( '' === $key || ! hash_equals( $order->get_order_key(), $key ) ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'woocommerce' ) ), 404 );
		}

		// Logged-in user must own the order. Guests with the right key still pass.
		if ( $order->get_customer_id() && is_user_logged_in() && get_current_user_id() !== $order->get_customer_id() ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'woocommerce' ) ), 404 );
		}

		// Reuse the same eligibility filter the page-load endpoint uses so the
		// submit path can never run on an order whose status no longer permits it.
		// phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- documented on Endpoint::is_authorised().
		$eligible_statuses = (array) apply_filters(
			'woocommerce_review_order_eligible_statuses',
			array( OrderStatus::COMPLETED ),
			$order
		);

		if ( ! in_array( $order->get_status(), $eligible_statuses, true ) ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'woocommerce' ) ), 404 );
		}

		$results = $this->process_rows( $order, $rows_in );

		$this->maybe_mark_order_complete( $order );

		/**
		 * Fires after the Review Order form has been processed.
		 *
		 * @since 10.8.0
		 *
		 * @param WC_Order $order   The order.
		 * @param array    $results Per-row outcomes — see `SubmissionHandler::process_rows()`.
		 */
		do_action( 'woocommerce_review_order_submitted', $order, $results );

		wp_send_json_success( array( 'results' => $results ) );
	}

	/**
	 * Process the submitted row payload and return per-row outcomes.
	 *
	 * @param WC_Order $order  Order being reviewed.
	 * @param array    $rows_in Raw `$_POST['reviews']` value.
	 * @return array<int, array{product_id:int, status:string, comment_id?:int, error?:string}>
	 */
	private function process_rows( WC_Order $order, array $rows_in ): array {
		$results      = array();
		$item_index   = $this->index_eligible_order_items( $order );
		$author_name  = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
		$author_email = $order->get_billing_email();
		$author_ip    = $order->get_customer_ip_address();
		$author_agent = $order->get_customer_user_agent();

		// Drop any per-request memoisation a prior caller may have populated,
		// then preload the eligibility cache so the per-row decide() calls
		// below don't issue one already-reviewed query each. Reset matters
		// inside the suite (multiple submissions in one PHP process) and is
		// a no-op in production (admin-ajax runs in a fresh process).
		ItemEligibility::reset_cache();
		ItemEligibility::preload_for_items( $item_index, $order );

		// Comment id created or updated in THIS request, keyed by product|variation
		// slot. The eligibility cache only reflects pre-request state, so this lets
		// the loop reject later rows for a slot already handled in the same request.
		$request_slot_comments = array();

		foreach ( $rows_in as $row_index => $row ) {
			$row_index = (int) $row_index;
			$row       = is_array( $row ) ? $row : array();

			$rating = isset( $row['rating'] ) ? (int) $row['rating'] : 0;
			if ( 0 === $rating ) {
				// Empty rating means the customer chose to skip this row; allowed.
				continue;
			}

			$product_id    = isset( $row['product_id'] ) ? absint( $row['product_id'] ) : 0;
			$order_item_id = isset( $row['order_item_id'] ) ? absint( $row['order_item_id'] ) : 0;
			// $rows_in was already unslashed in handle(); avoid double-unslashing.
			$text = isset( $row['text'] ) && is_string( $row['text'] ) ? trim( wp_kses( $row['text'], 'pre_comment_content' ) ) : '';

			// Per-row result always carries `product_id` (parent product, where
			// the review lives) and `variation_id` (0 for simple products) so
			// callers don't have to know whether the client posted the parent
			// or the variation id as `product_id`. Both are echoed back as
			// soon as we resolve the line item; for early validation failures
			// they reflect the raw submitted product id with `variation_id: 0`.
			$result = array(
				'product_id'   => $product_id,
				'variation_id' => 0,
				'status'       => 'error',
			);

			if ( $rating < 1 || $rating > 5 ) {
				$result['error']       = 'invalid_rating';
				$results[ $row_index ] = $result;
				continue;
			}

			// invalid_row also covers fully-refunded line items: index_eligible_order_items()
			// runs them through woocommerce_review_order_eligible_items, which strips them.
			if ( ! $product_id || ! $order_item_id || ! isset( $item_index[ $order_item_id ] ) ) {
				$result['error']       = 'invalid_row';
				$results[ $row_index ] = $result;
				continue;
			}

			$item = $item_index[ $order_item_id ];

			// Variable products: the row template posts the variation id,
			// while $item->get_product_id() returns the parent. Accept either.
			$line_product_id   = (int) $item->get_product_id();
			$line_variation_id = (int) $item->get_variation_id();
			if ( $product_id !== $line_product_id && $product_id !== $line_variation_id ) {
				$result['error']       = 'product_mismatch';
				$results[ $row_index ] = $result;
				continue;
			}

			// Canonicalise the result fields now that we've resolved the line
			// item: parent product id + the line's variation id (0 for simple).
			$result['product_id']   = $line_product_id;
			$result['variation_id'] = $line_variation_id;

			// Reviews always attach to the parent product so they show on the
			// product page regardless of which variation was bought.
			$review_post_id = $line_product_id;

			// Reviews are stored and resolved per product/variation slot. If this
			// slot was already handled in this request (the stock page collapses to
			// one row per slot, but a theme override or a tampered POST can send
			// several), reuse that outcome instead of storing a second review, so
			// extra rows can't stack duplicates yet still report success.
			$slot_key = $line_product_id . '|' . $line_variation_id;
			if ( isset( $request_slot_comments[ $slot_key ] ) ) {
				$results[ $row_index ] = $request_slot_comments[ $slot_key ];
				continue;
			}

			// Reject submissions for products whose review form was never
			// rendered (comments disabled on the product).
			$decision = ItemEligibility::decide( $item, $order );
			if ( ItemEligibility::STATUS_SKIP === $decision['status'] ) {
				$result['error']       = 'reviews_not_open';
				$results[ $row_index ] = $result;
				continue;
			}

			// Only attribute the comment to a WP user when the current request is
			// authenticated as that user. Guests reaching the page via the order
			// key are not authenticated, so the comment stays unattributed (0).
			$customer_id     = (int) $order->get_customer_id();
			$current_user_id = get_current_user_id();
			$comment_user_id = ( $current_user_id > 0 && $current_user_id === $customer_id ) ? $current_user_id : 0;

			// If the customer already has a review tied to this order for this
			// product, update it in place instead of stacking duplicates. The
			// existing comment id comes from the server-side lookup, not the
			// client, so a tampered POST can't target someone else's review.
			$existing = $decision['comment'] instanceof \WP_Comment ? $decision['comment'] : null;

			if ( $existing instanceof \WP_Comment ) {
				// decide() only returns approved or held reviews, so a spam/trash row
				// here would be a moderator's final verdict; never edit it.
				if ( in_array( wp_get_comment_status( $existing ), array( 'spam', 'trash' ), true ) ) {
					$result['error']       = 'update_failed';
					$results[ $row_index ] = $result;
					continue;
				}

				$result = array_merge( $result, self::update_review_in_place( $existing, $text, $rating, $author_ip, $author_agent ) );
				if ( ! isset( $result['error'] ) ) {
					$request_slot_comments[ $slot_key ] = $result;
				}
				$results[ $row_index ] = $result;
				continue;
			}

			// A moderator's spam/trash verdict for this slot is final.
			if ( self::has_rejected_review( $order, $line_product_id, $line_variation_id ) ) {
				$result['error']       = 'update_failed';
				$results[ $row_index ] = $result;
				continue;
			}

			// A row the pipeline auto-rejected earlier is invisible to decide()
			// (it only looks at approved/held rows). Reuse it instead of storing a
			// fresh row on every retry, so a disallowed resubmission can't grow the
			// table without bound.
			$auto_rejected = self::find_auto_rejected_review( $order, $line_product_id, $line_variation_id );
			if ( $auto_rejected instanceof \WP_Comment ) {
				$result = array_merge( $result, self::update_review_in_place( $auto_rejected, $text, $rating, $author_ip, $author_agent ) );
				if ( ! isset( $result['error'] ) ) {
					$request_slot_comments[ $slot_key ] = $result;
				}
				$results[ $row_index ] = $result;
				continue;
			}

			$comment_meta = array(
				'rating'                            => $rating,
				'verified'                          => 1,
				ItemEligibility::ORDER_META_KEY     => (int) $order->get_id(),
				ItemEligibility::VARIATION_META_KEY => $line_variation_id,
			);

			$variation_summary = ItemEligibility::format_variation_summary( $item );
			if ( '' !== $variation_summary ) {
				$comment_meta[ ItemEligibility::VARIATION_SUMMARY_META_KEY ] = $variation_summary;
			}

			$comment_id = self::insert_review(
				array(
					'comment_post_ID'      => $review_post_id,
					// Core strips markup from the name; fall back when nothing would be left.
					'comment_author'       => '' !== sanitize_text_field( $author_name ) ? $author_name : __( 'Anonymous', 'woocommerce' ),
					'comment_author_email' => $author_email,
					'comment_author_url'   => '',
					'comment_author_IP'    => $author_ip,
					'comment_agent'        => $author_agent,
					'comment_content'      => $text,
					'comment_type'         => 'review',
					'user_id'              => $comment_user_id,
					'comment_meta'         => $comment_meta,
				)
			);
			if ( ! $comment_id || is_wp_error( $comment_id ) ) {
				$result['error']       = 'insert_failed';
				$results[ $row_index ] = $result;
				continue;
			}

			// Tag a row the checks rejected (spam/trash) as an automatic rejection,
			// so a later valid resubmission is treated as a fresh attempt rather
			// than a moderator's final verdict by has_rejected_review().
			if ( in_array( wp_get_comment_status( $comment_id ), array( 'spam', 'trash' ), true ) ) {
				update_comment_meta( (int) $comment_id, self::AUTO_REJECTED_META_KEY, 1 );
			}

			$result['comment_id'] = (int) $comment_id;
			$result['status']     = 'approved' === wp_get_comment_status( $comment_id ) ? 'ok' : 'pending_moderation';

			$request_slot_comments[ $slot_key ] = $result;
			$results[ $row_index ]              = $result;
		}//end foreach

		return $results;
	}

	/**
	 * Update a review row in place: re-moderate changed content, write the rating,
	 * and move the row to the resulting status. Shared by the normal edit path and
	 * by resubmitting after an automatic rejection, so a rejected row is corrected
	 * rather than a new one stored.
	 *
	 * @param \WP_Comment $existing The review being updated.
	 * @param string      $content  The new content (already run through comment kses).
	 * @param int         $rating   Rating value 1-5.
	 * @param string      $ip       Comment author IP.
	 * @param string      $agent    Comment author user agent.
	 * @return array{comment_id?:int, status?:string, error?:string}
	 */
	private static function update_review_in_place( \WP_Comment $existing, string $content, int $rating, string $ip, string $agent ): array {
		$existing_id = (int) $existing->comment_ID;

		// Compare against the stored content run back through comment kses so that
		// filters core adds on save (e.g. rel="nofollow ugc" on links) don't read
		// as a content change. Only re-moderate when the text actually changed; a
		// rating-only edit keeps the row's current moderation state.
		$stored_content = trim( wp_kses( (string) $existing->comment_content, 'pre_comment_content' ) );
		$approved       = $content === $stored_content
			? $existing->comment_approved
			: self::moderate_edited_review( $existing, $content, $ip, $agent );

		$update_ok = wp_update_comment(
			wp_slash(
				array(
					'comment_ID'      => $existing_id,
					'comment_content' => $content,
				)
			)
		);
		if ( false === $update_ok || is_wp_error( $update_ok ) ) {
			return array( 'error' => 'update_failed' );
		}

		update_comment_meta( $existing_id, 'rating', $rating );

		// Drive the status explicitly so a previously auto-rejected row is untrashed
		// when it now approves or holds. Only when it actually changes, so an
		// unchanged status doesn't fire a redundant transition (or approval notice).
		// clear_auto_rejected_flag() drops the tag on a real transition; re-tag only
		// when the row stays rejected.
		$target = in_array( $approved, array( 'spam', 'trash' ), true )
			? (string) $approved
			: ( 1 === (int) $approved ? 'approve' : 'hold' );

		$status_vocab   = array(
			'approved'   => 'approve',
			'unapproved' => 'hold',
			'spam'       => 'spam',
			'trash'      => 'trash',
		);
		$current_status = $status_vocab[ wp_get_comment_status( $existing_id ) ] ?? '';
		if ( $target !== $current_status ) {
			wp_set_comment_status( $existing_id, $target );
		}

		if ( in_array( $approved, array( 'spam', 'trash' ), true ) ) {
			update_comment_meta( $existing_id, self::AUTO_REJECTED_META_KEY, 1 );
		}

		return array(
			'comment_id' => $existing_id,
			'status'     => 'approved' === wp_get_comment_status( $existing_id ) ? 'ok' : 'pending_moderation',
		);
	}

	/**
	 * Approval status for an edited review, run through the same moderation an insert
	 * gets: the disallowed-keys list, moderation keywords and link limit, and the
	 * `pre_comment_approved` filter. `wp_update_comment()` never runs these itself.
	 *
	 * @param \WP_Comment $existing The review being edited.
	 * @param string      $content  The new content.
	 * @param string      $ip       Comment author IP.
	 * @param string      $agent    Comment author user agent.
	 * @return int|string 1 or 0 to approve/hold, or 'spam'/'trash' to reject.
	 */
	private static function moderate_edited_review( \WP_Comment $existing, string $content, string $ip, string $agent ) {
		$comment_data = array(
			'comment_ID'           => (int) $existing->comment_ID,
			'comment_post_ID'      => (int) $existing->comment_post_ID,
			'comment_author'       => $existing->comment_author,
			'comment_author_email' => $existing->comment_author_email,
			'comment_author_url'   => $existing->comment_author_url,
			'comment_content'      => $content,
			'comment_author_IP'    => $ip,
			'comment_agent'        => $agent,
			'comment_type'         => 'review',
			// A deleted author would make wp_check_comment_data() call has_cap() on
			// a false user and fatal, so fall back to an unattributed 0.
			'user_id'              => get_userdata( (int) $existing->user_id ) ? (int) $existing->user_id : 0,
		);

		// Verified-purchase reviews are not held behind the "commenter must already
		// have an approved comment" gate, matching the insert path.
		add_filter( 'pre_option_comment_previously_approved', '__return_zero' );
		try {
			$approved = wp_check_comment_data( $comment_data );
		} finally {
			remove_filter( 'pre_option_comment_previously_approved', '__return_zero' );
		}

		// A filter may return WP_Error; fall back to holding for moderation.
		return is_wp_error( $approved ) ? 0 : $approved;
	}

	/**
	 * Insert a review through `wp_new_comment()`, so it gets the same filters,
	 * spam checks and notifications as a comment posted on the product page.
	 *
	 * @param array $comment_data Unslashed comment data.
	 * @return int|false|\WP_Error Comment ID, false on failure, or the error from the comment checks.
	 */
	private static function insert_review( array $comment_data ) {
		// Sanitize the address as core's pre_comment_author_email chain would, but
		// keep it un-encoded (sanitize_email preserves `&`) so the eligibility
		// lookups still match the order's billing email.
		$raw_email      = wp_slash( sanitize_email( (string) $comment_data['comment_author_email'] ) );
		$keep_raw_email = function () use ( $raw_email ) {
			return $raw_email;
		};

		// These reviews are tied to a real purchased line item, so don't hold them
		// behind the "commenter must already have an approved comment" gate that
		// core applies to anonymous blog commenters.
		add_filter( 'pre_option_comment_previously_approved', '__return_zero' );
		// Variations share the parent product, so identical text on two of them is not a duplicate.
		add_filter( 'duplicate_comment_id', '__return_zero' );
		// Keep the sanitized address as-is; core's chain would otherwise encode `&`.
		add_filter( 'pre_comment_author_email', $keep_raw_email, PHP_INT_MAX );
		// Rows are capped at one review per purchased item, and core's flood query matches order notes by IP.
		add_filter( 'wp_is_comment_flood', '__return_false', PHP_INT_MAX );

		try {
			return wp_new_comment( wp_slash( $comment_data ), true );
		} finally {
			remove_filter( 'pre_option_comment_previously_approved', '__return_zero' );
			remove_filter( 'duplicate_comment_id', '__return_zero' );
			remove_filter( 'pre_comment_author_email', $keep_raw_email, PHP_INT_MAX );
			remove_filter( 'wp_is_comment_flood', '__return_false', PHP_INT_MAX );
		}
	}

	/**
	 * Whether a moderator already marked this exact order/product/variation
	 * review as spam or trash. Reviews the comment pipeline auto-rejected (tagged
	 * with AUTO_REJECTED_META_KEY) are excluded, so an automatic verdict does not
	 * lock the customer out of resubmitting a clean review.
	 *
	 * @param WC_Order $order        Order being reviewed.
	 * @param int      $product_id   Parent product id.
	 * @param int      $variation_id Variation id (0 for simple products).
	 * @return bool
	 */
	private static function has_rejected_review( WC_Order $order, int $product_id, int $variation_id ): bool {
		$email = $order->get_billing_email();
		if ( '' === $email ) {
			return false;
		}

		$comments = get_comments(
			array(
				'post_id'      => $product_id,
				'author_email' => $email,
				'type'         => 'review',
				'status'       => array( 'spam', 'trash' ),
				'number'       => 1,
				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + author_email.
					'relation' => 'AND',
					array(
						'key'   => ItemEligibility::ORDER_META_KEY,
						'value' => (string) $order->get_id(),
					),
					array(
						// Only a moderator's verdict is final; skip pipeline auto-rejections.
						'key'     => self::AUTO_REJECTED_META_KEY,
						'compare' => 'NOT EXISTS',
					),
					array(
						'relation' => 'OR',
						array(
							'key'   => ItemEligibility::VARIATION_META_KEY,
							'value' => (string) $variation_id,
						),
						array(
							// Pre-10.9.0 reviews have no VARIATION_META_KEY row at all.
							'key'     => ItemEligibility::VARIATION_META_KEY,
							'compare' => 'NOT EXISTS',
						),
					),
				),
			)
		);

		return is_array( $comments ) && ! empty( $comments );
	}

	/**
	 * The customer's own auto-rejected (spam/trash, tagged) review for this
	 * order/product/variation, if any, so a resubmission reuses that row instead
	 * of stacking a new one. Moderator verdicts (untagged) are not returned.
	 *
	 * @param WC_Order $order        Order being reviewed.
	 * @param int      $product_id   Parent product id.
	 * @param int      $variation_id Variation id (0 for simple products).
	 * @return \WP_Comment|null
	 */
	private static function find_auto_rejected_review( WC_Order $order, int $product_id, int $variation_id ): ?\WP_Comment {
		$email = $order->get_billing_email();
		if ( '' === $email ) {
			return null;
		}

		$comments = get_comments(
			array(
				'post_id'      => $product_id,
				'author_email' => $email,
				'type'         => 'review',
				'status'       => array( 'spam', 'trash' ),
				'number'       => 1,
				'orderby'      => 'comment_date_gmt',
				'order'        => 'DESC',
				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + author_email.
					'relation' => 'AND',
					array(
						'key'   => ItemEligibility::ORDER_META_KEY,
						'value' => (string) $order->get_id(),
					),
					array(
						'key'     => self::AUTO_REJECTED_META_KEY,
						'compare' => 'EXISTS',
					),
					array(
						'relation' => 'OR',
						array(
							'key'   => ItemEligibility::VARIATION_META_KEY,
							'value' => (string) $variation_id,
						),
						array(
							'key'     => ItemEligibility::VARIATION_META_KEY,
							'compare' => 'NOT EXISTS',
						),
					),
				),
			)
		);

		if ( ! is_array( $comments ) || empty( $comments ) ) {
			return null;
		}

		$first = reset( $comments );
		return $first instanceof \WP_Comment ? $first : null;
	}

	/**
	 * Set the completed-at meta when every eligible item has a review by this
	 * customer (approved or pending moderation), whether posted in this
	 * submission or an earlier one. Spam/trash comments are excluded.
	 *
	 * @param WC_Order $order Order being reviewed.
	 */
	private function maybe_mark_order_complete( WC_Order $order ): void {
		// Recording the moment the order first became fully reviewed; never overwrite.
		if ( $order->get_meta( self::COMPLETED_META_KEY ) ) {
			return;
		}

		$customer_email = $order->get_billing_email();
		if ( '' === $customer_email ) {
			return;
		}

		// Build the same eligible-row set the page uses, then collect the
		// distinct (parent product, variation) slots that need a review.
		// Counting by slot rather than per-line-item means a double-submit of
		// the same variation can't satisfy a sibling variation's quota, and
		// the same simple product appearing on multiple rows still only
		// needs one review (the page collapses those rows anyway).
		// phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- documented at the page-template invocation site.
		$eligible_items = (array) apply_filters( 'woocommerce_review_order_eligible_items', $order->get_items(), $order );

		$required_slots = array();
		$product_ids    = array();
		foreach ( $eligible_items as $item ) {
			if ( ! $item instanceof \WC_Order_Item_Product ) {
				continue;
			}
			$product_id   = (int) $item->get_product_id();
			$variation_id = (int) $item->get_variation_id();
			if ( $product_id > 0 ) {
				$required_slots[ $product_id . '|' . $variation_id ] = true;
				$product_ids[ $product_id ]                          = $product_id;
			}
		}

		if ( empty( $required_slots ) ) {
			return;
		}

		// Single grouped lookup, fetching the comment objects directly so we
		// can read comment_post_ID without a follow-up query per row. Limit
		// to approved + pending-moderation so spam/trash never count as
		// completion, AND to reviews tagged with this order so an older
		// review of the same parent product from a previous order doesn't
		// satisfy the per-row count for the current one. number=>0 disables
		// the default 20-row cap so this still works for orders with many
		// reviewable items.
		$comments = get_comments(
			array(
				'post__in'     => array_values( $product_ids ),
				'author_email' => $customer_email,
				'type'         => 'review',
				'status'       => array( 'approve', 'hold' ),
				'number'       => 0,
				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post__in + author_email.
					array(
						'key'   => ItemEligibility::ORDER_META_KEY,
						'value' => (string) $order->get_id(),
					),
				),
			)
		);

		if ( ! is_array( $comments ) || empty( $comments ) ) {
			return;
		}

		// Index reviewed slots by (parent_id, variation_id); duplicate comments
		// for the same slot still count as one toward completion.
		$reviewed_slots = array();
		foreach ( $comments as $comment ) {
			if ( $comment instanceof \WP_Comment ) {
				$slot_key                    = (int) $comment->comment_post_ID . '|' . (int) get_comment_meta( (int) $comment->comment_ID, ItemEligibility::VARIATION_META_KEY, true );
				$reviewed_slots[ $slot_key ] = true;
			}
		}

		foreach ( $required_slots as $slot_key => $_ ) {
			if ( ! isset( $reviewed_slots[ $slot_key ] ) ) {
				return;
			}
		}

		$order->update_meta_data( self::COMPLETED_META_KEY, (string) time() );
		$order->save();
	}

	/**
	 * Map order_item_id => `WC_Order_Item_Product` for fast row lookup,
	 * filtered through `woocommerce_review_order_eligible_items` so the
	 * handler agrees with the page on which items are reviewable. The
	 * default callback excludes fully-refunded items.
	 *
	 * @param WC_Order $order Order being reviewed.
	 * @return array<int, \WC_Order_Item_Product>
	 */
	private function index_eligible_order_items( WC_Order $order ): array {
		/**
		 * Filter the eligible items considered by the Review Order
		 * submission handler.
		 *
		 * Same hook the page uses; documented in
		 * `templates/order/customer-review-order.php`.
		 *
		 * @since 10.8.0
		 *
		 * @param \WC_Order_Item[] $items Order line items.
		 * @param WC_Order         $order The order being reviewed.
		 */
		$items = (array) apply_filters( 'woocommerce_review_order_eligible_items', $order->get_items(), $order );

		$index = array();
		foreach ( $items as $item ) {
			if ( $item instanceof \WC_Order_Item_Product ) {
				$index[ $item->get_id() ] = $item;
			}
		}
		return $index;
	}
}