Completed
Push — instant-search-master ( a786a9...893b7c )
by
unknown
85:32 queued 79:17
created

Jetpack_Memberships::render_button()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 73

Duplication

Lines 18
Ratio 24.66 %

Importance

Changes 0
Metric Value
cc 11
nc 11
nop 1
dl 18
loc 73
rs 6.4424
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
 * Jetpack_Memberships: wrapper for memberships functions.
4
 *
5
 * @package    Jetpack
6
 * @since      7.3.0
7
 */
8
9
/**
10
 * Class Jetpack_Memberships
11
 * This class represents the Memberships functionality.
12
 */
13
class Jetpack_Memberships {
14
	/**
15
	 * CSS class prefix to use in the styling.
16
	 *
17
	 * @var string
18
	 */
19
	public static $css_classname_prefix = 'jetpack-memberships';
20
	/**
21
	 * Our CPT type for the product (plan).
22
	 *
23
	 * @var string
24
	 */
25
	public static $post_type_plan = 'jp_mem_plan';
26
	/**
27
	 * Option that will store currently set up account (Stripe etc) id for memberships.
28
	 *
29
	 * @var string
30
	 */
31
	public static $connected_account_id_option_name = 'jetpack-memberships-connected-account-id';
32
	/**
33
	 * Button block type to use.
34
	 *
35
	 * @var string
36
	 */
37
	private static $button_block_name = 'recurring-payments';
38
39
	/**
40
	 * These are defaults for wp_kses ran on the membership button.
41
	 *
42
	 * @var array
43
	 */
44
	private static $tags_allowed_in_the_button = array( 'br' => array() );
45
46
	/**
47
	 * The minimum required plan for this Gutenberg block.
48
	 *
49
	 * @var string Plan slug
50
	 */
51
	private static $required_plan;
52
53
	/**
54
	 * Track recurring payments block registration.
55
	 *
56
	 * @var boolean True if block registration has been executed.
57
	 */
58
	private static $has_registered_block = false;
59
60
	/**
61
	 * Classic singleton pattern
62
	 *
63
	 * @var Jetpack_Memberships
64
	 */
65
	private static $instance;
66
67
	/**
68
	 * Jetpack_Memberships constructor.
69
	 */
70
	private function __construct() {}
71
72
	/**
73
	 * The actual constructor initializing the object.
74
	 *
75
	 * @return Jetpack_Memberships
76
	 */
77 View Code Duplication
	public static function get_instance() {
78
		if ( ! self::$instance ) {
79
			self::$instance = new self();
80
			self::$instance->register_init_hook();
81
			// Yes, `personal-bundle` with a dash, `jetpack_personal` with an underscore. Check the v1.5 endpoint to verify.
82
			self::$required_plan = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? 'personal-bundle' : 'jetpack_personal';
83
		}
84
85
		return self::$instance;
86
	}
87
	/**
88
	 * Get the map that defines the shape of CPT post. keys are names of fields and
89
	 * 'meta' is the name of actual WP post meta field that corresponds.
90
	 *
91
	 * @return array
92
	 */
93
	private static function get_plan_property_mapping() {
94
		$meta_prefix = 'jetpack_memberships_';
95
		$properties  = array(
96
			'price'    => array(
97
				'meta' => $meta_prefix . 'price',
98
			),
99
			'currency' => array(
100
				'meta' => $meta_prefix . 'currency',
101
			),
102
		);
103
		return $properties;
104
	}
105
106
	/**
107
	 * Inits further hooks on init hook.
108
	 */
109
	private function register_init_hook() {
110
		add_action( 'init', array( $this, 'init_hook_action' ) );
111
		add_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_gutenberg_block' ) );
112
	}
113
114
	/**
115
	 * Actual hooks initializing on init.
116
	 */
117
	public function init_hook_action() {
118
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
119
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
120
		$this->setup_cpts();
121
	}
122
123
	/**
124
	 * Sets up the custom post types for the module.
125
	 */
126
	private function setup_cpts() {
127
		/*
128
		 * PLAN data structure.
129
		 */
130
		$capabilities = array(
131
			'edit_post'          => 'edit_posts',
132
			'read_post'          => 'read_private_posts',
133
			'delete_post'        => 'delete_posts',
134
			'edit_posts'         => 'edit_posts',
135
			'edit_others_posts'  => 'edit_others_posts',
136
			'publish_posts'      => 'publish_posts',
137
			'read_private_posts' => 'read_private_posts',
138
		);
139
		$order_args   = array(
140
			'label'               => esc_html__( 'Plan', 'jetpack' ),
141
			'description'         => esc_html__( 'Recurring Payments plans', 'jetpack' ),
142
			'supports'            => array( 'title', 'custom-fields', 'content' ),
143
			'hierarchical'        => false,
144
			'public'              => false,
145
			'show_ui'             => false,
146
			'show_in_menu'        => false,
147
			'show_in_admin_bar'   => false,
148
			'show_in_nav_menus'   => false,
149
			'can_export'          => true,
150
			'has_archive'         => false,
151
			'exclude_from_search' => true,
152
			'publicly_queryable'  => false,
153
			'rewrite'             => false,
154
			'capabilities'        => $capabilities,
155
			'show_in_rest'        => false,
156
		);
157
		register_post_type( self::$post_type_plan, $order_args );
158
	}
159
160
	/**
161
	 * Allows custom post types to be used by REST API.
162
	 *
163
	 * @param array $post_types - other post types.
164
	 *
165
	 * @see hook 'rest_api_allowed_post_types'
166
	 * @return array
167
	 */
168
	public function allow_rest_api_types( $post_types ) {
169
		$post_types[] = self::$post_type_plan;
170
171
		return $post_types;
172
	}
173
174
	/**
175
	 * Allows custom meta fields to sync.
176
	 *
177
	 * @param array $post_meta - previously changet post meta.
178
	 *
179
	 * @return array
180
	 */
181
	public function allow_sync_post_meta( $post_meta ) {
182
		$meta_keys = array_map(
183
			array( $this, 'return_meta' ),
184
			$this->get_plan_property_mapping()
185
		);
186
		return array_merge( $post_meta, array_values( $meta_keys ) );
187
	}
188
189
	/**
190
	 * This returns meta attribute of passet array.
191
	 * Used for array functions.
192
	 *
193
	 * @param array $map - stuff.
194
	 *
195
	 * @return mixed
196
	 */
197
	public function return_meta( $map ) {
198
		return $map['meta'];
199
	}
200
	/**
201
	 * Callback that parses the membership purchase shortcode.
202
	 *
203
	 * @param array $attrs - attributes in the shortcode. `id` here is the CPT id of the plan.
204
	 *
205
	 * @return string|void
206
	 */
207
	public function render_button( $attrs ) {
208
		Jetpack_Gutenberg::load_assets_as_required( self::$button_block_name, array( 'thickbox', 'wp-polyfill' ) );
209
210
		if ( empty( $attrs['planId'] ) ) {
211
			return;
212
		}
213
		$plan_id = intval( $attrs['planId'] );
214
		$product = get_post( $plan_id );
215
		if ( ! $product || is_wp_error( $product ) ) {
216
			return;
217
		}
218
		if ( $product->post_type !== self::$post_type_plan || 'publish' !== $product->post_status ) {
219
			return;
220
		}
221
222
		$data = array(
223
			'blog_id'      => self::get_blog_id(),
224
			'plan_id'      => $plan_id,
225
			'button_label' => __( 'Your contribution', 'jetpack' ),
226
		);
227
228
		if ( isset( $attrs['submitButtonText'] ) ) {
229
			$data['button_label'] = $attrs['submitButtonText'];
230
		}
231
		$button_styles = array();
232 View Code Duplication
		if ( ! empty( $attrs['customBackgroundButtonColor'] ) ) {
233
			array_push(
234
				$button_styles,
235
				sprintf(
236
					'background-color: %s',
237
					sanitize_hex_color( $attrs['customBackgroundButtonColor'] )
238
				)
239
			);
240
		}
241 View Code Duplication
		if ( ! empty( $attrs['customTextButtonColor'] ) ) {
242
			array_push(
243
				$button_styles,
244
				sprintf(
245
					'color: %s',
246
					sanitize_hex_color( $attrs['customTextButtonColor'] )
247
				)
248
			);
249
		}
250
		$button_styles = implode( ';', $button_styles );
251
		add_thickbox();
252
		global $wp;
253
254
		$button_url = add_query_arg(
255
			array(
256
				'blog'     => esc_attr( $data['blog_id'] ),
257
				'plan'     => esc_attr( $data['plan_id'] ),
258
				'lang'     => esc_attr( get_locale() ),
259
				'pid'      => esc_attr( get_the_ID() ), // Needed for analytics purposes.
260
				'redirect' => esc_attr( rawurlencode( home_url( $wp->request ) ) ), // Needed for redirect back in case of redirect-based flow.
261
			),
262
			'https://subscribe.wordpress.com/memberships/'
263
		);
264
		return sprintf(
265
			'<div class="%1$s"><a role="button" %6$s href="%2$s" class="%3$s" style="%4$s">%5$s</a></div>',
266
			esc_attr(
267
				Jetpack_Gutenberg::block_classes(
268
					self::$button_block_name,
269
					$attrs,
270
					array( 'wp-block-button' )
271
				)
272
			),
273
			esc_url( $button_url ),
274
			isset( $attrs['submitButtonClasses'] ) ? esc_attr( $attrs['submitButtonClasses'] ) : 'wp-block-button__link',
275
			esc_attr( $button_styles ),
276
			wp_kses( $data['button_label'], self::$tags_allowed_in_the_button ),
277
			isset( $attrs['submitButtonAttributes'] ) ? sanitize_text_field( $attrs['submitButtonAttributes'] ) : '' // Needed for arbitrary target=_blank on WPCOM VIP.
278
		);
279
	}
280
281
	/**
282
	 * Get current blog id.
283
	 *
284
	 * @return int
285
	 */
286
	public static function get_blog_id() {
287
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
288
			return get_current_blog_id();
289
		}
290
291
		return Jetpack_Options::get_option( 'id' );
292
	}
