WP_REST_Attachments_Controller::validate_image_size_namesprivate staticWP 7.1.0

Validates an image size name, or an array of names sharing a single file.

Shared by the sideload endpoint, which names the size a file is produced for, and the finalize endpoint, which names the size each submitted entry is stored under. Both need the same set, and finalize accepts a payload of its own rather than one this class produced, so leaving it unconstrained there would let a submission write an arbitrary key into the metadata 'sizes' array or route a file into a branch it was never produced for.

Method of the class: WP_REST_Attachments_Controller{}

No Hooks.

Returns

true|WP_Error. True when every name is valid, WP_Error otherwise.

Usage

$result = WP_REST_Attachments_Controller::validate_image_size_names( $value, $param );
$value(mixed) (required)
The image size name, or an array of names.
$param(string) (required)
Parameter name, used in the error messages.

Changelog

Since 7.1.0 Introduced.

WP_REST_Attachments_Controller::validate_image_size_names() code WP 7.1

private static function validate_image_size_names( $value, string $param ) {
	$special_sizes = self::get_special_image_sizes();
	$regular_sizes = array_values(
		array_diff(
			array_merge(
				array_keys( wp_get_registered_image_subsizes() ),
				// Not a registered sub-size, but stored as an ordinary
				// entry in the metadata 'sizes' array (PDF thumbnails).
				array( 'full' )
			),
			$special_sizes
		)
	);

	if ( is_string( $value ) ) {
		$items       = array( $value );
		$valid_sizes = array_merge( $regular_sizes, $special_sizes );
	} elseif ( is_array( $value ) ) {
		/**
		 * An array registers one sideloaded file under several size names,
		 * which only makes sense for regular sub-sizes: each special size
		 * names a single file with its own handling in
		 * {@see self::sideload_item()} and its own metadata key in
		 * {@see self::finalize_item()}. Rejecting them here is what lets the
		 * array branches in both methods treat an array as regular sizes.
		 */
		$items       = $value;
		$valid_sizes = $regular_sizes;
	} else {
		return new WP_Error(
			'rest_invalid_type',
			/* translators: %s: Parameter name. */
			sprintf( __( '%s must be a string or an array of strings.' ), $param )
		);
	}

	foreach ( $items as $item ) {
		if ( ! in_array( $item, $valid_sizes, true ) ) {
			return new WP_Error(
				'rest_not_in_enum',
				/* translators: %s: Parameter name. */
				sprintf( __( '%s contains an invalid image size.' ), $param )
			);
		}
	}

	return true;
}