": path } where is the * original's format (jpg, png, gif…; see ImageProcessor). Rendering used to * read only "jpg", so PNG/GIF posts rendered without any . */ final class VariantFormat { /** Native (non-WebP) keys in order of preference. */ private const NATIVE_KEYS = [ 'jpg', 'jpeg', 'png', 'gif' ]; /** * Relative path of the non-WebP file (the fallback), or the WebP * one when that is all there is; '' when the entry has no usable file. * * @param mixed $formats One variant entry. */ public static function fallbackPath( $formats ): string { if ( ! is_array( $formats ) ) { return ''; } foreach ( self::NATIVE_KEYS as $key ) { if ( isset( $formats[ $key ] ) && is_string( $formats[ $key ] ) && '' !== $formats[ $key ] ) { return $formats[ $key ]; } } return isset( $formats['webp'] ) && is_string( $formats['webp'] ) ? $formats['webp'] : ''; } /** * Largest variant no wider than $maxWidth that has a usable file * (falls back to the smallest one when all are wider). * * @param array $variants Variant map keyed by width. */ public static function bestPath( array $variants, int $maxWidth = 1080 ): string { $widths = array_map( 'intval', array_keys( $variants ) ); rsort( $widths ); $smallest = ''; foreach ( $widths as $w ) { $path = self::fallbackPath( $variants[ $w ] ?? $variants[ (string) $w ] ?? null ); if ( '' === $path ) { continue; } if ( $w <= $maxWidth ) { return $path; } $smallest = $path; } return $smallest; } /** * All stored sizes as an ("url 320w, url 640w, …"), WebP * where a size has it, else the native format. Lets the browser pick the * size for the viewport and pixel density instead of the largest file. * * @param array $variants Width => formats. * @param string $baseUrl Uploads base URL (with trailing slash). */ public static function srcset( array $variants, string $baseUrl ): string { $parts = []; foreach ( $variants as $width => $formats ) { $w = (int) $width; if ( $w <= 0 || ! is_array( $formats ) ) { continue; } $path = isset( $formats['webp'] ) && is_string( $formats['webp'] ) && '' !== $formats['webp'] ? $formats['webp'] : self::fallbackPath( $formats ); if ( '' !== $path ) { $parts[ $w ] = esc_url( $baseUrl . $path ) . ' ' . $w . 'w'; } } ksort( $parts ); return implode( ', ', $parts ); } }