| 1 |
<?php |
| 2 |
|
| 3 |
namespace TierPricingTable\Admin\Import; |
| 4 |
|
| 5 |
use WC_Product ; |
| 6 |
class Woocommerce |
| 7 |
{ |
| 8 |
/** |
| 9 |
* Import constructor. |
| 10 |
*/ |
| 11 |
public function __construct() |
| 12 |
{ |
| 13 |
add_filter( 'woocommerce_csv_product_import_mapping_options', [ $this, 'addColumnsToImporter' ] ); |
| 14 |
add_filter( 'woocommerce_csv_product_import_mapping_default_columns', [ $this, 'addColumnToMappingScreen' ] ); |
| 15 |
add_filter( |
| 16 |
'woocommerce_product_import_pre_insert_product_object', |
| 17 |
[ $this, 'processImport' ], |
| 18 |
10, |
| 19 |
2 |
| 20 |
); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Register the 'Tiered pricing' column in the importer. |
| 25 |
* |
| 26 |
* @param array $options |
| 27 |
* |
| 28 |
* @return array $options |
| 29 |
*/ |
| 30 |
public function addColumnsToImporter( $options ) |
| 31 |
{ |
| 32 |
$options['tiered_price_fixed'] = __( 'Fixed Tiered prices', 'tier-pricing-table' ); |
| 33 |
return $options; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Add automatic mapping support for 'Tiered pricing'. |
| 38 |
* |
| 39 |
* @param array $columns |
| 40 |
* |
| 41 |
* @return array $columns |
| 42 |
*/ |
| 43 |
public function addColumnToMappingScreen( $columns ) |
| 44 |
{ |
| 45 |
$columns[__( 'Fixed Tiered prices', 'tier-pricing-table' )] = 'tiered_price_fixed'; |
| 46 |
return $columns; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Process the data read from the CSV file. |
| 51 |
* |
| 52 |
* @param WC_Product $product - Product being imported or updated. |
| 53 |
* @param array $data - CSV data read for the product. |
| 54 |
* |
| 55 |
* @return WC_Product $object |
| 56 |
*/ |
| 57 |
public function processImport( $product, $data ) |
| 58 |
{ |
| 59 |
|
| 60 |
if ( !empty($data['tiered_price_fixed']) ) { |
| 61 |
$data = $this->decodeExport( $data['tiered_price_fixed'] ); |
| 62 |
if ( $data && !empty($data) ) { |
| 63 |
$product->update_meta_data( '_fixed_price_rules', $data ); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
return $product; |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Decode export file format to array |
| 72 |
* |
| 73 |
* @param string $data |
| 74 |
* |
| 75 |
* @return array |
| 76 |
*/ |
| 77 |
protected function decodeExport( $data ) |
| 78 |
{ |
| 79 |
$rules = explode( ",", $data ); |
| 80 |
$data = []; |
| 81 |
if ( $rules ) { |
| 82 |
foreach ( $rules as $rule ) { |
| 83 |
$rule = explode( ':', $rule ); |
| 84 |
if ( isset( $rule[0] ) && isset( $rule[1] ) ) { |
| 85 |
$data[intval( $rule[0] )] = $rule[1]; |
| 86 |
} |
| 87 |
} |
| 88 |
} |
| 89 |
$data = array_filter( $data ); |
| 90 |
return ( !empty($data) ? $data : [] ); |
| 91 |
} |
| 92 |
|
| 93 |
} |