Completed
Push — add/gutenblock-simple-payments ( 3a1a65...8a2d19 )
by
unknown
08:56 queued 55s
created

Jetpack_Simple_Payments::render_gutenberg_block()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 68
Code Lines 44

Duplication

Lines 3
Ratio 4.41 %

Importance

Changes 0
Metric Value
cc 4
eloc 44
nc 8
nop 1
dl 3
loc 68
rs 8.7864
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
 * Simple Payments lets users embed a PayPal button fully integrated with wpcom to sell products on the site.
4
 * This is not a proper module yet, because not all the pieces are in place. Until everything is shipped, it can be turned
5
 * into module that can be enabled/disabled.
6
*/
7
class Jetpack_Simple_Payments {
8
	// These have to be under 20 chars because that is CPT limit.
9
	static $post_type_order = 'jp_pay_order';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $post_type_order.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
10
	static $post_type_product = 'jp_pay_product';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $post_type_product.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
11
12
	static $shortcode = 'simple-payment';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $shortcode.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
13
14
	static $css_classname_prefix = 'jetpack-simple-payments';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $css_classname_prefix.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
15
16
	// Increase this number each time there's a change in CSS or JS to bust cache.
17
	static $version = '0.25';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $version.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
18
19
	// Classic singleton pattern:
20
	private static $instance;
21
22
	private function __construct() {}
23
24
	static function getInstance() {
25
		if ( ! self::$instance ) {
26
			self::$instance = new self();
27
			self::$instance->register_init_hook();
28
		}
29
		return self::$instance;
30
	}
31
32
	private function register_scripts() {
33
		/**
34
		 * Paypal heavily discourages putting that script in your own server:
35
		 * @see https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/
36
		 */
37
		wp_register_script( 'paypal-checkout-js', 'https://www.paypalobjects.com/api/checkout.js', array(), null, true );
38
		wp_register_script( 'paypal-express-checkout', plugins_url( '/paypal-express-checkout.js', __FILE__ ),
39
			array( 'jquery', 'paypal-checkout-js' ), self::$version );
40
	}
41
42
	private function register_init_hook() {
43
		add_action( 'init', array( $this, 'init_hook_action' ) );
44
	}
45
46
	private function register_shortcode() {
47
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
48
	}
49
50
	public function init_hook_action() {
51
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
52
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
53
		$this->register_scripts();
54
		$this->register_shortcode();
55
		$this->register_gutenberg_block();
56
		$this->setup_cpts();
57
		$this->setup_meta_fields_for_rest();
58
59
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
60
	}
61
62
	private function register_gutenberg_block() {
63
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
64
		add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) );
65
66
		if ( ! is_admin() ) {
67
			register_block_type( 'jetpack/simple-payments-button', array(
68
				'render_callback' => array( $this, 'render_gutenberg_block' ),
69
			) );
70
		}
71
	}
72
73
	public function enqueue_block_editor_assets() {
74
		wp_enqueue_script(
75
			'gutenberg-simple-payments-button',
76
			plugins_url( 'simple-payments-block.js', __FILE__ ),
77
			array( 'wp-blocks', 'wp-element' )
78
		);
79
	}
80
81
	public function enqueue_block_assets() {
82
		if ( is_admin() ) {
83
			// Load the styles just in admin area and rely on custom PayPal
84
			// styles on front end
85
			wp_enqueue_style(
86
				'gutenberg-simple-payments-button-styles',
87
				plugins_url( 'simple-payments-block.css', __FILE__ ),
88
				array(),
89
				JETPACK__VERSION
90
			);
91
92
			// Reuse some front end styles in editor
93
			wp_enqueue_style(
94
				'simple-payments',
95
				plugins_url( 'simple-payments.css', __FILE__ ),
96
				array( 'dashicons' )
97
			);
98
		}
99
	}
100
101
	/**
102
	 * This function is mostly similar on existing output_shortcode(),
103
	 * with some elements like product title and description removed,
104
	 * since we don't want to include these as part of the block.
105
	 *
106
	 * @param array $attributes Array of Gutenberg block attributes
107
	 *
108
	 * @return string HTML to be rendered on front end
109
	 */
110
	public function render_gutenberg_block( $attributes ) {
111
		$attribute_defaults = array(
112
			'price' => 1,
113
			'currency' => 'US',
114
			'showIcons' => true,
115
			'multiple' => false,
116
		);
117
118
		// Gutenberg won't persist attribute default values so we
119
		// have to provide defaults here again.
120
		$attributes = array_merge( $attribute_defaults, $attributes );
121
122
		$data = array();
123
		$data['id'] = $attributes['id'];
124
		$data['multiple'] = $attributes['multiple'];
125
		$data['dom_id'] = uniqid( self::$css_classname_prefix . '-' . $data['id'] . '_', true );
126
		$data['class'] = self::$css_classname_prefix . '-' . $data['id'];
127
		$data['price'] = $attributes['price'];
128
		$data['blog_id'] = $this->get_blog_id();
129
		$data['currency'] = $attributes['currency'];
130
131
		$currency_symbols = array(
132
			'US' => '$',
133
			'EU' => '€',
134
			'CA' => '$',
135
		);
136
137
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
138
			wp_enqueue_script( 'paypal-express-checkout' );
139
		}