293
294
	/**
295
	 * Get the id of the connected payment acount (Stripe etc).
296
	 *
297
	 * @return int|void
298
	 */
299
	public static function get_connected_account_id() {
300
		return get_option( self::$connected_account_id_option_name );
301
	}
302
303
	/**
304
	 * Whether Recurring Payments are enabled.
305
	 *
306
	 * @return bool
307
	 */
308
	public static function is_enabled_jetpack_recurring_payments() {
309
		// For WPCOM sites.
310 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_any_blog_stickers' ) ) {
311
			$site_id = get_current_blog_id();
312
			return has_any_blog_stickers( array( 'personal-plan', 'premium-plan', 'business-plan', 'ecommerce-plan' ), $site_id );
313
		}
314
315
		// For Jetpack sites.
316
		return Jetpack::is_active() && (
317
			/** This filter is documented in class.jetpack-gutenberg.php */
318
			! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ) || // Remove when the default becomes `true`.
319
			Jetpack_Plan::supports( 'recurring-payments' )
320
		);
321
	}
322
323
	/**
324
	 * Register the Recurring Payments Gutenberg block
325
	 */
326
	public function register_gutenberg_block() {
327
		// This gate was introduced to prevent duplicate registration. A race condition exists where
328
		// the registration that happens via extensions/blocks/recurring-payments/recurring-payments.php
329
		// was adding the registration action after the action had been run in some contexts.
330
		if ( self::$has_registered_block ) {
331
			return;
332
		}
333
334
		if ( self::is_enabled_jetpack_recurring_payments() ) {
335
			jetpack_register_block(
336
				'jetpack/recurring-payments',
337
				array(
338
					'render_callback' => array( $this, 'render_button' ),
339
				)
340
			);
341
		} else {
342
			Jetpack_Gutenberg::set_extension_unavailable(
343
				'jetpack/recurring-payments',
344
				'missing_plan',
345
				array(
346
					'required_feature' => 'memberships',
347
					'required_plan'    => self::$required_plan,
348
				)
349
			);
350
		}
351
352
		self::$has_registered_block = true;
353
	}
354
}
355
Jetpack_Memberships::get_instance();
356