Completed
Push — fix/amp-map-no-ssl ( 67e248 )
by
unknown
07:57
created

map.php ➔ load_assets()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 2
dl 0
loc 55
rs 8.9818
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Map block.
4
 *
5
 * @since 6.8.0
6
 *
7
 * @package Jetpack
8
 */
9
10
namespace Automattic\Jetpack\Extensions\Map;
11
12
use Automattic\Jetpack\Tracking;
13
use Jetpack;
14
use Jetpack_AMP_Support;
15
use Jetpack_Gutenberg;
16
use Jetpack_Mapbox_Helper;
17
use Jetpack_Options;
18
19
const FEATURE_NAME = 'map';
20
const BLOCK_NAME   = 'jetpack/' . FEATURE_NAME;
21
22
if ( ! class_exists( 'Jetpack_Mapbox_Helper' ) ) {
23
	\jetpack_require_lib( 'class-jetpack-mapbox-helper' );
24
}
25
26
/**
27
 * Registers the block for use in Gutenberg
28
 * This is done via an action so that we can disable
29
 * registration if we need to.
30
 */
31
function register_block() {
32
	jetpack_register_block(
33
		BLOCK_NAME,
34
		array(
35
			'render_callback' => __NAMESPACE__ . '\load_assets',
36
		)
37
	);
38
}
39
add_action( 'init', __NAMESPACE__ . '\register_block' );
40
41
/**
42
 * Record a Tracks event every time the Map block is loaded on WordPress.com and Atomic.
43
 *
44
 * @param string $access_token_source The Mapbox API access token source.
45
 */
46
function wpcom_load_event( $access_token_source ) {
47
	if ( 'wpcom' !== $access_token_source ) {
48
		return;
49
	}
50
51
	$event_name = 'map_block_mapbox_wpcom_key_load';
52
	if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
53
		jetpack_require_lib( 'tracks/client' );
54
		tracks_record_event( wp_get_current_user(), $event_name );
55
	} elseif ( jetpack_is_atomic_site() && Jetpack::is_active() ) {
56
		$tracking = new Tracking();
57
		$tracking->record_user_event( $event_name );
58
	}
59
}
60
61
/**
62
 * Map block registration/dependency declaration.
63
 *
64
 * @param array  $attr    Array containing the map block attributes.
65
 * @param string $content String containing the map block content.
66
 *
67
 * @return string
68
 */
69
function load_assets( $attr, $content ) {
70
	$access_token = Jetpack_Mapbox_Helper::get_access_token();
71
72
	wpcom_load_event( $access_token['source'] );
73
74
	if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
75
		// Get the original state.
76
		$scripts_queue = wp_scripts()->queue;
77
		$scripts_done  = wp_scripts()->done;
78
		$styles_queue  = wp_styles()->queue;
79
		$styles_done   = wp_styles()->done;
80
81
		// Empty out everything.
82
		wp_scripts()->queue = array();
83
		wp_scripts()->done  = array();
84
		wp_styles()->queue  = array();
85
		wp_styles()->done   = array();
86
87
		// Get what we need.
88
		ob_start();
89
		add_filter( 'jetpack_is_amp_request', '__return_false' );
90
		Jetpack_Gutenberg::load_assets_as_required( 'map' );
91
		wp_scripts()->do_items();
92
		wp_styles()->do_items();
93
		add_filter( 'jetpack_is_amp_request', '__return_true' );
94
		$assets_html = ob_get_clean();
95
96
		// Restore to the original state.
97
		wp_scripts()->queue = $scripts_queue;
98
		wp_scripts()->done  = $scripts_done;
99
		wp_styles()->queue  = $styles_queue;
100
		wp_styles()->done   = $styles_done;
101
102
		$html = sprintf(
103
			'<!DOCTYPE html><head><style>html, body { margin: 0; padding: 0; }</style>%s</head><body>%s</body>',
104
			$assets_html,
105
			preg_replace( '/(?<=<div\s)/', 'data-api-key="' . esc_attr( $access_token['key'] ) . '" ', $content, 1 )
106
		);
107
108
		$placeholder = preg_replace( '/(?<=<div\s)/', 'placeholder ', $content );
109
110
		// @todo Is intrinsic size right? Is content_width the right dimensions?
111
		return sprintf(
112
			'<amp-iframe srcdoc="%s" width="%d" height="%d" layout="intrinsic" allowfullscreen sandbox="allow-scripts">%s</amp-iframe>',
113
			htmlspecialchars( $html ),
114
			Jetpack::get_content_width(),
115
			Jetpack::get_content_width(),
116
			$placeholder
117
		);
118
	}
119
120
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME );
121
122
	return preg_replace( '/<div /', '<div data-api-key="' . esc_attr( $access_token['key'] ) . '" ', $content, 1 );
123
}
124
125
/**
126
 * Render a page containing only a single Map block.
127
 */
128
function render_single_block_page() {
129
	// phpcs:ignore WordPress.Security.NonceVerification
130
	$map_block_counter = isset( $_GET, $_GET['map-block-counter'] ) ? absint( $_GET['map-block-counter'] ) : null;
131
	// phpcs:ignore WordPress.Security.NonceVerification
132
	$map_block_post_id = isset( $_GET, $_GET['map-block-post-id'] ) ? absint( $_GET['map-block-post-id'] ) : null;
133
134
	if ( ! $map_block_counter || ! $map_block_post_id ) {
135
		return;
136
	}
137
138
	/* Create an array of all root-level DIVs that are Map Blocks */
139
	$post = get_post( $map_block_post_id );
140
141
	if ( ! class_exists( 'DOMDocument' ) ) {
142
		return;
143
	}
144
145
	$post_html = new \DOMDocument();
146
	/** This filter is already documented in core/wp-includes/post-template.php */
147
	$content = apply_filters( 'the_content', $post->post_content );
148
149
	/* Suppress warnings */
150
	libxml_use_internal_errors( true );
151
	@$post_html->loadHTML( $content ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
152
	libxml_use_internal_errors( false );
153
154
	$xpath     = new \DOMXPath( $post_html );
155
	$container = $xpath->query( '//div[ contains( @class, "wp-block-jetpack-map" ) ]' )->item( $map_block_counter - 1 );
156
157
	/* Check that we have a block matching the counter position */
158
	if ( ! $container ) {
159
		return;
160
	}
161
162
	/* Compile scripts and styles */
163
	ob_start();
164
165
	add_filter( 'jetpack_is_amp_request', '__return_false' );
166
167
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME );
168
	wp_scripts()->do_items();
169
	wp_styles()->do_items();
170
171
	add_filter( 'jetpack_is_amp_request', '__return_true' );
172
173
	$head_content = ob_get_clean();
174
175
	/* Put together a new complete document containing only the requested block markup and the scripts/styles needed to render it */
176
	$block_markup = $post_html->saveHTML( $container );
177
	$access_token = Jetpack_Mapbox_Helper::get_access_token();
178
	$page_html    = sprintf(
179
		'<!DOCTYPE html><head><style>html, body { margin: 0; padding: 0; }</style>%s</head><body>%s</body>',
180
		$head_content,
181
		preg_replace( '/(?<=<div\s)/', 'data-api-key="' . esc_attr( $access_token['key'] ) . '" ', $block_markup, 1 )
182
	);
183
	echo $page_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
184
	exit;
185
}
186
add_action( 'wp', __NAMESPACE__ . '\render_single_block_page' );
187