Completed
Push — simple-payments/styling ( 6ea277...67a632 )
by
unknown
167:24 queued 159:01
created

Jetpack_Simple_Payments::output_shortcode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
nc 2
nop 1
dl 0
loc 23
rs 9.0856
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
 * TODO: Once the feature is fully shipped, create a file modules/simple-payments.php with a proper header to turn module on/off.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
7
*/
8
class Jetpack_Simple_Payments {
9
	// These have to be under 20 chars because that is CPT limit.
10
	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...
11
	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...
12
13
	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...
14
15
	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...
16
17
	// Classic singleton pattern:
18
	private static $instance;
19
	private function __construct() {}
20
	static function getInstance() {
21
		if ( ! self::$instance ) {
22
			self::$instance = new self();
23
			self::$instance->register_init_hook();
24
		}
25
		return self::$instance;
26
	}
27
28
	private function register_scripts() {
29
		/**
30
		 * Paypal heavily discourages putting that script in your own server:
31
		 * @see https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/
32
		 */
33
		wp_register_script( 'paypal-checkout-js', 'https://www.paypalobjects.com/api/checkout.js', array(), null, true );
34
		wp_register_script( 'paypal-express-checkout', plugins_url( '/paypal-express-checkout.js', __FILE__ ) , array( 'jquery', 'paypal-checkout-js' ), '0.21' );
35
		wp_enqueue_style( 'simple-payments', plugins_url( '/simple-payments.css', __FILE__ ) );
36
	}
37
	private function register_init_hook() {
38
		add_action( 'init', array( $this, 'init_hook_action' ) );
39
	}
40
	private function register_shortcode() {
41
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
42
	}
43
44
	public function init_hook_action() {
45
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
46
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
47
		$this->register_scripts();
48
		$this->register_shortcode();
49
		$this->setup_cpts();
50
	}
51
52
	function parse_shortcode( $attrs, $content = false ) {
53
		if ( empty( $attrs['id'] ) ) {
54
			return;
55
		}
56
		$product = get_post( $attrs['id'] );
57
		if ( ! $product || is_wp_error( $product ) ) {
58
			return;
59
		}
60
		if ( $product->post_type !== self::$post_type_product ) {
61
			return;
62
		}
63
64
		// We allow for overriding the presentation labels
65
		$data = shortcode_atts( array(
66
			'blog_id'     => Jetpack_Options::get_option( 'id' ),
67
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
68
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
69
			'title'       => get_the_title( $product ),
70
			'description' => $product->post_content,
71
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
72
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
73
		), $attrs );
74
		$data['price'] = $this->format_price(
75
			get_post_meta( $product->ID, 'spay_price', true ),
76
			get_post_meta( $product->ID, 'spay_currency', true ),
77
			$data
78
		);
79
80
		if ( ! wp_script_is( 'paypal-express-checkout','enqueued' ) ) {
81
			wp_enqueue_script( 'paypal-express-checkout' );
82
		}
83
84
		wp_add_inline_script( 'paypal-express-checkout', "try{PaypalExpressCheckout.renderButton( '{$data['blog_id']}', '{$attrs['id']}', '{$data['dom_id']}', '{$data['multiple']}' );}catch(e){}" );
85
86
		return $this->output_shortcode( $data );
87
	}
88
89
	function output_shortcode( $data ) {
90
		$items = '';
91
		$cssPrefix = self::$css_classname_prefix;
92
93
		if ( $data['multiple'] ) {
94
			$items="<div class='${cssPrefix}-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...
95
				<input class='${cssPrefix}-items-number' type='number' value='1' id='{$data['dom_id']}_number' />
96
			</div>";
97
		}
98
99
		return "
100
<div class='{$data['class']} ${cssPrefix}-wrapper'>
101
	<p class='${cssPrefix}-purchase-message'></p>
102
	<div class='${cssPrefix}-title'><p>{$data['title']}</p></div>
103
	<div class='${cssPrefix}-description'><p>{$data['description']}</p></div>
104
	<div class='${cssPrefix}-purchase-box'>
105
		<div class='${cssPrefix}-price'><p>{$data['price']}</p></div>
106
		{$items}
107
		<div class='${cssPrefix}-button' id='{$data['dom_id']}_button'></div>
108
	</div>
109
</div>
110
		";
111
	}
112
113
	function format_price( $price, $currency, $all_data ) {
114
		// TODO: better price formatting logic. Extracting from woocmmerce is not a solution since its bound with woo site options.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
115
		return "$price $currency";
116
	}
117
118
	/**
119
	 * Allows custom post types to be used by REST API.
120
	 * @param $post_types
121
	 * @see hook 'rest_api_allowed_post_types'
122
	 * @return array
123
	 */
124
	function allow_rest_api_types( $post_types ) {
125
		$post_types[] = self::$post_type_order;
126
		$post_types[] = self::$post_type_product;
127
		return $post_types;
128
	}
129
130
	function allow_sync_post_meta( $post_meta ) {
131
		return array_merge( $post_meta, array(
132
			'spay_paypal_id',
133
			'spay_status',
134
			'spay_product_id',
135
			'spay_quantity',
136
			'spay_price',
137
			'spay_customer_email',
138
			'spay_currency',
139
			'spay_cta',
140
			'spay_email',
141
			'spay_multiple'
142
		) );
143
	}
144
145
	/**
146
	 * Sets up the custom post types for the module.
147
	 */
148
	function setup_cpts() {
149
150
		/*
151
		 * ORDER data structure. holds:
152
		 * title = customer_name | 4xproduct_name
153
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
154
		 * metadata:
155
		 * spay_paypal_id - paypal id of transaction
156
		 * spay_status
157
		 * spay_product_id - post_id of bought product
158
		 * spay_quantity - quantity of product
159
		 * spay_price - item price at the time of purchase
160
		 * spay_customer_email - customer email
161
		 * ... (WIP)
162
		 */
163
		$order_capabilities = array(
164
			'edit_post'             => 'edit_posts',
165
			'read_post'             => 'read_private_posts',
166
			'delete_post'           => 'delete_posts',
167
			'edit_posts'            => 'edit_posts',
168
			'edit_others_posts'     => 'edit_others_posts',
169
			'publish_posts'         => 'publish_posts',
170
			'read_private_posts'    => 'read_private_posts',
171
		);
172
		$order_args = array(
173
			'label'                 => esc_html__( 'Order', 'jetpack' ),
174
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
175
			'supports'              => array( 'custom-fields', 'excerpt' ),
176
			'hierarchical'          => false,
177
			'public'                => false,
178
			'show_ui'               => false,
179
			'show_in_menu'          => false,
180
			'show_in_admin_bar'     => false,
181
			'show_in_nav_menus'     => false,
182
			'can_export'            => true,
183
			'has_archive'           => false,
184
			'exclude_from_search'   => true,
185
			'publicly_queryable'    => false,
186
			'rewrite'               => false,
187
			'capabilities'          => $order_capabilities,
188
			'show_in_rest'          => true,
189
		);
190
		register_post_type( self::$post_type_order, $order_args );
191
192
		/*
193
		 * PRODUCT data structure. Holds:
194
		 * title - title
195
		 * content - description
196
		 * thumbnail - image
197
		 * metadata:
198
		 * spay_price - price
199
		 * spay_currency - currency code
200
		 * spay_cta - text with "Buy" or other CTA
201
		 * spay_email - paypal email
202
		 * spay_multiple - allow for multiple items
203
		 * spay_status - status. { enabled | disabled }
204
		 */
205
		$product_capabilities = array(
206
			'edit_post'             => 'edit_posts',
207
			'read_post'             => 'read_private_posts',
208
			'delete_post'           => 'delete_posts',
209
			'edit_posts'            => 'edit_posts',
210
			'edit_others_posts'     => 'edit_others_posts',
211
			'publish_posts'         => 'publish_posts',
212
			'read_private_posts'    => 'read_private_posts',
213
		);
214
		$product_args = array(
215
			'label'                 => esc_html__( 'Product', 'jetpack' ),
216
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
217
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields' ),
218
			'hierarchical'          => false,
219
			'public'                => false,
220
			'show_ui'               => false,
221
			'show_in_menu'          => false,
222
			'show_in_admin_bar'     => false,
223
			'show_in_nav_menus'     => false,
224
			'can_export'            => true,
225
			'has_archive'           => false,
226
			'exclude_from_search'   => true,
227
			'publicly_queryable'    => false,
228
			'rewrite'               => false,
229
			'capabilities'          => $product_capabilities,
230
			'show_in_rest'          => true,
231
		);
232
		register_post_type( self::$post_type_product, $product_args );
233
	}
234
235
}
236
Jetpack_Simple_Payments::getInstance();
237