Skip to content

Instantly share code, notes, and snippets.

@lsolesen
Created March 29, 2017 13:12
Show Gist options
  • Save lsolesen/e5a08777eccaa1a03d21e04212d77e98 to your computer and use it in GitHub Desktop.
Save lsolesen/e5a08777eccaa1a03d21e04212d77e98 to your computer and use it in GitHub Desktop.
Export products from Drupal Commerce Kickstart to Shoporama
<?php
/**
* Run using drush scr export.php
*/
// Require client for Shoporama
require_once __DIR__ . '/../shoporama-php-sdk/vendor/autoload.php';
use Shoporama\Client;
use Shoporama\Request;
$request = new Request('apikey');
$client = new Client($request);
//This function intelligently trims a body of text to a certain
//number of words, but will not break a sentence.
function excerpt($string, $truncation = 15) {
$string = strip_tags($string);
$matches = preg_split("/\s+/", $string);
$count = count($matches);
if($count > $truncation) {
//Grab the last word; we need to determine if
//it is the end of the sentence or not
$last_word = strip_tags($matches[$truncation-1]);
$lw_count = strlen($last_word);
//The last word in our truncation has a sentence ender
if($last_word[$lw_count-1] == "." || $last_word[$lw_count-1] == "?" || $last_word[$lw_count-1] == "!") {
for($i=$truncation;$i<$count;$i++) {
unset($matches[$i]);
}
//The last word in our truncation doesn't have a sentence ender, find the next one
} else {
//Check each word following the last word until
//we determine a sentence's ending
for($i=($truncation);$i<$count;$i++) {
if($ending_found != TRUE) {
$len = strlen(strip_tags($matches[$i]));
if($matches[$i][$len-1] == "." || $matches[$i][$len-1] == "?" || $matches[$i][$len-1] == "!") {
//Test to see if the next word starts with a capital
if($matches[$i+1][0] == strtoupper($matches[$i+1][0])) {
$ending_found = TRUE;
}
}
} else {
unset($matches[$i]);
}
}
}
//Check to make sure we still have a closing <p> tag at the end
$body = implode(' ', $matches);
if(substr($body, -4) != "</p>") {
$body = $body;
}
return $body;
} else {
return $string;
}
}
$suppliers_json = $client->get('/supplier');
$suppliers = json_decode($suppliers_json->getBody(), true);
$plastic_profile_id = 16009;
$plastic_json = $client->get('/profile-attribute-value?attribute_id=' . $plastic_profile_id);
$plastics = json_decode($plastic_json->getBody(), true);
$types_json = $client->get('/profile-attribute-value?attribute_id=16010');
$types = json_decode($types_json->getBody(), true);
$levels_json = $client->get('/profile-attribute-value?attribute_id=16011');
$levels = json_decode($levels_json->getBody(), true);
$variant_profile_id = 16008;
$variants_json = $client->get('/profile-attribute-value?attribute_id=' . $variant_profile_id);
$variants = json_decode($variants_json->getBody(), true);
$categories_json = $client->get('/category');
$categories = json_decode($categories_json->getBody(), true);
// Bootstrap Drupal.
$drupal_path = $_SERVER['DOCUMENT_ROOT'];
define('DRUPAL_ROOT', $drupal_path);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Gettting to work
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'discgolf')
->propertyCondition('status', 1);
$result = $query->execute();
if (!empty($result['node'])) {
$nids = array_keys($result['node']);
foreach ($nids as $nid) {
$data = array();
$shoporama = array();
$test_image_path = '';
$category_ids = array();
$discount = 0;
$related = array();
$reserve_images = array();
$node_id = $nid;
$node = node_load($nid, NULL, TRUE);
$wrapper = entity_metadata_wrapper('node', $node);
$title = $node->title;
$body = $wrapper->body->value()['safe_value'];
$url = drupal_get_path_alias('node/' . $node->nid);
// field_collection;
$collection = $wrapper->field_collection->value()->name;
// field_category
$category = $type = $wrapper->field_category->value()->name;
// field_brand;
$brand = $wrapper->field_brand->value()->name;
$supplier = $brand;
//3484 - Sportsartikler > Friluftsliv > Udendørsspil > Discgolf
$data["meta"] = "g:google_product_category=3484";
if (empty($brand)) {
$brand = $supplier = 'Unknown';
} else {
$data["meta"] .= "\ng:brand=" . $brand;
}
$data["meta"] .= "\ng:product_type=" . $collection . " & " . $category;
// field_level
$level = $wrapper->field_level->value()->name;
// field_discount_group
$discount_group = $wrapper->field_discount_group->value()->name;
// Shoporama values
$data['name'] = $title;
$data['profile_id'] = 12254;
$data['rewrite_url'] = $url;
$data['description'] = $body;
$data['list_description'] = excerpt($body);
$data['shipping_weight'] = 200;
$data['auto_offline'] = 0;
$data['meta_title'] = '[NAME] - ' . $category . ' fra [SUPPLIER] - kun [PRICE],-';
$data['meta_description'] = '[NAME] fra [SUPPLIER] er en ' . strtolower($category) . ' golfdisc til en ' . strtolower($level) . '.';
$data['canonical_id'] = "";
$data['allow_negative_stock'] = 0;
$data['is_online'] = 1;
$data['own_id'] = $node_id;
print 'Importing ' . $node_id . "\n";
// Supplier
$found_supplier = array_search($supplier, array_column($suppliers, 'name'));
$supplier_id = $suppliers[$found_supplier]['supplier_id'];
$data['supplier_id'] = $supplier_id;
// Categories
$found_category = array_search($collection, array_column($categories, 'name'));
$category_id = $categories[$found_category]['category_id'];
$data['main_category_id'] = $category_id;
$category_ids[] = $category_id;
$found_category = array_search($level, array_column($categories, 'name'));
if ($found_category) {
$category_ids[] = $categories[$found_category]['category_id'];
}
$found_category = array_search($type, array_column($categories, 'name'));
if ($found_category) {
$category_ids[] = $categories[$found_category]['category_id'];
} else {
echo 'Did not find' . $type;
}
$data['categories'] = $category_ids;
// Attributes: Levels
$found_level = array_search($level, array_column($levels, 'val'));
$level_id = $levels[$found_level]['attribute_value_id'];
// Attributes: types
$found_type = array_search($category, array_column($types, 'val'));
$type_id = $types[$found_type]['attribute_value_id'];
$data["attributes"] = array(
// Type 16010
array(
"attribute_id" => 16010,
"value" => $type_id
),
// Niveau 16011
array(
"attribute_id" => 16011,
"value" => $level_id
),
);
// field_product;
foreach ($wrapper->field_product->value() as $pid) {
$product_wrapper = entity_metadata_wrapper('commerce_product', $pid->product_id);
// field_plastic
$plastic = $product_wrapper->field_plastic->value()->name;
if (empty($shoporama[$plastic])) {
$shoporama[$plastic] = $data;
$shoporama[$plastic]['name'] .= ' - ' . $plastic;
}
$product_title = $product_wrapper->title_field->value();
// billysbilling_product_id
$billy_id = $product_wrapper->billysbilling_product_id->value();
// commerce_price
$price = $product_wrapper->commerce_price->value();
$base_price = $price['data']['components'][0]['price']['amount'] / 100;
// commerce_stock
$stock = $product_wrapper->commerce_stock->value()[0];
// field_color
$color = $product_wrapper->field_color->value()->name;
// field_weight
$weight = $product_wrapper->field_weight->value()->name;
$shoporama[$plastic]['price'] = $base_price;
if ($shoporama[$plastic]['price'] == 0) {
$shoporama[$plastic]['price'] = 100;
}
$sell_price = commerce_product_calculate_sell_price($pid);
foreach ($sell_price as $pr) {
foreach ($pr['components'] as $p) {
if (substr($p['name'], 0, 9) == 'discount|') {
$discount = abs($p['price']['amount']) / 100 * 0.8;
}
}
}
if ($discount > 0) {
$shoporama[$plastic]['sale_price'] = $shoporama[$plastic]['price'] - $discount;
}
// Shoporama SKU
$own_id = $nid . '-' . $pid->product_id;
// Variants
$variant = $color . ', ' . $weight;
$found_variant = array_search($variant, array_column($variants, 'val'));
if ($found_variant === false) {
$new_data = array(
"attribute_id" => $variant_profile_id,
"val" => $variant,
"tag" => ""
);
$response = $client->post('/profile-attribute-value', $new_data);
$interpret = json_decode($response->getBody(), true);
$variant_id = $interpret['attribute_value_id'];
$variants_json = $client->get('/profile-attribute-value?attribute_id=' . $variant_profile_id);
$variants = json_decode($variants_json->getBody(), true);
}
$variant_id = $variants[$found_variant]['attribute_value_id'];
// Vægt og farve = 16008
$shoporama[$plastic]["stock_settings"][] =
array(
"attribute_id" => 16008,
"attribute_value_id" => $variant_id,
"sec_own_id" => $billy_id,
"own_id" => $own_id
);
// Attributes: types
$found_plastic = array_search($plastic, array_column($plastics, 'val'));
if ($found_plastic === false) {
$new_data = array(
"attribute_id" => $plastic_profile_id,
"val" => $plastic,
"tag" => ""
);
$response = $client->post('/profile-attribute-value', $new_data);
$interpret = json_decode($response->getBody(), true);
$plastic_id = $interpret['attribute_value_id'];
$plastic_json = $client->get('/profile-attribute-value?attribute_id=' . $plastic_profile_id);
$plastics = json_decode($plastic_json->getBody(), true);
}
$plastic_id = $types[$found_plastic]['attribute_value_id'];
// Plastik 16009
$shoporama[$plastic]["attributes"][] =
array(
"attribute_id" => 16009,
"value" => $plastic_id
);
// field_images
foreach ($pid->field_images[LANGUAGE_NONE] as $img) {
$image_path = drupal_realpath($img['uri']);
$base_encoded_image = base64_encode(file_get_contents($image_path));
if ($base_encoded_image == $test_image_path) {
continue;
}
$shoporama[$plastic]["images"][] =
array(
"data" => $base_encoded_image,
"description" => $shoporama[$plastic]['name']
);
$test_image_path = $base_encoded_image;
}
if (empty($shoporama[$plastic]["images"])) {
$shoporama[$plastic]["images"] = $reserve_images;
}
$reserve_images = $shoporama[$plastic]["images"];
$stock_data[] =
array(
"SKU" => $own_id,
"stock" => $stock,
"price" => $shoporama[$plastic]['price'] * 0.6
);
// Put some products on the front page
if ($stock > 0 and rand(1, 10) == 4) {
$shoporama[$plastic]['categories'][] = 56394;
}
// TODO - Ville være ret awesome med automatisk indsættelse :)
$shoporama[$plastic]['related'] = $related;
}
foreach ($shoporama as $values) {
$response = $client->post('/product', $values);
$created_product = json_decode($response->getBody(), true);
$related[] = $created_product['product_id'];
}
foreach ($related as $r) {
$data_related = array('related' => $related);
$client->patch('/product/' . $r, $data_related);
}
$client->post('/stock', $stock_data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment