Completed
Push — updates/infinity-vanilla-js ( fda899...9466ff )
by
unknown
07:55
created

map.php ➔ render_single_block_page()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 16
nop 0
dl 0
loc 58
rs 7.983
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
		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
		static $map_block_counter = array();
76
77
		$id = get_the_ID();
78
		if ( ! isset( $map_block_counter[ $id ] ) ) {
79
			$map_block_counter[ $id ] = 0;
80
		}
81
		$map_block_counter[ $id ]++;
82
83
		$iframe_url = add_query_arg(
84
			array(
85
				'map-block-counter' => absint( $map_block_counter[ $id ] ),
86
				'map-block-post-id' => $id,
87
			),
88
			get_permalink()
89
		);
90
91
		$placeholder = preg_replace( '/(?<=<div\s)/', 'placeholder ', $content );
92
93
		return sprintf(
94
			'<amp-iframe src="%s" width="%d" height="%d" layout="responsive" allowfullscreen sandbox="allow-scripts">%s</amp-iframe>',
95
			esc_url( $iframe_url ),
96
			4,
97
			3,
98
			$placeholder
99
		);
100
	}
101
102
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME );
103
104
	return preg_replace( '/<div /', '<div data-api-key="' . esc_attr( $access_token['key'] ) . '" ', $content, 1 );
105
}
106
107
/**
108
 * Render a page containing only a single Map block.
109
 */
110
function render_single_block_page() {
111
	// phpcs:ignore WordPress.Security.NonceVerification
112
	$map_block_counter = isset( $_GET, $_GET['map-block-counter'] ) ? absint( $_GET['map-block-counter'] ) : null;
113
	// phpcs:ignore WordPress.Security.NonceVerification
114
	$map_block_post_id = isset( $_GET, $_GET['map-block-post-id'] ) ? absint( $_GET['map-block-post-id'] ) : null;
115
116
	if ( ! $map_block_counter || ! $map_block_post_id ) {
117
		return;
118
	}
119
120
	/* Create an array of all root-level DIVs that are Map Blocks */
121
	$post = get_post( $map_block_post_id );
122
123
	if ( ! class_exists( 'DOMDocument' ) ) {
124
		return;
125
	}
126
127
	$post_html = new \DOMDocument();
128
	/** This filter is already documented in core/wp-includes/post-template.php */
129
	$content = apply_filters( 'the_content', $post->post_content );
130
131
	/* Suppress warnings */
132
	libxml_use_internal_errors( true );
133
	@$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...
134
	libxml_use_internal_errors( false );
135
136
	$xpath     = new \DOMXPath( $post_html );
137
	$container = $xpath->query( '//div[ contains( @class, "wp-block-jetpack-map" ) ]' )->item( $map_block_counter - 1 );
138
139
	/* Check that we have a block matching the counter position */
140
	if ( ! $container ) {
141
		return;
142
	}
143
144
	/* Compile scripts and styles */
145
	ob_start();
146
147
	add_filter( 'jetpack_is_amp_request', '__return_false' );
148
149
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME );
150
	wp_scripts()->do_items();
151
	wp_styles()->do_items();
152
153
	add_filter( 'jetpack_is_amp_request', '__return_true' );
154
155
	$head_content = ob_get_clean();
156
157
	/* Put together a new complete document containing only the requested block markup and the scripts/styles needed to render it */
158
	$block_markup = $post_html->saveHTML( $container );
159
	$access_token = Jetpack_Mapbox_Helper::get_access_token();
160
	$page_html    = sprintf(
161
		'<!DOCTYPE html><head><style>html, body { margin: 0; padding: 0; }</style>%s</head><body>%s</body>',
162
		$head_content,
163
		preg_replace( '/(?<=<div\s)/', 'data-api-key="' . esc_attr( $access_token['key'] ) . '" ', $block_markup, 1 )
164
	);
165
	echo $page_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
166
	exit;
167
}
168
add_action( 'wp', __NAMESPACE__ . '\render_single_block_page' );
169