Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Automattic\WooCommerce\Client;
- class ImportController {
- //Database-like structure (config)
- const DOORS = [
- [
- 'id' => 7,
- 'name' => '1 Дверь'
- ],
- [
- 'id' => 8,
- 'name' => '2 Дверь'
- ],
- [
- 'id' => 9,
- 'name' => '3 Дверь'
- ],
- [
- 'id' => 10,
- 'name' => '4 Дверь'
- ],
- ];
- const MATERIALS = [
- 'МДФ',
- 'Зеркало',
- 'Стекло'
- ];
- const COLORS = [
- 1 => 'Бежевый',
- 2 => 'Белый'
- ];
- const MILLING = [
- 1 => 'Верона',
- 2 =>'Ламель'
- ];
- const DOORKNOBS = [
- 'Л' => 'Слева',
- 'П' => 'Справа'
- ];
- /**
- * Show form for creation new import
- * @return mixed
- */
- static function show()
- {
- return view('form');
- }
- /**
- * Import
- */
- static function store() {
- global $wpdb;
- $image = $_FILES['image'];
- $params = explode( '-', $image['name'] );
- //Build attributes array
- $attributes = [];
- //Doors
- $doors = str_split( $params[1] );
- foreach ( $doors as $iteration => $value ) {
- $door = self::DOORS[ $iteration ];
- $value = self::MATERIALS[ $value ];
- array_push( $attributes, [
- 'id' => $door['id'],
- 'name' => $door['name'],
- 'option' => $value
- ] );
- }
- //Color
- $color = self::COLORS[ $params[2][0] ];
- array_push( $attributes, [
- 'id' => 4,
- 'name' => 'Цвет',
- 'option' => $color
- ] );
- //Milling
- $milling = self::MILLING[ $params[2][1] ];
- array_push( $attributes, [
- 'id' => 5,
- 'name' => 'Фрезеровка',
- 'option' => $milling
- ] );
- //Get product id
- $productTitle = $params[0];
- $productID = $wpdb->get_var( "SELECT ID from $wpdb->posts WHERE post_title LIKE \"%$productTitle%\"" );
- try {
- if ( empty( $productID ) ) {
- throw new Exception(
- "Product not found, please create a product that contains the title '$productTitle'"
- );
- }
- //Set-up woocommerce api
- $woocommerce = new Client(
- 'http://promebel.local', // Your store URL
- 'ck_29f81bf934d967f7525c257d74bd82fcff01ba1f', // Your consumer key
- 'cs_dc0f8b192a3f84d82b48a0f4cf79bfbcf02d7fb7', // Your consumer secret
- [
- 'wp_api' => true, // Enable the WP REST API integration
- 'version' => 'wc/v3' // WooCommerce WP REST API version
- ]
- );
- //Get product vatiations
- $variations = $woocommerce->get( "products/$productID/variations");
- //Check if variation exits
- $exits = false;
- foreach ( $variations as $variation ) {
- if ( $variation->attributes === $attributes ) {
- $exits = true;
- break;
- }
- }
- if (!$exits){
- $photoId = upload_photo($image);
- $woocommerce->post("products/$productID/variations" , [
- 'image' => [
- 'id' => $photoId
- ],
- 'attributes' => $attributes
- ]);
- }
- } catch(Exception $e) {
- echo 'Error: ' .$e->getMessage();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement