Completed
Push — add/gutenblock-simple-payments ( d67703 )
by
unknown
28:53 queued 19:36
created

Jetpack_Simple_Payments::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
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
58
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
59
	}
60
61
	private function register_gutenberg_block() {
62
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
63
	}
64
65
	public function enqueue_block_editor_assets() {
66
		wp_enqueue_script(
67
			'gutenberg-simple-payments-button',
68
			plugins_url( 'block.js', __FILE__ ),
69
			array( 'wp-blocks', 'wp-element' )
70
		);
71
	}
72
73
	function remove_auto_paragraph_from_product_description( $content ) {
74
		if ( get_post_type() === self::$post_type_product ) {
75
			remove_filter( 'the_content', 'wpautop' );
76
		}
77
78
		return $content;
79
	}
80
81
	function get_blog_id() {
82
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
83
			return get_current_blog_id();
84
		}
85
86
		return Jetpack_Options::get_option( 'id' );
87
	}
88
89
	function parse_shortcode( $attrs, $content = false ) {
90
		if ( empty( $attrs['id'] ) ) {
91
			return;
92
		}
93
		$product = get_post( $attrs['id'] );
94
		if ( ! $product || is_wp_error( $product ) ) {
95
			return;
96
		}
97
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
98
			return;
99
		}
100
101
		// We allow for overriding the presentation labels
102
		$data = shortcode_atts( array(
103
			'blog_id'     => $this->get_blog_id(),
104
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
105
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
106
			'title'       => get_the_title( $product ),
107
			'description' => $product->post_content,
108
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
109
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
110
		), $attrs );
111
112
		$data['price'] = $this->format_price(
113
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
114
			get_post_meta( $product->ID, 'spay_price', true ),
115
			get_post_meta( $product->ID, 'spay_currency', true ),
116
			$data
117
		);
118
119
		$data['id'] = $attrs['id'];
120
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
121
			wp_enqueue_script( 'paypal-express-checkout' );
122
		}
123
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
124
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
125
		}
126
127
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
128
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
129
			esc_js( $data['blog_id'] ),
130
			esc_js( $attrs['id'] ),
131
			esc_js( $data['dom_id'] ),
132
			esc_js( $data['multiple'] )
133
		) );
134
135
		return $this->output_shortcode( $data );
136
	}
137
138
	function output_shortcode( $data ) {
139
		$items = '';
140
		$css_prefix = self::$css_classname_prefix;
141
142
		if ( $data['multiple'] ) {
143
			$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...
144
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
145
			</div>";
146
		}
147
		$image = "";
148
		if( has_post_thumbnail( $data['id'] ) ) {
149
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
150
		}
151
		return "
152
<div class='{$data['class']} ${css_prefix}-wrapper'>
153
	<div class='${css_prefix}-product'>
154
		{$image}
155
		<div class='${css_prefix}-details'>
156
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
157
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
158
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
159
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
160
			<div class='${css_prefix}-purchase-box'>
161
				{$items}
162
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
163
			</div>
164
		</div>
165
	</div>
166
</div>
167
		";
168
	}
169
170
	function format_price( $formatted_price, $price, $currency, $all_data ) {
171
		if ( $formatted_price ) {
172
			return $formatted_price;
173
		}
174
		return "$price $currency";
175
	}
176
177
	/**
178
	 * Allows custom post types to be used by REST API.
179
	 * @param $post_types
180
	 * @see hook 'rest_api_allowed_post_types'
181
	 * @return array
182
	 */
183
	function allow_rest_api_types( $post_types ) {
184
		$post_types[] = self::$post_type_order;
185
		$post_types[] = self::$post_type_product;
186
		return $post_types;
187
	}
188
189
	function allow_sync_post_meta( $post_meta ) {
190
		return array_merge( $post_meta, array(
191
			'spay_paypal_id',
192
			'spay_status',
193
			'spay_product_id',
194
			'spay_quantity',
195
			'spay_price',
196
			'spay_customer_email',
197
			'spay_currency',
198
			'spay_cta',
199
			'spay_email',
200
			'spay_multiple',
201
			'spay_formatted_price',
202
		) );
203
	}
204
205
	/**
206
	 * Sets up the custom post types for the module.
207
	 */
208
	function setup_cpts() {
209
210
		/*
211
		 * ORDER data structure. holds:
212
		 * title = customer_name | 4xproduct_name
213
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
214
		 * metadata:
215
		 * spay_paypal_id - paypal id of transaction
216
		 * spay_status
217
		 * spay_product_id - post_id of bought product
218
		 * spay_quantity - quantity of product
219
		 * spay_price - item price at the time of purchase
220
		 * spay_customer_email - customer email
221
		 * ... (WIP)
222
		 */
223
		$order_capabilities = array(
224
			'edit_post'             => 'edit_posts',
225
			'read_post'             => 'read_private_posts',
226
			'delete_post'           => 'delete_posts',
227
			'edit_posts'            => 'edit_posts',
228
			'edit_others_posts'     => 'edit_others_posts',
229
			'publish_posts'         => 'publish_posts',
230
			'read_private_posts'    => 'read_private_posts',
231
		);
232
		$order_args = array(
233
			'label'                 => esc_html__( 'Order', 'jetpack' ),
234
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
235
			'supports'              => array( 'custom-fields', 'excerpt' ),
236
			'hierarchical'          => false,
237
			'public'                => false,
238
			'show_ui'               => false,
239
			'show_in_menu'          => false,
240
			'show_in_admin_bar'     => false,
241
			'show_in_nav_menus'     => false,
242
			'can_export'            => true,
243
			'has_archive'           => false,
244
			'exclude_from_search'   => true,
245
			'publicly_queryable'    => false,
246
			'rewrite'               => false,
247
			'capabilities'          => $order_capabilities,
248
			'show_in_rest'          => true,
249
		);
250
		register_post_type( self::$post_type_order, $order_args );
251
252
		/*
253
		 * PRODUCT data structure. Holds:
254
		 * title - title
255
		 * content - description
256
		 * thumbnail - image
257
		 * metadata:
258
		 * spay_price - price
259
		 * spay_formatted_price
260
		 * spay_currency - currency code
261
		 * spay_cta - text with "Buy" or other CTA
262
		 * spay_email - paypal email
263
		 * spay_multiple - allow for multiple items
264
		 * spay_status - status. { enabled | disabled }
265
		 */
266
		$product_capabilities = array(
267
			'edit_post'             => 'edit_posts',
268
			'read_post'             => 'read_private_posts',
269
			'delete_post'           => 'delete_posts',
270
			'edit_posts'            => 'edit_posts',
271
			'edit_others_posts'     => 'edit_others_posts',
272
			'publish_posts'         => 'publish_posts',
273
			'read_private_posts'    => 'read_private_posts',
274
		);
275
		$product_args = array(
276
			'label'                 => esc_html__( 'Product', 'jetpack' ),
277
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
278
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields' ),
279
			'hierarchical'          => false,
280
			'public'                => false,
281
			'show_ui'               => false,
282
			'show_in_menu'          => false,
283
			'show_in_admin_bar'     => false,
284
			'show_in_nav_menus'     => false,
285
			'can_export'            => true,
286
			'has_archive'           => false,
287
			'exclude_from_search'   => true,
288
			'publicly_queryable'    => false,
289
			'rewrite'               => false,
290
			'capabilities'          => $product_capabilities,
291
			'show_in_rest'          => true,
292
		);
293
		register_post_type( self::$post_type_product, $product_args );
294
	}
295
296
}
297
Jetpack_Simple_Payments::getInstance();
298