Automattic\WooCommerce\Blocks\Domain\Services

CheckoutFields::process_select_field()privateWC 1.0

Processes the options for a select field and returns the new field_options array.

Method of the class: CheckoutFields{}

No Hooks.

Return

Array|false. The updated $field_data array or false if an error was encountered.

Usage

// private - for code of main (parent) class only
$result = $this->process_select_field( $field_data, $options );
$field_data(array) (required)
The field data array to be updated.
$options(array) (required)
The options supplied during field registration.

CheckoutFields::process_select_field() code WC 9.0.1

private function process_select_field( $field_data, $options ) {
	$id = $options['id'];

	if ( empty( $options['options'] ) || ! is_array( $options['options'] ) ) {
		$message = sprintf( 'Unable to register field with id: "%s". %s', $id, 'Fields of type "select" must have an array of "options".' );
		_doing_it_wrong( 'woocommerce_register_additional_checkout_field', esc_html( $message ), '8.6.0' );
		return false;
	}
	$cleaned_options = [];
	$added_values    = [];

	// Check all entries in $options['options'] has a key and value member.
	foreach ( $options['options'] as $option ) {
		if ( ! isset( $option['value'] ) || ! isset( $option['label'] ) ) {
			$message = sprintf( 'Unable to register field with id: "%s". %s', $id, 'Fields of type "select" must have an array of "options" and each option must contain a "value" and "label" member.' );
			_doing_it_wrong( 'woocommerce_register_additional_checkout_field', esc_html( $message ), '8.6.0' );
			return false;
		}

		$sanitized_value = sanitize_text_field( $option['value'] );
		$sanitized_label = sanitize_text_field( $option['label'] );

		if ( in_array( $sanitized_value, $added_values, true ) ) {
			$message = sprintf( 'Duplicate key found when registering field with id: "%s". The value in each option of "select" fields must be unique. Duplicate value "%s" found. The duplicate key will be removed.', $id, $sanitized_value );
			_doing_it_wrong( 'woocommerce_register_additional_checkout_field', esc_html( $message ), '8.6.0' );
			continue;
		}

		$added_values[] = $sanitized_value;

		$cleaned_options[] = [
			'value' => $sanitized_value,
			'label' => $sanitized_label,
		];
	}

	$field_data['options'] = $cleaned_options;

	// If the field is not required, inject an empty option at the start.
	if ( isset( $field_data['required'] ) && false === $field_data['required'] && ! in_array( '', $added_values, true ) ) {
		$field_data['options'] = array_merge(
			[
				[
					'value' => '',
					'label' => '',
				],
			],
			$field_data['options']
		);
	}

	return $field_data;
}