Skip to content

Commit

Permalink
Move image conversion to new class
Browse files Browse the repository at this point in the history
So it can be re-used in other instances like showing the avatar, which
WordPress by default returns an <img> tag.

Fixes #1
  • Loading branch information
mjangda committed Sep 30, 2015
1 parent 4a2ee22 commit 697e449
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
32 changes: 23 additions & 9 deletions class-amp-content.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,34 @@ public function transform() {
// Convert HTML to AMP
// see https://github.com/ampproject/amphtml/blob/master/spec/amp-html-format.md#html-tags)

$content = $this->img_to_amp_img( $content );
$content = ( new AMP_Img_Converter )->convert( $content );

return $content;
}
}

abstract class AMP_Converter {
abstract public function convert( $content );

public function img_to_amp_img( $content ) {
if ( false === stripos( $content, '<img' ) ) {
public function has_tag( $content, $tag ) {
return false !== stripos( $content, sprintf( '<%s', $tag ) );
}

public function get_tags( $content, $tag ) {
preg_match_all( '#<' . $tag . '[^>]+?[\/]?>#i', $content, $tags, PREG_SET_ORDER );
return $tags;
}
}

class AMP_Img_Converter extends AMP_Converter {
public static $tag = 'img';

public function convert( $content ) {
if ( ! $this->has_tag( $content, self::$tag ) ) {
return $content;
}

preg_match_all( '#<img[^>]+?[\/]?>#i', $content, $images, PREG_SET_ORDER );
$images = $this->get_tags( $content, self::$tag );
if ( empty( $images ) ) {
return $content;
}
Expand All @@ -39,9 +56,6 @@ public function img_to_amp_img( $content ) {
$name = $attribute['name'];
$value = $attribute['value'];

// TODO: srcset
// TODO: handle when width and height are missing

switch ( $name ) {
case 'src':
case 'alt':
Expand All @@ -55,9 +69,9 @@ public function img_to_amp_img( $content ) {

}

$new_img .= ' />';
$new_img .= '></amp-img>';

$old_img_pattern = '#' . preg_quote( $old_img ) . '#';
$old_img_pattern = '~' . preg_quote( $old_img, '~' ) . '~';
$content = preg_replace( $old_img_pattern, $new_img, $content, 1 );
}

Expand Down
4 changes: 3 additions & 1 deletion class-amp-post.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ function get_metadata() {
}

function get_author_avatar( $size = 24 ) {
return get_avatar( $this->author->user_email, 24 );
$avatar_html = get_avatar( $this->author->user_email, 24 );

return ( new AMP_Img_Converter )->convert( $avatar_html );
}

function get_author_name() {
Expand Down
2 changes: 1 addition & 1 deletion template.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
a:focus {
color: #33bbe3;
}
.avatar {
.byline amp-img {
border-radius: 50%;
border: 0;
background: #f3f6f8;
Expand Down

0 comments on commit 697e449

Please sign in to comment.