Completed
Push — add/gutenblock-simple-payments ( 8454b1...25b2a1 )
by
unknown
08:51
created

Jetpack_Simple_Payments::render_gutenberg_block()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 58
Code Lines 38

Duplication

Lines 3
Ratio 5.17 %

Importance

Changes 0
Metric Value
cc 4
eloc 38
nc 8
nop 1
dl 3
loc 58
rs 9.0077
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
			self::$instance->register_gutenberg_block();
29
		}
30
		return self::$instance;
31
	}
32
33
	private function register_scripts() {
34
		/**
35
		 * Paypal heavily discourages putting that script in your own server:
36
		 * @see https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/
37
		 */
38
		wp_register_script( 'paypal-checkout-js', 'https://www.paypalobjects.com/api/checkout.js', array(), null, true );
39
		wp_register_script( 'paypal-express-checkout', plugins_url( '/paypal-express-checkout.js', __FILE__ ),
40
			array( 'jquery', 'paypal-checkout-js' ), self::$version );
41
	}
42
43
	private function register_init_hook() {
44
		add_action( 'init', array( $this, 'init_hook_action' ) );
45
	}
46
47
	private function register_shortcode() {
48
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
49
	}
50
51
	public function init_hook_action() {
52
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
53
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
54
		$this->register_scripts();
55
		$this->register_shortcode();
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
		register_block_type( 'jetpack/simple-payments-button', array(
67
			'render_callback' => array( $this, 'render_gutenberg_block' ),
68
		) );
69
	}
70
71
	public function enqueue_block_editor_assets() {
72
		wp_enqueue_script(
73
			'gutenberg-simple-payments-button',
74
			plugins_url( 'simple-payments-block.js', __FILE__ ),
75
			array( 'wp-blocks', 'wp-element' )
76
		);
77
	}
78
79
	public function enqueue_block_assets() {
80
		if ( is_admin() ) {
81
			// Load the styles just in admin area and rely on custom PayPal
82
			// styles on front end
83
			wp_enqueue_style(
84
				'gutenberg-simple-payments-button-styles',
85
				plugins_url( 'simple-payments-block.css', __FILE__ ),
86
				array(),
87
				JETPACK__VERSION
88
			);
89
		}
90
	}
91
92
	/**
93
	 * This function is mostly similar on existing output_shortcode(),
94
	 * with some elements like product title and description removed,
95
	 * since we don't want to include these as part of the block.
96
	 *
97
	 * @param array $attributes Array of Gutenberg block attributes
98
	 *
99
	 * @return string HTML to be rendered on front end
100
	 */
101
	public function render_gutenberg_block( $attributes ) {
102
		$data = array();
103
		// mock product ID for now since we don't have CPT support in Gutenberg yet
104
		$data['id'] = 111;
105
		$data['multiple'] = $attributes['multiple'];
106
		$data['dom_id'] = uniqid( self::$css_classname_prefix . '-' . $data['id'] . '_', true );
107
		$data['class'] = self::$css_classname_prefix . '-' . $data['id'];
108
		$data['price'] = $attributes['price'];
109
		$data['blog_id'] = $this->get_blog_id();
110
		$data['currency'] = $attributes['currency'];
111
112
		$currency_symbols = array(
113
			'US' => '$',
114
			'EU' => '€',
115
			'CA' => '$',
116
		);
117
118
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
119
			wp_enqueue_script( 'paypal-express-checkout' );
120
		}
121 View Code Duplication
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
122
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
123
		}
124
125
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
126
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
127
			esc_js( $data['blog_id'] ),
128
			esc_js( $data['id'] ),
129
			esc_js( $data['dom_id'] ),
130
			esc_js( $data['multiple'] )
131
		) );
132
133
		$css_prefix = self::$css_classname_prefix;
134
		$display_price = $currency_symbols[ $data['currency'] ] . $data['price'];
135
136
		if ( $data['multiple'] ) {
137
			$items = "
138
				<div class='${css_prefix}-items'>
139
					<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
140
				</div>
141
				";
142
		}
143
144
		return "
