Automattic\WooCommerce\StoreApi\Routes\V1\Ucp

CatalogSearch::validate_search_input │ private │ WC 1.0

Validate the search query string and filters before any query runs.

Values that would silently degrade to something meaningless — a price cast from a non-numeric string, a range whose minimum exceeds its maximum — are refused rather than executed, so a caller cannot spend database work on a request that was never going to match.

Метод класса: CatalogSearch{}

Хуков нет.

Возвращает

\WP_REST_Response|null. Error response, or null when the input is acceptable.

Использование

// private - только в коде основоного (родительского) класса
$result = $this->validate_search_input( $query, $filters );
$query(строка) (обязательный)
Free-text search term.
$filters(массив) (обязательный)
Request filters.

Код CatalogSearch::validate_search_input() WC 11.3.0

private function validate_search_input( string $query, array $filters ) {
	if ( strlen( $query ) > self::MAX_QUERY_LENGTH ) {
		return $this->ucp_error(
			'VALIDATION_ERROR',
			sprintf(
				/* translators: %d: maximum accepted query length in characters. */
				__( 'query exceeds the maximum length of %d characters.', 'woocommerce' ),
				self::MAX_QUERY_LENGTH
			),
			'recoverable',
			400
		);
	}

	$has_categories = ! empty( $filters['categories'] ) && is_array( $filters['categories'] );
	$has_price      = isset( $filters['price'] ) && is_array( $filters['price'] ) && ( isset( $filters['price']['min'] ) || isset( $filters['price']['max'] ) );

	// UCP requires at least one recognized input; an unknown filter on its
	// own would otherwise browse the whole catalog.
	if ( '' === $query && ! $has_categories && ! $has_price ) {
		return $this->ucp_error(
			'VALIDATION_ERROR',
			__( 'A query or at least one supported filter (categories, price) is required.', 'woocommerce' ),
			'recoverable',
			400
		);
	}

	if ( ! $has_price ) {
		return null;
	}

	$bounds = array();

	foreach ( array( 'min', 'max' ) as $bound ) {
		if ( ! isset( $filters['price'][ $bound ] ) ) {
			continue;
		}

		$value = $filters['price'][ $bound ];

		if ( ! is_numeric( $value ) || (float) $value < 0 ) {
			return $this->ucp_error(
				'VALIDATION_ERROR',
				sprintf(
					/* translators: %s: price filter bound name, `min` or `max`. */
					__( 'filters.price.%s must be a non-negative amount in minor units.', 'woocommerce' ),
					$bound
				),
				'recoverable',
				400
			);
		}

		$bounds[ $bound ] = (int) $value;
	}

	if ( isset( $bounds['min'], $bounds['max'] ) && $bounds['min'] > $bounds['max'] ) {
		return $this->ucp_error(
			'VALIDATION_ERROR',
			__( 'filters.price.min must not exceed filters.price.max.', 'woocommerce' ),
			'recoverable',
			400
		);
	}

	return null;
}