Skip to content

Commit

Permalink
Merge pull request #793 from Automattic/update/img-dimension-back-compat
Browse files Browse the repository at this point in the history
Support extracting dimensions for single URLs
  • Loading branch information
westonruter committed Aug 3, 2018
2 parents f6b28d6 + cb30fca commit 06918f1
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
22 changes: 21 additions & 1 deletion includes/utils/class-amp-image-dimension-extractor.php
Expand Up @@ -5,13 +5,27 @@ class AMP_Image_Dimension_Extractor {
const STATUS_FAILED_LAST_ATTEMPT = 'failed';
const STATUS_IMAGE_EXTRACTION_FAILED = 'failed';

static public function extract( $urls ) {
/**
* Extract dimensions from image URLs.
*
* @since 0.2
*
* @param array|string $urls Array of URLs to extract dimensions from, or a single URL string.
* @return array|string Extracted dimensions keyed by original URL, or else the single set of dimensions if one URL string is passed.
*/
public static function extract( $urls ) {
if ( ! self::$callbacks_registered ) {
self::register_callbacks();
}

$return_dimensions = array();

// Back-compat for users calling this method directly.
$is_single = is_string( $urls );
if ( $is_single ) {
$urls = array( $urls );
}

// Normalize URLs and also track a map of normalized-to-original as we'll need it to reformat things when returning the data.
$url_map = array();
$normalized_urls = array();
Expand All @@ -22,6 +36,7 @@ static public function extract( $urls ) {
$normalized_urls[] = $normalized_url;
} else {
// This is not a URL we can extract dimensions from, so default to false.
$url_map[ $original_url ] = $original_url;
$return_dimensions[ $original_url ] = false;
}
}
Expand All @@ -35,6 +50,11 @@ static public function extract( $urls ) {
$return_dimensions[ $original_url ] = $dimension;
}

// Back-compat: just return the dimensions, not the full mapped array.
if ( $is_single ) {
return current( $return_dimensions );
}

return $return_dimensions;
}

Expand Down
29 changes: 29 additions & 0 deletions tests/test-amp-image-dimension-extractor.php
Expand Up @@ -36,6 +36,35 @@ public function disable_downloads() {
remove_all_filters( 'amp_extract_image_dimensions_batch' );
}

/**
* Test single url returns expected dimensions.
*
* @covers \AMP_Image_Dimension_Extractor::extract()
*/
public function test__single_url() {
add_action(
'amp_extract_image_dimensions_batch_callbacks_registered',
function() {
add_filter( 'amp_extract_image_dimensions_batch', function() {
return array(
'https://example.com/image.png' => array(
100,
101,
),
);
} );
},
9999 // Run after the `disable_downloads`.
);

$source_url = 'https://example.com/image.png';
$expected = array( 100, 101 );

$actual = AMP_Image_Dimension_Extractor::extract( $source_url );

$this->assertEquals( $expected, $actual );
}

/**
* Test where processed URLs should match originals.
*/
Expand Down

0 comments on commit 06918f1

Please sign in to comment.