140 View Code Duplication
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
141
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
142
		}
143
144
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
145
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
146
			esc_js( $data['blog_id'] ),
147
			esc_js( $data['id'] ),
148
			esc_js( $data['dom_id'] ),
149
			esc_js( $data['multiple'] )
150
		) );
151
152
		$css_prefix = self::$css_classname_prefix;
153
		$display_price = $currency_symbols[ $data['currency'] ] . $data['price'];
154
155
		if ( $data['multiple'] ) {
156
			$items = "
157
				<div class='${css_prefix}-items'>
158
					<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
159
				</div>
160
				";
161
		}
162
163
		return "
164
			<div class='{$data['class']} ${css_prefix}-wrapper'>
165
				<div class='${css_prefix}-product'>
166
					<div class='${css_prefix}-details'>
167
						<div class='${css_prefix}-price'><p>{$display_price}</p></div>
168
						<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
169
						<div class='${css_prefix}-purchase-box'>
170
							{$items}
0 ignored issues
show
Bug introduced by
The variable $items does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
171
							<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
172
						</div>
173
					</div>
174
				</div>
175
			</div>
176
		";
177
	}
178
179
	function remove_auto_paragraph_from_product_description( $content ) {
180
		if ( get_post_type() === self::$post_type_product ) {
181
			remove_filter( 'the_content', 'wpautop' );
182
		}
183
184
		return $content;
185
	}
186
187
	function get_blog_id() {
188
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
189
			return get_current_blog_id();
190
		}
191
192
		return Jetpack_Options::get_option( 'id' );
193
	}
194
195
	function parse_shortcode( $attrs, $content = false ) {
196
		if ( empty( $attrs['id'] ) ) {
197
			return;
198
		}
199
		$product = get_post( $attrs['id'] );
200
		if ( ! $product || is_wp_error( $product ) ) {
201
			return;
202
		}
203
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
204
			return;
205
		}
206
207
		// We allow for overriding the presentation labels
208
		$data = shortcode_atts( array(
209
			'blog_id'     => $this->get_blog_id(),
210
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
211
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
212
			'title'       => get_the_title( $product ),
213
			'description' => $product->post_content,
214
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
215
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
216
		), $attrs );
217
218
		$data['price'] = $this->format_price(
219
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
220
			get_post_meta( $product->ID, 'spay_price', true ),
221
			get_post_meta( $product->ID, 'spay_currency', true ),
222
			$data
223
		);
224
225
		$data['id'] = $attrs['id'];
226
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
227
			wp_enqueue_script( 'paypal-express-checkout' );
228
		}
229 View Code Duplication
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
230
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
231
		}
232
233
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
234
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
235
			esc_js( $data['blog_id'] ),
236
			esc_js( $attrs['id'] ),
237
			esc_js( $data['dom_id'] ),
238
			esc_js( $data['multiple'] )
239
		) );
240
241
		return $this->output_shortcode( $data );
242
	}
243
244
	function output_shortcode( $data ) {
245
		$items = '';
246
		$css_prefix = self::$css_classname_prefix;
247
248
		if ( $data['multiple'] ) {
249
			$items="<div class='${css_prefix}-items'>
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 0 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
250
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
251
			</div>";
252
		}
253
		$image = "";
254
		if( has_post_thumbnail( $data['id'] ) ) {
255
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
256
		}
257
		return "
258
<div class='{$data['class']} ${css_prefix}-wrapper'>
259
	<div class='${css_prefix}-product'>
260
		{$image}
261
		<div class='${css_prefix}-details'>
262
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
263
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
264
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
265
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
266
			<div class='${css_prefix}-purchase-box'>
267
				{$items}
268
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
269
			</div>
270
		</div>
271
	</div>
272
</div>
273
		";
274
	}
275
276
	function format_price( $formatted_price, $price, $currency, $all_data ) {
277
		if ( $formatted_price ) {
278
			return $formatted_price;
279
		}
280
		return "$price $currency";
281
	}
282
283
	/**
284
	 * Allows custom post types to be used by REST API.
285
	 * @param $post_types
286
	 * @see hook 'rest_api_allowed_post_types'
287
	 * @return array
288
	 */
