}
/**
- * Generate a srcset attribute value from an array mapping pixel densities
- * to URLs. Note that srcset supports width and height values as well, which
- * are not used here.
+ * Generate a srcset attribute value.
+ *
+ * Generates a srcset attribute value from an array mapping pixel densities
+ * to URLs. A trailing 'x' in pixel density values is optional.
+ *
+ * @note srcset width and height values are not supported.
+ *
+ * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
+ *
+ * @par Example:
+ * @code
+ * Html::srcSet( array(
+ * '1x' => 'standard.jpeg',
+ * '1.5x' => 'large.jpeg',
+ * '3x' => 'extra-large.jpeg',
+ * ) );
+ * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
+ * @endcode
*
* @param string[] $urls
* @return string
static function srcSet( $urls ) {
$candidates = array();
foreach ( $urls as $density => $url ) {
- // Image candidate syntax per current whatwg live spec, 2012-09-23:
- // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
- $candidates[] = "{$url} {$density}x";
+ // Cast density to float to strip 'x'.
+ $candidates[] = $url . ' ' . (float)$density . 'x';
}
return implode( ", ", $candidates );
}
'Label wrapper'
);
}
+
+ public static function provideSrcSetImages() {
+ return array(
+ array( array(), '', 'when there are no images, return empty string' ),
+ array(
+ array( '1x' => '1x.png', '1.5x' => '1_5x.png', '2x' => '2x.png' ),
+ '1x.png 1x, 1_5x.png 1.5x, 2x.png 2x',
+ 'pixel depth keys may include a trailing "x"'
+ ),
+ array(
+ array( '1' => '1x.png', '1.5' => '1_5x.png', '2' => '2x.png' ),
+ '1x.png 1x, 1_5x.png 1.5x, 2x.png 2x',
+ 'pixel depth keys may omit a trailing "x"'
+ ),
+ );
+ }
+
+ /**
+ * @dataProvider provideSrcSetImages
+ * @covers Html::srcSet
+ */
+ public function testSrcSet( $images, $expected, $message ) {
+ $this->assertEquals( Html::srcSet( $images ), $expected, $message );
+ }
}
class HtmlTestValue {