Automattic\WooCommerce\Internal\RestApi\Routes\V4\Settings\PaymentGateways\Schema

AbstractPaymentGatewaySettingsSchema::validate_field_valueprivateWC 1.0

Validate field value.

Method of the class: AbstractPaymentGatewaySettingsSchema{}

No Hooks.

Returns

true|WP_Error. True if valid, WP_Error otherwise.

Usage

// private - for code of main (parent) class only
$result = $this->validate_field_value( $key, $value, $field, $gateway );
$key(string) (required)
Field key.
$value(mixed) (required)
Sanitized value.
$field(array) (required)
Field definition.
$gateway(WC_Payment_Gateway) (required)
Gateway instance.

AbstractPaymentGatewaySettingsSchema::validate_field_value() code WC 10.4.3

private function validate_field_value( string $key, $value, array $field, WC_Payment_Gateway $gateway ) {
	$field_type = $this->normalize_field_type( $field['type'] ?? 'text' );

	// Validate select/radio options.
	if ( in_array( $field_type, array( 'select', 'radio' ), true ) && ! empty( $field['options'] ) ) {
		if ( ! array_key_exists( $value, $field['options'] ) && '' !== $value ) {
			return new WP_Error(
				'rest_invalid_param',
				sprintf(
					/* translators: 1: field key, 2: valid options */
					__( 'Invalid value for %1$s. Valid options: %2$s', 'woocommerce' ),
					$key,
					implode( ', ', array_keys( $field['options'] ) )
				),
				array( 'status' => 400 )
			);
		}
	}

	// Validate multiselect options.
	if ( 'multiselect' === $field_type && ! empty( $field['options'] ) ) {
		if ( is_array( $value ) ) {
			foreach ( $value as $v ) {
				if ( ! array_key_exists( $v, $field['options'] ) ) {
					return new WP_Error(
						'rest_invalid_param',
						sprintf(
							/* translators: 1: field key, 2: invalid value */
							__( 'Invalid option "%2$s" for %1$s.', 'woocommerce' ),
							$key,
							$v
						),
						array( 'status' => 400 )
					);
				}
			}
		}
	}

	// Add more validations as needed.

	return true;
}