289
	function allow_rest_api_types( $post_types ) {
290
		$post_types[] = self::$post_type_order;
291
		$post_types[] = self::$post_type_product;
292
		return $post_types;
293
	}
294
295
	function allow_sync_post_meta( $post_meta ) {
296
		return array_merge( $post_meta, array(
297
			'spay_paypal_id',
298
			'spay_status',
299
			'spay_product_id',
300
			'spay_quantity',
301
			'spay_price',
302
			'spay_customer_email',
303
			'spay_currency',
304
			'spay_cta',
305
			'spay_email',
306
			'spay_multiple',
307
			'spay_formatted_price',
308
		) );
309
	}
310
311
	/**
312
	 * Sets up the custom post types for the module.
313
	 */
314
	function setup_cpts() {
315
316
		/*
317
		 * ORDER data structure. holds:
318
		 * title = customer_name | 4xproduct_name
319
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
320
		 * metadata:
321
		 * spay_paypal_id - paypal id of transaction
322
		 * spay_status
323
		 * spay_product_id - post_id of bought product
324
		 * spay_quantity - quantity of product
325
		 * spay_price - item price at the time of purchase
326
		 * spay_customer_email - customer email
327
		 * ... (WIP)
328
		 */
329
		$order_capabilities = array(
330
			'edit_post'             => 'edit_posts',
331
			'read_post'             => 'read_private_posts',
332
			'delete_post'           => 'delete_posts',
333
			'edit_posts'            => 'edit_posts',
334
			'edit_others_posts'     => 'edit_others_posts',
335
			'publish_posts'         => 'publish_posts',
336
			'read_private_posts'    => 'read_private_posts',
337
		);
338
		$order_args = array(
339
			'label'                 => esc_html__( 'Order', 'jetpack' ),
340
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
341
			'supports'              => array( 'custom-fields', 'excerpt' ),
342
			'hierarchical'          => false,
343
			'public'                => false,
344
			'show_ui'               => false,
345
			'show_in_menu'          => false,
346
			'show_in_admin_bar'     => false,
347
			'show_in_nav_menus'     => false,
348
			'can_export'            => true,
349
			'has_archive'           => false,
350
			'exclude_from_search'   => true,
351
			'publicly_queryable'    => false,
352
			'rewrite'               => false,
353
			'capabilities'          => $order_capabilities,
354
			'show_in_rest'          => true,
355
		);
356
		register_post_type( self::$post_type_order, $order_args );
357
358
		/*
359
		 * PRODUCT data structure. Holds:
360
		 * title - title
361
		 * content - description
362
		 * thumbnail - image
363
		 * metadata:
364
		 * spay_price - price
365
		 * spay_formatted_price
366
		 * spay_currency - currency code
367
		 * spay_cta - text with "Buy" or other CTA
368
		 * spay_email - paypal email
369
		 * spay_multiple - allow for multiple items
370
		 * spay_status - status. { enabled | disabled }
371
		 */
372
		$product_capabilities = array(
373
			'edit_post'             => 'edit_posts',
374
			'read_post'             => 'read_private_posts',
375
			'delete_post'           => 'delete_posts',
376
			'edit_posts'            => 'edit_posts',
377
			'edit_others_posts'     => 'edit_others_posts',
378
			'publish_posts'         => 'publish_posts',
379
			'read_private_posts'    => 'read_private_posts',
380
		);
381
		$product_args = array(
382
			'label'                 => esc_html__( 'Product', 'jetpack' ),
383
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
384
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields' ),
385
			'hierarchical'          => false,
386
			'public'                => false,
387
			'show_ui'               => false,
388
			'show_in_menu'          => false,
389
			'show_in_admin_bar'     => false,
390
			'show_in_nav_menus'     => false,
391
			'can_export'            => true,
392
			'has_archive'           => false,
393
			'exclude_from_search'   => true,
394
			'publicly_queryable'    => false,
395
			'rewrite'               => false,
396
			'capabilities'          => $product_capabilities,
397
			'show_in_rest'          => true,
398
		);
399
		register_post_type( self::$post_type_product, $product_args );
400
	}
401
402
	public function update_post_meta_for_api( $meta_arr, $object ) {
403
		//get the id of the post object array
404
		$post_id = $object->ID;
405
406
		foreach( $meta_arr as $meta_key => $meta_val ) {
407
			update_post_meta( $post_id, $meta_key, $meta_val );
408
		}
409
410
		return true;
411
	}
412
413
	function setup_meta_fields_for_rest() {
414
		$args = array(
415
		   'update_callback' => array( $this, 'update_post_meta_for_api'),
416
		);
417
418
		register_rest_field( self::$post_type_product, 'meta', $args );
419
	}
420
421
}
422
Jetpack_Simple_Payments::getInstance();
423