| Current Path : /home/rtorresani/www/scripts/import/include/ |
| Current File : //home/rtorresani/www/scripts/import/include/createAttributeAndSetAttribute.php |
<?php
function initConnection($api, $instance) {
switch($instance) {
case 'MAGENTO-TEST':
$host = 'https://magento.test.indacotrentino.com/';
$consumerKey = '610dee75s27oe0jlx7dx8cyr5k275861';
$consumerSecret = 'aw0nis1v3kst9gxlozdewmf8pnotscxf';
$accessToken = '0kufmoncdszyzs13bkvyrkjxlgu593bj';
$accessTokenSecret = 'jvdbnuw6w4cfbv4o18cg44p400ap4ad6';
break;
case 'INDACO-38121':
$host = 'http://indaco.38121.it/';
$consumerKey = 'yh9nspb82lqo1h2buqi6l90hqltzwchb';
$consumerSecret = 'i1j57ms6b418b5z4d8q6uq3unyc4s0nn';
$accessToken = 't0nj8c2n71y6gmsb8t5mzwc9i70ly2y5';
$accessTokenSecret = 'u66odr3bnc5gr93bxv9rjg7ptx35psuc';
break;
case 'INDACO2-38121':
$host = 'https://indaco2.38121.it/';
$consumerKey = 'qiz7m6tkxl92lpgk624aecbbr648t8i9';
$consumerSecret = '1l4431yo7qo54fyeuis8cu35inqdpp84';
$accessToken = 'irfnvon6ku6vyn6a7efcf5mdf8j06g6c';
$accessTokenSecret = 'ra6ctr07sk5vud2x43qpkcrng0rhtmpq';
break;
case 'INDACO4-38121':
$host = 'https://indaco4.38121.it/';
$consumerKey = 'enqqh6nemwmloa8zcauli7t1updudoiu';
$consumerSecret = 'd5nq8imhunv5s0jgkivwpvz03btg4zol';
$accessToken = 'f3jwzuzuqk6hu2u3blwh2ezm183if8l2';
$accessTokenSecret = 'bjun4wdhvl90dvfvn099ar6xc0o4wdrd';
break;
case 'INDACOTRENTINO.COM':
$host = 'https://www.indacotrentino.com/';
$consumerKey = '610dee75s27oe0jlx7dx8cyr5k275861';
$consumerSecret = 'aw0nis1v3kst9gxlozdewmf8pnotscxf';
$accessToken = '0kufmoncdszyzs13bkvyrkjxlgu593bj';
$accessTokenSecret = 'jvdbnuw6w4cfbv4o18cg44p400ap4ad6';
break;
default:
die("Check instance server: ".$instance."\n");
}
$api->setConsumerKey($consumerKey);
$api->setConsumerSecret($consumerSecret);
$api->setAccesToken($accessToken);
$api->setAccesTokenSecret($accessTokenSecret);
$api->setUrl($host . 'rest/%storecode/V1/');
$api->setStoreCode('all');
$api->init();
}
function getAttributeGroupId($api, $attributeSetId, $nameGroup, $sort=null) {
createAttributeSetGroup($api, $nameGroup, $attributeSetId, $sort);
$attributeGroupId = getAttributeSetGroupIdByNameAndId($api, $nameGroup, $attributeSetId);
if ($attributeGroupId < 1) {
die ("Check getAttributeGroupId result is " . $attributeSetId);
}
return $attributeGroupId;
}
function createAttributeSetGroup($api, $nameGroup, $attributeSetId, $sort=19) {
$attributeSetGroupId = getAttributeSetGroupIdByNameAndId($api, $nameGroup, $attributeSetId);
if ($attributeSetGroupId == 0) {
$data = '
{
"group": {
"attribute_group_name": "' . $nameGroup . '",
"attribute_set_id": "' . $attributeSetId . '",
"extension_attributes": {
"sort_order": "' . $sort . '"
}
}
}';
$result = $api->call('products/attribute-sets/groups', json_decode($data), 'POST');
} else {
$data = '
{
"group": {
"attribute_group_id": "' . $attributeSetGroupId . '",
"attribute_group_name": "' . strtoupper($nameGroup) . '",
"attribute_set_id": "' . $attributeSetId . '",
"extension_attributes": {
"sort_order": "' . $sort . '"
}
}
}';
$result = $api->call('products/attribute-sets/' . $attributeSetId . '/groups', json_decode($data), 'PUT');
}
}
function getAttributeSetGroupIdByNameAndId($api, $nameGroup, $attributeSetId) {
$data = '
{
"searchCriteria": {
"filter_groups": [
{
"filters": [
{
"field": "attribute_set_id",
"value": "' . $attributeSetId . '",
"condition_type": "eq"
}
]
}
]
}
}';
$result = $api->call('products/attribute-sets/groups/list/', json_decode($data), 'GET');
$attributeGroupId = 0;
foreach ($result->items as $item) {
if ($item->attribute_group_name == $nameGroup) {
$attributeGroupId = $item->attribute_group_id;
}
}
return $attributeGroupId;
}
function getAttributeSetId($api, $nameSetAttribute) {
createAttributeSet($api, $nameSetAttribute);
$attributeSet = getAttributeSetByName($api, $nameSetAttribute);
$attributeSetId = 0;
if ($attributeSet->total_count == 1) {
$attributeSetId = $attributeSet->items[0]->attribute_set_id;
} elseif ($attributeSet->total_count > 1) {
$attributeSetId = -1;
}
if ($attributeSetId<1) {
die ("Check getAttributeSetId result is " . $attributeSetId);
}
return $attributeSetId;
}
function createAttributeSet( $api, $nameSetAttribute, $sort=10) {
$attributeSet = getAttributeSetByName($api, $nameSetAttribute);
if ($attributeSet->total_count == 0) {
$data = '
{
"attributeSet": {
"attribute_set_name": "' . $nameSetAttribute . '",
"sort_order": 10,
"entity_type_id": "4"
},
"skeletonId": "4"
}';
$result = $api->call('products/attribute-sets', json_decode($data), 'POST');
}
}
function getAttributeSetByName($api, $name) {
$data = '
{
"searchCriteria": {
"filter_groups": [
{
"filters": [
{
"field": "attribute_set_name",
"value": "' . $name . '",
"condition_type": "eq"
}
]
}
]
}
}';
$result = $api->call('products/attribute-sets/sets/list/', json_decode($data), 'GET');
return ($result);
}
function getProductAttribute($api, $code) {
$data = getSearchCriteriaJson('attribute_code', $code, 'eq');
return $api->call('products/attributes/', json_decode($data), 'GET');
}
function getSearchCriteriaJson($field, $value, $conditionType) {
return '
{
"searchCriteria": {
"filter_groups": [
{
"filters": [
{
"field": "' . $field . '",
"value": "' . $value . '",
"condition_type": "' . $conditionType . '"
}
]
}
]
}
}';
}
function importCsvAttributeAndSetAttribute($api, $fileName, $attributeSetId, $attributeGroupId) {
$attributeDefault = [
"attribute" => [
"is_wysiwyg_enabled" => false,
"is_html_allowed_on_front" => false,
"used_for_sort_by" => false,
"is_filterable" => false,
"is_filterable_in_search" => false,
"is_used_in_grid" => false,
"is_visible_in_grid" => false,
"is_filterable_in_grid" => false,
"position" => 0,
// "apply_to" => [],
"is_searchable" => "0",
"is_comparable" => "1",
"is_used_for_promo_rules" => "0",
"is_visible_on_front" => "0",
"used_in_product_listing" => "0",
"is_visible" => true,
"scope" => "store", // "website" "global",
"attribute_code" => "indaco_default",
"frontend_input" => "text",
"entity_type_id" => "4",
"is_required" => false,
"is_user_defined" => true,
"default_frontend_label" => "INDACODEFAULT",
"frontend_labels" => null,
"backend_type" => "text",
"default_value" => "",
"source_model" => "Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table",
"is_unique" => "0"
]
];
// "source_model" => "Magento%5C%5CEav%5C%5CModel%5C%5CEntity%5C%5CAttribute%5C%5CSource%5C%5CTable",
$attributeDefaultText = [
"is_visible_in_advanced_search" => "1",
];
$row = 1;
$header = [];
// flag if is present column with name 'import': imported only row with value import=1
$import = -1;
if (($handle = fopen($fileName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$attributeCustom = $attributeDefault;
$num = count($data);
$position = 0;
if ($row == 1) {
for ($c=0; $c < $num; $c++) {
$header[$c] = trim($data[$c]);
if (trim($data[$c]) == 'import') { $import = $c; }
}
} else {
if ($import==-1 || $data[$import]==1) {
$attributeCode = '';
$options = '';
for ($c=0; $c < $num; $c++) {
if ($import<>$c && strlen(trim($data[$c]))>0) {
if (substr($data[$c], 0, 1) === '|' && substr($data[$c], -1) === '|') {
if ($header[$c] == 'options') {
$options = trim($data[$c]);
} else {
trim($data[$c], '|');
$count = 0;
$labels = '';
$sep = '{';
foreach (explode('|', $data[$c]) as $item) {
if (trim($item)) {
$labels .= $sep . '"label":"' . $item .'"}';
$sep = ',{';
$count++;
}
}
$attributeCustom['attribute'][$header[$c]] = '['.$labels.']';
}
} else {
switch ($header[$c]) {
case 'default_frontend_label':
$attributeCustom['attribute'][$header[$c]] = trim($data[$c]);
// $attributeCustom['attribute'][$header[$c]] = "'".trim($data[$c])."'";
break;
case 'position':
// $attributeCustom['attribute'][$header[$c]] = trim($data[$c]);
$position = trim($data[$c]);
default :
$attributeCustom['attribute'][ $header[$c]] = trim($data[$c]);
break;
}
// echo "\n".$header[$c]."=".trim($data[$c])."\n";
}
if ($header[$c] == 'attribute_code') {
$attribute_code = trim($data[$c]);
}
}
}
// echo ">> " . $attribute_code . "\n";
// echo var_dump($attributeCustom);
$response = json_decode(json_encode(getProductAttribute($api, $attribute_code)), true);
// echo var_dump($response);
if (!(array_key_exists("items", $response) && array_key_exists("0", $response['items']) && array_key_exists("attribute_code", $response['items'][0])) ) {
echo "- insert: $attribute_code\n";
$response = $api->call('products/attributes', $attributeCustom, 'POST');
} else {
$attributeCustom['attribute']['attribute_id'] = $response['items'][0]['attribute_id'];
//$attributeCustom['attribute']['default_value'] = 'lorem';
echo "- update $attribute_code\n";
$response = $api->call('products/attributes/'.$attribute_code, $attributeCustom, 'PUT');
}
$response = json_decode(json_encode($response), true);
if ($options<>'') {
trim($options, '|');
$countItem = 1;
$labels = '';
$listOptions = [];
$resultListOptions = $api->call('products/attributes/'.$attribute_code."/options", null, 'GET');
foreach ($resultListOptions as $itemOption) {
$listOptions[$itemOption->label] = $itemOption->value;
}
foreach (explode('|', $options) as $item) {
if (trim($item) && !array_key_exists(trim($item), $listOptions)) {
$data = '{
"option": {
"label": "' . $item . '",
"value": "' . $item . '",
"sort_order": "' . $countItem . '"
}
}';
$api->call('products/attributes/'.$attribute_code."/options", json_decode($data), 'POST');
} elseif (trim($item)) {
$data = '{
"option": {
"label": "' . $item . '",
"value": "' . $item . '",
"sort_order": "' . $countItem . '"
}
}';
$api->call('products/attributes/'.$attribute_code."/options/".$listOptions[trim($item)], json_decode($data), 'PUT');
}
$countItem++;
}
}
if (strpos(json_encode($response), "attribute_code") > 0) {
$criteria = [
'attributeSetId' => $attributeSetId,
'attributeGroupId' => $attributeGroupId,
'attributeCode' => $attribute_code,
'sortOrder' => $position
];
$api->call('products/attribute-sets/attributes', $criteria, 'POST');
} else {
echo " >>>>>>>> ".var_dump($response);
}
}
}
$row++;
// if ($row>2) {
// exit();
// }
}
fclose($handle);
}
}