1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Image Compare Block. |
4
|
|
|
* |
5
|
|
|
* @since 8.6 |
6
|
|
|
* |
7
|
|
|
* @package Jetpack |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Automattic\Jetpack\Extensions\ImageCompare; |
11
|
|
|
|
12
|
|
|
use Jetpack_AMP_Support; |
13
|
|
|
use Jetpack_Gutenberg; |
14
|
|
|
|
15
|
|
|
const FEATURE_NAME = 'image-compare'; |
16
|
|
|
const BLOCK_NAME = 'jetpack/' . FEATURE_NAME; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Registers the block for use in Gutenberg |
20
|
|
|
* This is done via an action so that we can disable |
21
|
|
|
* registration if we need to. |
22
|
|
|
*/ |
23
|
|
|
function register_block() { |
24
|
|
|
jetpack_register_block( |
25
|
|
|
BLOCK_NAME, |
26
|
|
|
array( 'render_callback' => __NAMESPACE__ . '\load_assets' ) |
27
|
|
|
); |
28
|
|
|
} |
29
|
|
|
add_action( 'init', __NAMESPACE__ . '\register_block' ); |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Image Compare block registration/dependency declaration. |
33
|
|
|
* |
34
|
|
|
* @param array $attr Array containing the image-compare block attributes. |
35
|
|
|
* @param string $content String containing the image-compare block content. |
36
|
|
|
* |
37
|
|
|
* @return string |
38
|
|
|
*/ |
39
|
|
View Code Duplication |
function load_assets( $attr, $content ) { |
|
|
|
|
40
|
|
|
Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME ); |
41
|
|
|
if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) { |
42
|
|
|
return render_amp( $attr ); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $content; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Render image compare block for AMP |
51
|
|
|
* |
52
|
|
|
* @param array $attr Array containing the image-compare block attributes. |
53
|
|
|
* |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
function render_amp( $attr ) { |
57
|
|
|
$img_before = $attr['imageBefore']; |
58
|
|
|
$img_after = $attr['imageAfter']; |
59
|
|
|
|
60
|
|
|
return sprintf( |
61
|
|
|
'<amp-image-slider layout="responsive" width="%1$d" height="%2$d"> <amp-img id="%3$d" src="%4$s" alt="%5$s" layout="fill"></amp-img> <amp-img id="%6$d" src="%7$s" alt="%8$s" layout="fill"></amp-img></amp-image-slider>', |
62
|
|
|
absint( $img_before['width'] ), |
63
|
|
|
absint( $img_before['height'] ), |
64
|
|
|
absint( $img_before['id'] ), |
65
|
|
|
esc_url( $img_before['url'] ), |
66
|
|
|
esc_attr( $img_before['alt'] ), |
67
|
|
|
absint( $img_after['id'] ), |
68
|
|
|
esc_url( $img_after['url'] ), |
69
|
|
|
esc_attr( $img_after['alt'] ) |
70
|
|
|
); |
71
|
|
|
} |
72
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.