Passed
Pull Request — master (#168)
by
unknown
02:19
created
classes/class-send-products.php 2 patches
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -15,14 +15,14 @@  discard block
 block discarded – undo
15 15
  * Abort if this file is called directly
16 16
  */
17 17
 if (!defined('ABSPATH')) {
18
-    exit;
18
+	exit;
19 19
 }
20 20
 
21 21
 /**
22 22
  * Include plugin file if function is_plugin_active does not exist
23 23
  */
24 24
 if (!function_exists('is_plugin_active')) {
25
-    require_once(ABSPATH . '/wp-admin/includes/plugin.php');
25
+	require_once(ABSPATH . '/wp-admin/includes/plugin.php');
26 26
 }
27 27
 
28 28
 /**
@@ -45,271 +45,271 @@  discard block
 block discarded – undo
45 45
 define('ALGOLIA_API_KEY', '_admin_api_key');
46 46
 
47 47
 if (!class_exists('Algolia_Send_Products')) {
48
-    /**
49
-     * Algolia WooIndexer main class
50
-     */
51
-    // TODO Rename class "Algolia_Send_Products" to match the regular expression ^[A-Z][a-zA-Z0-9]*$.
52
-    class Algolia_Send_Products
53
-    {
54
-        const PLUGIN_NAME      = 'Algolia Woo Indexer';
55
-        const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
56
-
57
-        /**
58
-         * The Algolia instance
59
-         *
60
-         * @var \Algolia\AlgoliaSearch\SearchClient
61
-         */
62
-        private static $algolia = null;
63
-
64
-        /**
65
-         * Check if we can connect to Algolia, if not, handle the exception, display an error and then return
66
-         */
67
-        public static function can_connect_to_algolia()
68
-        {
69
-            try {
70
-                self::$algolia->listApiKeys();
71
-            } catch (\Algolia\AlgoliaSearch\Exceptions\UnreachableException $error) {
72
-                add_action(
73
-                    'admin_notices',
74
-                    function () {
75
-                        echo '<div class="error notice">
48
+	/**
49
+	 * Algolia WooIndexer main class
50
+	 */
51
+	// TODO Rename class "Algolia_Send_Products" to match the regular expression ^[A-Z][a-zA-Z0-9]*$.
52
+	class Algolia_Send_Products
53
+	{
54
+		const PLUGIN_NAME      = 'Algolia Woo Indexer';
55
+		const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
56
+
57
+		/**
58
+		 * The Algolia instance
59
+		 *
60
+		 * @var \Algolia\AlgoliaSearch\SearchClient
61
+		 */
62
+		private static $algolia = null;
63
+
64
+		/**
65
+		 * Check if we can connect to Algolia, if not, handle the exception, display an error and then return
66
+		 */
67
+		public static function can_connect_to_algolia()
68
+		{
69
+			try {
70
+				self::$algolia->listApiKeys();
71
+			} catch (\Algolia\AlgoliaSearch\Exceptions\UnreachableException $error) {
72
+				add_action(
73
+					'admin_notices',
74
+					function () {
75
+						echo '<div class="error notice">
76 76
 							  <p>' . esc_html__('An error has been encountered. Please check your application ID and API key. ', 'algolia-woo-indexer') . '</p>
77 77
 							</div>';
78
-                    }
79
-                );
80
-                return;
81
-            }
82
-        }
83
-
84
-        /**
85
-         * Get sale price or regular price based on product type
86
-         *
87
-         * @param  mixed $product Product to check   
88
-         * @return array ['sale_price' => $sale_price,'regular_price' => $regular_price] Array with regular price and sale price
89
-         */
90
-        public static function get_product_type_price($product)
91
-        {
92
-            $sale_price = 0;
93
-            $regular_price = 0;
94
-            if ($product->is_type('simple')) {
95
-                $sale_price     =  $product->get_sale_price();
96
-                $regular_price  =  $product->get_regular_price();
97
-            } elseif ($product->is_type('variable')) {
98
-                $sale_price     =  $product->get_variation_sale_price('min', true);
99
-                $regular_price  =  $product->get_variation_regular_price('max', true);
100
-            }
101
-            return array(
102
-                'sale_price' => $sale_price,
103
-                'regular_price' => $regular_price
104
-            );
105
-        }
106
-
107
-
108
-        /**
109
-         * Checks if stock management is enabled and if so, returns quantity and status
110
-         *
111
-         * @param  mixed $product Product to check   
112
-         * @return array ['stock_quantity' => $stock_quantity,'stock_status' => $stock_status] Array with quantity and status. if stock management is disabled, false will be returned,
113
-         */
114
-        public static function get_product_stock_data($product)
115
-        {
116
-            if ($product->get_manage_stock()) {
117
-                return array(
118
-                    'stock_quantity' => $product->get_stock_quantity(),
119
-                    'stock_status' => $product->get_stock_status()
120
-                );
121
-            } else {
122
-                return false;
123
-            }
124
-        }
125
-
126
-        /**
127
-         * Get attributes from product
128
-         *
129
-         * @param  mixed $product Product to check   
130
-         * @return array ['pa_name' => ['value1', 'value2']] Array with key set to the product attribute internal name and values as array. returns false if not attributes found.
131
-         */
132
-        public static function get_product_attributes($product)
133
-        {
134
-            $rawAttributes = $product->get_attributes();
135
-            $numericRangeAttributes = ["pa_height", "pa_flowermonth"];
136
-            if (!$rawAttributes) {
137
-                return false;
138
-            }
139
-
140
-            $attributes = [];
141
-            foreach ($rawAttributes as $attribute) {
142
-                if ($attribute->get_variation()) {
143
-                    continue;
144
-                }
145
-                $name = $attribute->get_name();
146
-                if ($attribute->is_taxonomy()) {
147
-                    $terms = wp_get_post_terms($product->get_id(), $name, 'all');
148
-                    $tax_terms = array();
78
+					}
79
+				);
80
+				return;
81
+			}
82
+		}
83
+
84
+		/**
85
+		 * Get sale price or regular price based on product type
86
+		 *
87
+		 * @param  mixed $product Product to check   
88
+		 * @return array ['sale_price' => $sale_price,'regular_price' => $regular_price] Array with regular price and sale price
89
+		 */
90
+		public static function get_product_type_price($product)
91
+		{
92
+			$sale_price = 0;
93
+			$regular_price = 0;
94
+			if ($product->is_type('simple')) {
95
+				$sale_price     =  $product->get_sale_price();
96
+				$regular_price  =  $product->get_regular_price();
97
+			} elseif ($product->is_type('variable')) {
98
+				$sale_price     =  $product->get_variation_sale_price('min', true);
99
+				$regular_price  =  $product->get_variation_regular_price('max', true);
100
+			}
101
+			return array(
102
+				'sale_price' => $sale_price,
103
+				'regular_price' => $regular_price
104
+			);
105
+		}
106
+
107
+
108
+		/**
109
+		 * Checks if stock management is enabled and if so, returns quantity and status
110
+		 *
111
+		 * @param  mixed $product Product to check   
112
+		 * @return array ['stock_quantity' => $stock_quantity,'stock_status' => $stock_status] Array with quantity and status. if stock management is disabled, false will be returned,
113
+		 */
114
+		public static function get_product_stock_data($product)
115
+		{
116
+			if ($product->get_manage_stock()) {
117
+				return array(
118
+					'stock_quantity' => $product->get_stock_quantity(),
119
+					'stock_status' => $product->get_stock_status()
120
+				);
121
+			} else {
122
+				return false;
123
+			}
124
+		}
125
+
126
+		/**
127
+		 * Get attributes from product
128
+		 *
129
+		 * @param  mixed $product Product to check   
130
+		 * @return array ['pa_name' => ['value1', 'value2']] Array with key set to the product attribute internal name and values as array. returns false if not attributes found.
131
+		 */
132
+		public static function get_product_attributes($product)
133
+		{
134
+			$rawAttributes = $product->get_attributes();
135
+			$numericRangeAttributes = ["pa_height", "pa_flowermonth"];
136
+			if (!$rawAttributes) {
137
+				return false;
138
+			}
139
+
140
+			$attributes = [];
141
+			foreach ($rawAttributes as $attribute) {
142
+				if ($attribute->get_variation()) {
143
+					continue;
144
+				}
145
+				$name = $attribute->get_name();
146
+				if ($attribute->is_taxonomy()) {
147
+					$terms = wp_get_post_terms($product->get_id(), $name, 'all');
148
+					$tax_terms = array();
149 149
                     
150
-                    // interpolate all values when found in numericRangeAttributes
151
-                    if (array_search($name, $numericRangeAttributes, true) !== false) {
152
-                        $integers = array();
153
-                        foreach ($terms as $term) {
154
-                            array_push($integers, (int) $term->name);
155
-                        }
156
-                        for ($i = min($integers); $i <= max($integers); $i++) {
157
-                            array_push($tax_terms, $i);
158
-                        }
159
-                    } else {
160
-                        // strings
161
-                        foreach ($terms as $term) {
162
-                            $single_term = esc_html($term->name);
163
-                            array_push($tax_terms, $single_term);
164
-                        }
165
-                    }
166
-                }
167
-                $attributes[$name] = $tax_terms;
168
-            }
169
-            return $attributes;
170
-        }
171
-
172
-        /**
173
-         * Send WooCommerce products to Algolia
174
-         *
175
-         * @param Int $id Product to send to Algolia if we send only a single product
176
-         * @return void
177
-         */
178
-        public static function send_products_to_algolia($id = '')
179
-        {
180
-            /**
181
-             * Remove classes from plugin URL and autoload Algolia with Composer
182
-             */
183
-
184
-            $base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
185
-            require_once $base_plugin_directory . '/vendor/autoload.php';
186
-
187
-            /**
188
-             * Fetch the required variables from the Settings API
189
-             */
190
-
191
-            $algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APP_ID);
192
-            $algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
193
-
194
-            $algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
195
-            $algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
196
-
197
-            $algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
198
-            $algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
199
-
200
-            /**
201
-             * Display admin notice and return if not all values have been set
202
-             */
203
-
204
-            Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
205
-
206
-            /**
207
-             * Initiate the Algolia client
208
-             */
209
-            self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
210
-
211
-            /**
212
-             * Check if we can connect, if not, handle the exception, display an error and then return
213
-             */
214
-            self::can_connect_to_algolia();
215
-
216
-            /**
217
-             * Initialize the search index and set the name to the option from the database
218
-             */
219
-            $index = self::$algolia->initIndex($algolia_index_name);
220
-
221
-            /**
222
-             * Setup arguments for sending all products to Algolia
223
-             *
224
-             * Limit => -1 means we send all products
225
-             */
226
-            $arguments = array(
227
-                'status'   => 'publish',
228
-                'limit'    => -1,
229
-                'paginate' => false,
230
-            );
231
-
232
-            /**
233
-             * Setup arguments for sending only a single product
234
-             */
235
-            if (isset($id) && '' !== $id) {
236
-                $arguments = array(
237
-                    'status'   => 'publish',
238
-                    'include'  => array($id),
239
-                    'paginate' => false,
240
-                );
241
-            }
242
-
243
-            /**
244
-             * Fetch all products from WooCommerce
245
-             *
246
-             * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
247
-             */
248
-            $products =
249
-                /** @scrutinizer ignore-call */
250
-                wc_get_products($arguments);
251
-
252
-            if (empty($products)) {
253
-                return;
254
-            }
255
-            $records = array();
256
-            $record  = array();
257
-
258
-            foreach ($products as $product) {
259
-                /**
260
-                 * Set sale price or regular price based on product type
261
-                 */
262
-                $product_type_price = self::get_product_type_price($product);
263
-                $sale_price = $product_type_price['sale_price'];
264
-                $regular_price = $product_type_price['regular_price'];
265
-                /**
266
-                 * Extract image from $product->get_image()
267
-                 */
268
-                preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
269
-                $product_image = array_pop($result);
270
-
271
-                /**
272
-                 * Build the record array using the information from the WooCommerce product
273
-                 */
274
-                $record['objectID']                      = $product->get_id();
275
-                $record['product_name']                  = $product->get_name();
276
-                $record['product_image']                 = $product_image;
277
-                $record['short_description']             = $product->get_short_description();
278
-                $record['regular_price']                 = $regular_price;
279
-                $record['sale_price']                    = $sale_price;
280
-                $record['on_sale']                       = $product->is_on_sale();
281
-                $record['attributes']                    = self::get_product_attributes($product);
282
-
283
-
284
-                /**
285
-                 * Add stock information if stock management is on
286
-                 */
287
-                $stock_data = self::get_product_stock_data($product);
288
-                if($stock_data) {
289
-                    $record = array_merge($record, $stock_data);
290
-                }
150
+					// interpolate all values when found in numericRangeAttributes
151
+					if (array_search($name, $numericRangeAttributes, true) !== false) {
152
+						$integers = array();
153
+						foreach ($terms as $term) {
154
+							array_push($integers, (int) $term->name);
155
+						}
156
+						for ($i = min($integers); $i <= max($integers); $i++) {
157
+							array_push($tax_terms, $i);
158
+						}
159
+					} else {
160
+						// strings
161
+						foreach ($terms as $term) {
162
+							$single_term = esc_html($term->name);
163
+							array_push($tax_terms, $single_term);
164
+						}
165
+					}
166
+				}
167
+				$attributes[$name] = $tax_terms;
168
+			}
169
+			return $attributes;
170
+		}
171
+
172
+		/**
173
+		 * Send WooCommerce products to Algolia
174
+		 *
175
+		 * @param Int $id Product to send to Algolia if we send only a single product
176
+		 * @return void
177
+		 */
178
+		public static function send_products_to_algolia($id = '')
179
+		{
180
+			/**
181
+			 * Remove classes from plugin URL and autoload Algolia with Composer
182
+			 */
183
+
184
+			$base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
185
+			require_once $base_plugin_directory . '/vendor/autoload.php';
186
+
187
+			/**
188
+			 * Fetch the required variables from the Settings API
189
+			 */
190
+
191
+			$algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APP_ID);
192
+			$algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
193
+
194
+			$algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
195
+			$algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
196
+
197
+			$algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
198
+			$algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
199
+
200
+			/**
201
+			 * Display admin notice and return if not all values have been set
202
+			 */
203
+
204
+			Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
205
+
206
+			/**
207
+			 * Initiate the Algolia client
208
+			 */
209
+			self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
210
+
211
+			/**
212
+			 * Check if we can connect, if not, handle the exception, display an error and then return
213
+			 */
214
+			self::can_connect_to_algolia();
215
+
216
+			/**
217
+			 * Initialize the search index and set the name to the option from the database
218
+			 */
219
+			$index = self::$algolia->initIndex($algolia_index_name);
220
+
221
+			/**
222
+			 * Setup arguments for sending all products to Algolia
223
+			 *
224
+			 * Limit => -1 means we send all products
225
+			 */
226
+			$arguments = array(
227
+				'status'   => 'publish',
228
+				'limit'    => -1,
229
+				'paginate' => false,
230
+			);
231
+
232
+			/**
233
+			 * Setup arguments for sending only a single product
234
+			 */
235
+			if (isset($id) && '' !== $id) {
236
+				$arguments = array(
237
+					'status'   => 'publish',
238
+					'include'  => array($id),
239
+					'paginate' => false,
240
+				);
241
+			}
242
+
243
+			/**
244
+			 * Fetch all products from WooCommerce
245
+			 *
246
+			 * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
247
+			 */
248
+			$products =
249
+				/** @scrutinizer ignore-call */
250
+				wc_get_products($arguments);
251
+
252
+			if (empty($products)) {
253
+				return;
254
+			}
255
+			$records = array();
256
+			$record  = array();
257
+
258
+			foreach ($products as $product) {
259
+				/**
260
+				 * Set sale price or regular price based on product type
261
+				 */
262
+				$product_type_price = self::get_product_type_price($product);
263
+				$sale_price = $product_type_price['sale_price'];
264
+				$regular_price = $product_type_price['regular_price'];
265
+				/**
266
+				 * Extract image from $product->get_image()
267
+				 */
268
+				preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
269
+				$product_image = array_pop($result);
270
+
271
+				/**
272
+				 * Build the record array using the information from the WooCommerce product
273
+				 */
274
+				$record['objectID']                      = $product->get_id();
275
+				$record['product_name']                  = $product->get_name();
276
+				$record['product_image']                 = $product_image;
277
+				$record['short_description']             = $product->get_short_description();
278
+				$record['regular_price']                 = $regular_price;
279
+				$record['sale_price']                    = $sale_price;
280
+				$record['on_sale']                       = $product->is_on_sale();
281
+				$record['attributes']                    = self::get_product_attributes($product);
282
+
283
+
284
+				/**
285
+				 * Add stock information if stock management is on
286
+				 */
287
+				$stock_data = self::get_product_stock_data($product);
288
+				if($stock_data) {
289
+					$record = array_merge($record, $stock_data);
290
+				}
291 291
 
292 292
                 
293
-                $records[] = $record;
294
-            }
295
-            wp_reset_postdata();
296
-
297
-            /**
298
-             * Send the information to Algolia and save the result
299
-             * If result is NullResponse, print an error message
300
-             */
301
-            $result = $index->saveObjects($records);
302
-
303
-            if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
304
-                wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
305
-            }
306
-
307
-            /**
308
-             * Display success message
309
-             */
310
-            echo '<div class="notice notice-success is-dismissible">
293
+				$records[] = $record;
294
+			}
295
+			wp_reset_postdata();
296
+
297
+			/**
298
+			 * Send the information to Algolia and save the result
299
+			 * If result is NullResponse, print an error message
300
+			 */
301
+			$result = $index->saveObjects($records);
302
+
303
+			if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
304
+				wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
305
+			}
306
+
307
+			/**
308
+			 * Display success message
309
+			 */
310
+			echo '<div class="notice notice-success is-dismissible">
311 311
 					 	<p>' . esc_html__('Product(s) sent to Algolia.', 'algolia-woo-indexer') . '</p>
312 312
 				  		</div>';
313
-        }
314
-    }
313
+		}
314
+	}
315 315
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -14,14 +14,14 @@  discard block
 block discarded – undo
