Passed
Pull Request — master (#168)
by
unknown
02:08
created
classes/class-send-products.php 2 patches
Indentation   +235 added lines, -235 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,242 +45,242 @@  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
-         * Get attributes from product
109
-         *
110
-         * @param  mixed $product Product to check   
111
-         * @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.
112
-         */
113
-        public static function get_product_attributes($product)
114
-        {
115
-            $rawAttributes = $product->get_attributes();
116
-            $numericRangeAttributes = ["pa_height", "pa_flowermonth"];
117
-            if (!$rawAttributes) {
118
-                return false;
119
-            }
120
-
121
-            $attributes = [];
122
-            foreach ($rawAttributes as $attribute) {
123
-                if ($attribute->get_variation()) {
124
-                    continue;
125
-                }
126
-                $name = $attribute->get_name();
127
-                if ($attribute->is_taxonomy()) {
128
-                    $terms = wp_get_post_terms($product->get_id(), $name, 'all');
129
-                    $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
+		 * Get attributes from product
109
+		 *
110
+		 * @param  mixed $product Product to check   
111
+		 * @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.
112
+		 */
113
+		public static function get_product_attributes($product)
114
+		{
115
+			$rawAttributes = $product->get_attributes();
116
+			$numericRangeAttributes = ["pa_height", "pa_flowermonth"];
117
+			if (!$rawAttributes) {
118
+				return false;
119
+			}
120
+
121
+			$attributes = [];
122
+			foreach ($rawAttributes as $attribute) {
123
+				if ($attribute->get_variation()) {
124
+					continue;
125
+				}
126
+				$name = $attribute->get_name();
127
+				if ($attribute->is_taxonomy()) {
128
+					$terms = wp_get_post_terms($product->get_id(), $name, 'all');
129
+					$tax_terms = array();
130 130
                     
131
-                    // interpolate all values when found in numericRangeAttributes
132
-                    if (array_search($name, $numericRangeAttributes, true) !== false) {
133
-                        $integers = array();
134
-                        foreach ($terms as $term) {
135
-                            array_push($integers, (int) $term->name);
136
-                        }
137
-                        for ($i = min($integers); $i <= max($integers); $i++) {
138
-                            array_push($tax_terms, $i);
139
-                        }
140
-                    } else {
141
-                        // strings
142
-                        foreach ($terms as $term) {
143
-                            $single_term = esc_html($term->name);
144
-                            array_push($tax_terms, $single_term);
145
-                        }
146
-                    }
147
-                }
148
-                $attributes[$name] = $tax_terms;
149
-            }
150
-            return $attributes;
151
-        }
152
-
153
-        /**
154
-         * Send WooCommerce products to Algolia
155
-         *
156
-         * @param Int $id Product to send to Algolia if we send only a single product
157
-         * @return void
158
-         */
159
-        public static function send_products_to_algolia($id = '')
160
-        {
161
-            /**
162
-             * Remove classes from plugin URL and autoload Algolia with Composer
163
-             */
164
-
165
-            $base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
166
-            require_once $base_plugin_directory . '/vendor/autoload.php';
167
-
168
-            /**
169
-             * Fetch the required variables from the Settings API
170
-             */
171
-
172
-            $algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APP_ID);
173
-            $algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
174
-
175
-            $algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
176
-            $algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
177
-
178
-            $algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
179
-            $algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
180
-
181
-            /**
182
-             * Display admin notice and return if not all values have been set
183
-             */
184
-
185
-            Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
186
-
187
-            /**
188
-             * Initiate the Algolia client
189
-             */
190
-            self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
191
-
192
-            /**
193
-             * Check if we can connect, if not, handle the exception, display an error and then return
194
-             */
195
-            self::can_connect_to_algolia();
196
-
197
-            /**
198
-             * Initialize the search index and set the name to the option from the database
199
-             */
200
-            $index = self::$algolia->initIndex($algolia_index_name);
201
-
202
-            /**
203
-             * Setup arguments for sending all products to Algolia
204
-             *
205
-             * Limit => -1 means we send all products
206
-             */
207
-            $arguments = array(
208
-                'status'   => 'publish',
209
-                'limit'    => -1,
210
-                'paginate' => false,
211
-            );
212
-
213
-            /**
214
-             * Setup arguments for sending only a single product
215
-             */
216
-            if (isset($id) && '' !== $id) {
217
-                $arguments = array(
218
-                    'status'   => 'publish',
219
-                    'include'  => array($id),
220
-                    'paginate' => false,
221
-                );
222
-            }
223
-
224
-            /**
225
-             * Fetch all products from WooCommerce
226
-             *
227
-             * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
228
-             */
229
-            $products =
230
-                /** @scrutinizer ignore-call */
231
-                wc_get_products($arguments);
232
-
233
-            if (empty($products)) {
234
-                return;
235
-            }
236
-            $records = array();
237
-            $record  = array();
238
-
239
-            foreach ($products as $product) {
240
-                /**
241
-                 * Set sale price or regular price based on product type
242
-                 */
243
-                $product_type_price = self::get_product_type_price($product);
244
-                $sale_price = $product_type_price['sale_price'];
245
-                $regular_price = $product_type_price['regular_price'];
246
-
247
-                /**
248
-                 * Extract image from $product->get_image()
249
-                 */
250
-                preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
251
-                $product_image = array_pop($result);
252
-
253
-                /**
254
-                 * Build the record array using the information from the WooCommerce product
255
-                 */
256
-                $record['objectID']                      = $product->get_id();
257
-                $record['product_name']                  = $product->get_name();
258
-                $record['product_image']                 = $product_image;
259
-                $record['short_description']             = $product->get_short_description();
260
-                $record['regular_price']                 = $regular_price;
261
-                $record['sale_price']                    = $sale_price;
262
-                $record['on_sale']                       = $product->is_on_sale();
263
-                $record['attributes']                    = self::get_product_attributes($product);
264
-                $records[] = $record;
265
-            }
266
-            wp_reset_postdata();
267
-
268
-            /**
269
-             * Send the information to Algolia and save the result
270
-             * If result is NullResponse, print an error message
271
-             */
272
-            $result = $index->saveObjects($records);
273
-
274
-            if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
275
-                wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
276
-            }
277
-
278
-            /**
279
-             * Display success message
280
-             */
281
-            echo '<div class="notice notice-success is-dismissible">
131
+					// interpolate all values when found in numericRangeAttributes
132
+					if (array_search($name, $numericRangeAttributes, true) !== false) {
133
+						$integers = array();
134
+						foreach ($terms as $term) {
135
+							array_push($integers, (int) $term->name);
136
+						}
137
+						for ($i = min($integers); $i <= max($integers); $i++) {
138
+							array_push($tax_terms, $i);
139
+						}
140
+					} else {
141
+						// strings
142
+						foreach ($terms as $term) {
143
+							$single_term = esc_html($term->name);
144
+							array_push($tax_terms, $single_term);
145
+						}
146
+					}
147
+				}
148
+				$attributes[$name] = $tax_terms;
149
+			}
150
+			return $attributes;
151
+		}
152
+
153
+		/**
154
+		 * Send WooCommerce products to Algolia
155
+		 *
156
+		 * @param Int $id Product to send to Algolia if we send only a single product
157
+		 * @return void
158
+		 */
159
+		public static function send_products_to_algolia($id = '')
160
+		{
161
+			/**
162
+			 * Remove classes from plugin URL and autoload Algolia with Composer
163
+			 */
164
+
165
+			$base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
166
+			require_once $base_plugin_directory . '/vendor/autoload.php';
167
+
168
+			/**
169
+			 * Fetch the required variables from the Settings API
170
+			 */
171
+
172
+			$algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APP_ID);
173
+			$algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
174
+
175
+			$algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
176
+			$algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
177
+
178
+			$algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
179
+			$algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
180
+
181
+			/**
182
+			 * Display admin notice and return if not all values have been set
183
+			 */
184
+
185
+			Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
186
+
187
+			/**
188
+			 * Initiate the Algolia client
189
+			 */
190
+			self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
191
+
192
+			/**
193
+			 * Check if we can connect, if not, handle the exception, display an error and then return
194
+			 */
195
+			self::can_connect_to_algolia();
196
+
197
+			/**
198
+			 * Initialize the search index and set the name to the option from the database
199
+			 */
200
+			$index = self::$algolia->initIndex($algolia_index_name);
201
+
202
+			/**
203
+			 * Setup arguments for sending all products to Algolia
204
+			 *
205
+			 * Limit => -1 means we send all products
206
+			 */
207
+			$arguments = array(
208
+				'status'   => 'publish',
209
+				'limit'    => -1,
210
+				'paginate' => false,
211
+			);
212
+
213
+			/**
214
+			 * Setup arguments for sending only a single product
215
+			 */
216
+			if (isset($id) && '' !== $id) {
217
+				$arguments = array(
218
+					'status'   => 'publish',
219
+					'include'  => array($id),
220
+					'paginate' => false,
221
+				);
222
+			}
223
+
224
+			/**
225
+			 * Fetch all products from WooCommerce
226
+			 *
227
+			 * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
228
+			 */
229
+			$products =
230
+				/** @scrutinizer ignore-call */
231
+				wc_get_products($arguments);
232
+
233
+			if (empty($products)) {
234
+				return;
235
+			}
236
+			$records = array();
237
+			$record  = array();
238
+
239
+			foreach ($products as $product) {
240
+				/**
241
+				 * Set sale price or regular price based on product type
242
+				 */
243
+				$product_type_price = self::get_product_type_price($product);
244
+				$sale_price = $product_type_price['sale_price'];
245
+				$regular_price = $product_type_price['regular_price'];
246
+
247
+				/**
248
+				 * Extract image from $product->get_image()
249
+				 */
250
+				preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
251
+				$product_image = array_pop($result);
252
+
253
+				/**
254
+				 * Build the record array using the information from the WooCommerce product
255
+				 */
256
+				$record['objectID']                      = $product->get_id();
257
+				$record['product_name']                  = $product->get_name();
258
+				$record['product_image']                 = $product_image;
259
+				$record['short_description']             = $product->get_short_description();
260
+				$record['regular_price']                 = $regular_price;
261
+				$record['sale_price']                    = $sale_price;
262
+				$record['on_sale']                       = $product->is_on_sale();
263
+				$record['attributes']                    = self::get_product_attributes($product);
264
+				$records[] = $record;
265
+			}
266
+			wp_reset_postdata();
267
+
268
+			/**
269
+			 * Send the information to Algolia and save the result
270
+			 * If result is NullResponse, print an error message
271
+			 */
272
+			$result = $index->saveObjects($records);
273
+
274
+			if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
275
+				wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
276
+			}
277
+
278
+			/**
279
+			 * Display success message
280
+			 */
281
+			echo '<div class="notice notice-success is-dismissible">
282 282
 					 	<p>' . esc_html__('Product(s) sent to Algolia.', 'algolia-woo-indexer') . '</p>
283 283
 				  		</div>';
284
-        }
285
-    }
284
+		}
285
+	}
286 286
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 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,
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
         {
115 115
             $rawAttributes = $product->get_attributes();
116 116
             $numericRangeAttributes = ["pa_height", "pa_flowermonth"];
117
-            if (!$rawAttributes) {
117
+            if ( ! $rawAttributes) {
118 118
                 return false;
119 119
             }
120 120
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
             $algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
177 177
 
178 178
             $algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
179
-            $algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
179
+            $algolia_index_name = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
180 180
 
181 181
             /**
182 182
              * Display admin notice and return if not all values have been set
Please login to merge, or discard this patch.