145
			<div class='{$data['class']} ${css_prefix}-wrapper'>
146
				<div class='${css_prefix}-product'>
147
					<div class='${css_prefix}-details'>
148
						<div class='${css_prefix}-price'><p>{$display_price}</p></div>
149
						<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
150
						<div class='${css_prefix}-purchase-box'>
151
							{$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...
152
							<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
153
						</div>
154
					</div>
155
				</div>
156
			</div>
157
		";
158
	}
159
160
	function remove_auto_paragraph_from_product_description( $content ) {
161
		if ( get_post_type() === self::$post_type_product ) {
162
			remove_filter( 'the_content', 'wpautop' );
163
		}
164
165
		return $content;
166
	}
167
168
	function get_blog_id() {
169
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
170
			return get_current_blog_id();
171
		}
172
173
		return Jetpack_Options::get_option( 'id' );
174
	}
175
176
	function parse_shortcode( $attrs, $content = false ) {
177
		if ( empty( $attrs['id'] ) ) {
178
			return;
179
		}
180
		$product = get_post( $attrs['id'] );
181
		if ( ! $product || is_wp_error( $product ) ) {
182
			return;
183
		}
184
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
185
			return;
186
		}
187
188
		// We allow for overriding the presentation labels
189
		$data = shortcode_atts( array(
190
			'blog_id'     => $this->get_blog_id(),
191
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
192
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
193
			'title'       => get_the_title( $product ),
194
			'description' => $product->post_content,
195
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
196
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
197
		), $attrs );
198
199
		$data['price'] = $this->format_price(
200
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
201
			get_post_meta( $product->ID, 'spay_price', true ),
202
			get_post_meta( $product->ID, 'spay_currency', true ),
203
			$data
204
		);
205
206
		$data['id'] = $attrs['id'];
207
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
208
			wp_enqueue_script( 'paypal-express-checkout' );
209
		}
210 View Code Duplication
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
211
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
212
		}
213
214
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
215
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
216
			esc_js( $data['blog_id'] ),
217
			esc_js( $attrs['id'] ),
218
			esc_js( $data['dom_id'] ),
219
			esc_js( $data['multiple'] )
220
		) );
221
222
		return $this->output_shortcode( $data );
223
	}
224
225
	function output_shortcode( $data ) {
226
		$items = '';
227
		$css_prefix = self::$css_classname_prefix;
228
229
		if ( $data['multiple'] ) {
230
			$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...
231
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
232
			</div>";
233
		}
234
		$image = "";
235
		if( has_post_thumbnail( $data['id'] ) ) {
236
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
237
		}
238
		return "
239
<div class='{$data['class']} ${css_prefix}-wrapper'>
240
	<div class='${css_prefix}-product'>
241
		{$image}
242
		<div class='${css_prefix}-details'>
243
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
244
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
245
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
246
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
247
			<div class='${css_prefix}-purchase-box'>
248
				{$items}
249
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
250
			</div>
251
		</div>
252
	</div>
253
</div>
254
		";
255
	}
256
257
	function format_price( $formatted_price, $price, $currency, $all_data ) {
258
		if ( $formatted_price ) {
259
			return $formatted_price;
260
		}
261
		return "$price $currency";
262
	}
263
264
	/**
265
	 * Allows custom post types to be used by REST API.
266
	 * @param $post_types
267
	 * @see hook 'rest_api_allowed_post_types'
268
	 * @return array
269
	 */
270
	function allow_rest_api_types( $post_types ) {
271
		$post_types[] = self::$post_type_order;
272
		$post_types[] = self::$post_type_product;
273
		return $post_types;
274
	}
275
276
	function allow_sync_post_meta( $post_meta ) {
277
		return array_merge( $post_meta, array(
278
			'spay_paypal_id',
279
			'spay_status',
280
			'spay_product_id',
281
			'spay_quantity',
282
			'spay_price',
283
			'spay_customer_email',
284
			'spay_currency',
285
			'spay_cta',
286
			'spay_email',
287
			'spay_multiple',
288
			'spay_formatted_price',
289
		) );
290
	}