14 14
 /**
15 15
  * Abort if this file is called directly
16 16
  */
17
-if (!defined('ABSPATH')) {
17
+if ( ! defined('ABSPATH')) {
18 18
     exit;
19 19
 }
20 20
 
21 21
 /**
22 22
  * Include plugin file if function is_plugin_active does not exist
23 23
  */
24
-if (!function_exists('is_plugin_active')) {
24
+if ( ! function_exists('is_plugin_active')) {
25 25
     require_once(ABSPATH . '/wp-admin/includes/plugin.php');
26 26
 }
27 27
 
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 define('ALGOLIA_APP_ID', '_application_id');
45 45
 define('ALGOLIA_API_KEY', '_admin_api_key');
46 46
 
47
-if (!class_exists('Algolia_Send_Products')) {
47
+if ( ! class_exists('Algolia_Send_Products')) {
48 48
     /**
49 49
      * Algolia WooIndexer main class
50 50
      */
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
             } catch (\Algolia\AlgoliaSearch\Exceptions\UnreachableException $error) {
72 72
                 add_action(
73 73
                     'admin_notices',
74
-                    function () {
74
+                    function() {
75 75
                         echo '<div class="error notice">
76 76
 							  <p>' . esc_html__('An error has been encountered. Please check your application ID and API key. ', 'algolia-woo-indexer') . '</p>
77 77
 							</div>';
@@ -92,11 +92,11 @@  discard block
 block discarded – undo
92 92
             $sale_price = 0;
93 93
             $regular_price = 0;
94 94
             if ($product->is_type('simple')) {
95
-                $sale_price     =  $product->get_sale_price();
96
-                $regular_price  =  $product->get_regular_price();
95
+                $sale_price     = $product->get_sale_price();
96
+                $regular_price  = $product->get_regular_price();
97 97
             } elseif ($product->is_type('variable')) {
98
-                $sale_price     =  $product->get_variation_sale_price('min', true);
99
-                $regular_price  =  $product->get_variation_regular_price('max', true);
98
+                $sale_price     = $product->get_variation_sale_price('min', true);
99
+                $regular_price  = $product->get_variation_regular_price('max', true);
100 100
             }
101 101
             return array(
102 102
                 'sale_price' => $sale_price,
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
         {
134 134
             $rawAttributes = $product->get_attributes();
135 135
             $numericRangeAttributes = ["pa_height", "pa_flowermonth"];
136
-            if (!$rawAttributes) {
136
+            if ( ! $rawAttributes) {
137 137
                 return false;
138 138
             }
139 139
 
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
             $algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
196 196
 
197 197
             $algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
198
-            $algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
198
+            $algolia_index_name = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
199 199
 
200 200
             /**
201 201
              * Display admin notice and return if not all values have been set
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
                  * Add stock information if stock management is on
286 286
                  */
287 287
                 $stock_data = self::get_product_stock_data($product);
288
-                if($stock_data) {
288
+                if ($stock_data) {
289 289
                     $record = array_merge($record, $stock_data);
290 290
                 }
291 291
 
Please login to merge, or discard this patch.