Automattic\WooCommerce\StoreApi\Routes\V1

ProductReviews::get_route_response()protectedWC 1.0

Get a collection of reviews.

Method of the class: ProductReviews{}

No Hooks.

Return

\WP_REST_Response.

Usage

// protected - for code of main (parent) or child class
$result = $this->get_route_response( $request );
$request(\WP_REST_Request) (required)
Request object.

ProductReviews::get_route_response() code WC 9.3.3

protected function get_route_response( \WP_REST_Request $request ) {
	$prepared_args = array(
		'type'          => 'review',
		'status'        => 'approve',
		'no_found_rows' => false,
		'offset'        => $request['offset'],
		'order'         => $request['order'],
		'number'        => $request['per_page'],
		'post__in'      => $request['product_id'],
	);

	/**
	 * Map category id to list of product ids.
	 */
	if ( ! empty( $request['category_id'] ) ) {
		$category_ids = $request['category_id'];
		$child_ids    = [];
		foreach ( $category_ids as $category_id ) {
			$child_ids = array_merge( $child_ids, get_term_children( $category_id, 'product_cat' ) );
		}
		$category_ids              = array_unique( array_merge( $category_ids, $child_ids ) );
		$product_ids               = get_objects_in_term( $category_ids, 'product_cat' );
		$prepared_args['post__in'] = isset( $prepared_args['post__in'] ) ? array_merge( $prepared_args['post__in'], $product_ids ) : $product_ids;
	}

	if ( 'rating' === $request['orderby'] ) {
		$prepared_args['meta_query'] = array( // phpcs:ignore
			'relation' => 'OR',
			array(
				'key'     => 'rating',
				'compare' => 'EXISTS',
			),
			array(
				'key'     => 'rating',
				'compare' => 'NOT EXISTS',
			),
		);
	}
	$prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] );

	if ( empty( $request['offset'] ) ) {
		$prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 );
	}

	$query            = new WP_Comment_Query();
	$query_result     = $query->query( $prepared_args );
	$response_objects = array();

	foreach ( $query_result as $review ) {
		$data               = $this->prepare_item_for_response( $review, $request );
		$response_objects[] = $this->prepare_response_for_collection( $data );
	}

	$total_reviews = (int) $query->found_comments;
	$max_pages     = (int) $query->max_num_pages;

	if ( $total_reviews < 1 ) {
		// Out-of-bounds, run the query again without LIMIT for total count.
		unset( $prepared_args['number'], $prepared_args['offset'] );

		$query                  = new WP_Comment_Query();
		$prepared_args['count'] = true;

		$total_reviews = $query->query( $prepared_args );
		$max_pages     = $request['per_page'] ? ceil( $total_reviews / $request['per_page'] ) : 1;
	}

	$response = rest_ensure_response( $response_objects );
	$response = ( new Pagination() )->add_headers( $response, $request, $total_reviews, $max_pages );

	return $response;
}