291
292
	/**
293
	 * Sets up the custom post types for the module.
294
	 */
295
	function setup_cpts() {
296
297
		/*
298
		 * ORDER data structure. holds:
299
		 * title = customer_name | 4xproduct_name
300
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
301
		 * metadata:
302
		 * spay_paypal_id - paypal id of transaction
303
		 * spay_status
304
		 * spay_product_id - post_id of bought product
305
		 * spay_quantity - quantity of product
306
		 * spay_price - item price at the time of purchase
307
		 * spay_customer_email - customer email
308
		 * ... (WIP)
309
		 */
310
		$order_capabilities = array(
311
			'edit_post'             => 'edit_posts',
312
			'read_post'             => 'read_private_posts',
313
			'delete_post'           => 'delete_posts',
314
			'edit_posts'            => 'edit_posts',
315
			'edit_others_posts'     => 'edit_others_posts',
316
			'publish_posts'         => 'publish_posts',
317
			'read_private_posts'    => 'read_private_posts',
318
		);
319
		$order_args = array(
320
			'label'                 => esc_html__( 'Order', 'jetpack' ),
321
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
322
			'supports'              => array( 'custom-fields', 'excerpt' ),
323
			'hierarchical'          => false,
324
			'public'                => false,
325
			'show_ui'               => false,
326
			'show_in_menu'          => false,
327
			'show_in_admin_bar'     => false,
328
			'show_in_nav_menus'     => false,
329
			'can_export'            => true,
330
			'has_archive'           => false,
331
			'exclude_from_search'   => true,
332
			'publicly_queryable'    => false,
333
			'rewrite'               => false,
334
			'capabilities'          => $order_capabilities,
335
			'show_in_rest'          => true,
336
		);
337
		register_post_type( self::$post_type_order, $order_args );
338
339
		/*
340
		 * PRODUCT data structure. Holds:
341
		 * title - title
342
		 * content - description
343
		 * thumbnail - image
344
		 * metadata:
345
		 * spay_price - price
346
		 * spay_formatted_price
347
		 * spay_currency - currency code
348
		 * spay_cta - text with "Buy" or other CTA
349
		 * spay_email - paypal email
350
		 * spay_multiple - allow for multiple items
351
		 * spay_status - status. { enabled | disabled }
352
		 */
353
		$product_capabilities = array(
354
			'edit_post'             => 'edit_posts',
355
			'read_post'             => 'read_private_posts',
356
			'delete_post'           => 'delete_posts',
357
			'edit_posts'            => 'edit_posts',
358
			'edit_others_posts'     => 'edit_others_posts',
359
			'publish_posts'         => 'publish_posts',
360
			'read_private_posts'    => 'read_private_posts',
361
		);
362
		$product_args = array(
363
			'label'                 => esc_html__( 'Product', 'jetpack' ),
364
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
365
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields' ),
366
			'hierarchical'          => false,
367
			'public'                => false,
368
			'show_ui'               => false,
369
			'show_in_menu'          => false,
370
			'show_in_admin_bar'     => false,
371
			'show_in_nav_menus'     => false,
372
			'can_export'            => true,
373
			'has_archive'           => false,
374
			'exclude_from_search'   => true,
375
			'publicly_queryable'    => false,
376
			'rewrite'               => false,
377
			'capabilities'          => $product_capabilities,
378
			'show_in_rest'          => true,
379
		);
380
		register_post_type( self::$post_type_product, $product_args );
381
	}
382
383
	public function update_post_meta_for_api( $meta_arr, $object ) {
384
		//get the id of the post object array
385
		$post_id = $object->ID;
386
387
		foreach( $meta_arr as $meta_key => $meta_val ) {
388
			update_post_meta( $post_id, $meta_key, $meta_val );
389
		}
390
391
		return true;
392
	}
393
394
	function setup_meta_fields_for_rest() {
395
		$args = array(
396
		   'update_callback' => array( $this, 'update_post_meta_for_api'),
397
		);
398
399
		register_rest_field( self::$post_type_product, 'meta', $args );
400
	}
401
402
}
403
Jetpack_Simple_Payments::getInstance();
404