Automattic\WooCommerce\Internal\ShopperLists

ShopperListItem::resolve_variation_attributesprivate staticWC 1.0

Resolve and validate the variation attribute array against the variation product.

Mirrors CartController::parse_variation_data(): specific values come from the variation (server-authoritative); "any" slots must be supplied by the caller with a value that exists on the parent product.

Method of the class: ShopperListItem{}

No Hooks.

Returns

Array.

Usage

$result = ShopperListItem::resolve_variation_attributes( $variation_product, $requested_attributes ): array;
$variation_product(WC_Product) (required)
Variation product.
$requested_attributes(array) (required)
Variation attributes supplied by the caller, keyed by attribute_<slug>.

ShopperListItem::resolve_variation_attributes() code WC 10.9.1

private static function resolve_variation_attributes( \WC_Product $variation_product, array $requested_attributes ): array {
	$parent = wc_get_product( $variation_product->get_parent_id() );
	if ( ! $parent || ! $parent->is_type( ProductType::VARIABLE ) || ! $variation_product->is_type( ProductType::VARIATION ) ) {
		return array();
	}

	$result = array();

	$all_attributes       = array_filter( $parent->get_attributes(), fn( $attribute ) => $attribute->get_variation() );
	$variation_attributes = wc_get_product_variation_attributes( $variation_product->get_id() );

	foreach ( $all_attributes as $name => $attribute ) {
		$key      = 'attribute_' . $name;
		$expected = $variation_attributes[ $key ] ?? '';

		// Variation doesn't provide attribute ('any' attribute).
		if ( '' === $expected ) {
			if ( ! isset( $requested_attributes[ $key ] ) ) {
				throw new \InvalidArgumentException(
					esc_html(
						sprintf(
							/* translators: %s: attribute name. */
							__( 'Attribute "%s" is required.', 'woocommerce' ),
							$name
						)
					)
				);
			}

			if ( ! in_array( $requested_attributes[ $key ], $attribute->get_slugs(), true ) ) {
				throw new \InvalidArgumentException(
					esc_html(
						sprintf(
							/* translators: 1: attribute name, 2: comma-separated allowed values. */
							__( 'Invalid value posted for "%1$s". Allowed values: %2$s', 'woocommerce' ),
							$name,
							implode( ', ', $attribute->get_slugs() )
						)
					)
				);
			}

			$result[ $key ] = $requested_attributes[ $key ];
			continue;
		}//end if

		// Variation provides attribute.
		if ( isset( $requested_attributes[ $key ] ) && $requested_attributes[ $key ] !== $expected ) {
			throw new \InvalidArgumentException(
				esc_html(
					sprintf(
						/* translators: 1: attribute name, 2: expected value. */
						__( 'Invalid value posted for "%1$s". Expected "%2$s".', 'woocommerce' ),
						$name,
						$expected
					)
				)
			);
		}

		$result[ $key ] = $expected;
	}//end foreach

	return $result;
}