[php] PHP import magento2

Viewer

copydownloadembedprintName: PHP import magento2
  1. <?php
  2. use Magento\Framework\App\Bootstrap;
  3.  
  4. error_reporting(E_ALL);
  5. ini_set("display_errors", 1);
  6.  
  7. require __DIR__ . '/../app/bootstrap.php';
  8. if (! isset($_POST))
  9.     exit();
  10.  
  11. $params = $_SERVER;
  12. $bootstrap = Bootstrap::create(BP, $params);
  13. $objectManager = $bootstrap->getObjectManager();
  14. $state = $objectManager->get('Magento\Framework\App\State');
  15. $state->setAreaCode('frontend');
  16.  
  17. $context = $objectManager->get('\Magento\Framework\App\Helper\Context');
  18. $attributeRepository = $objectManager->get('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
  19. $tableFactory = $objectManager->get('\Magento\Eav\Model\Entity\Attribute\Source\TableFactory');
  20. $attributeOptionManagement = $objectManager->get('\Magento\Eav\Api\AttributeOptionManagementInterface');
  21. $optionLabelFactory = $objectManager->get('\Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory');
  22. $optionFactory = $objectManager->get('\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory');
  23. $registry = $objectManager->get('\Magento\Framework\Registry');
  24. $registry->register('isSecureArea', true);
  25.  
  26. $productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
  27. $associatedIdMap = new stdClass();
  28. $nameSkuMap = new stdClass();
  29. $attributGustoMap = new stdClass();
  30. $attributeValues;
  31.  
  32.  
  33. function getAttribute($attributeCode)
  34.  
  35. {
  36.     global $attributeRepository;
  37.     return $attributeRepository->get($attributeCode);
  38. }
  39.  
  40. function createOrGetId($attributeCode, $label)
  41. {
  42.     if (strlen($label) < 1) {
  43.         throw new \Magento\Framework\Exception\LocalizedException(__('Label for %1 must not be empty.', $attributeCode));
  44.     }
  45.     global $attributGustoMap;
  46.     global $optionLabelFactory;
  47.     global $optionFactory;
  48.     global $attributeOptionManagement;
  49.     // Does it already exist?
  50.     $optionId = getOptionId($attributeCode, $label);
  51.  
  52.     if (! $optionId) {
  53.         // If no, add it.
  54.         $optionLabel = $optionLabelFactory->create();
  55.         $optionLabel->setStoreId(0);
  56.         $optionLabel->setLabel($label);
  57.  
  58.         $option = $optionFactory->create();
  59.         $option->setLabel($label);
  60.         $option->setStoreLabels([
  61.             $optionLabel
  62.         ]);
  63.         $option->setSortOrder(0);
  64.         $option->setIsDefault(false);
  65.  
  66.         $attrId = getAttribute($attributeCode)->getAttributeId();
  67.  
  68.         $attributeOptionManagement->add(\Magento\Catalog\Model\Product::ENTITY, '157', $option);
  69.  
  70.         // Get the inserted ID. Should be returned from the installer, but it isn't.
  71.         $optionId = getOptionId($attributeCode, $label, true);
  72.         $attributGustoMap->$label = $optionId;
  73.     }
  74.  
  75.     return $optionId;
  76. }
  77.  
  78. function getOptionId($attributeCode, $label, $force = false)
  79. {
  80.     global $attributGustoMap, $attributeValues;
  81.  
  82.     if (property_exists($attributGustoMap, $label)) {
  83.         return $attributGustoMap->$label;
  84.     }
  85.     $attribute = getAttribute($attributeCode);
  86.  
  87.     global $tableFactory;
  88.  
  89.     // Build option array if necessary
  90.     if ($force === true || ! isset($attributeValues[$attribute->getAttributeId()])) {
  91.  
  92.         $attributeValues[$attribute->getAttributeId()] = [];
  93.  
  94.         // We have to generate a new sourceModel instance each time through to prevent it from
  95.         // referencing its _options cache. No other way to get it to pick up newly-added values.
  96.  
  97.         $sourceModel = $tableFactory->create();
  98.         $sourceModel->setAttribute($attribute);
  99.  
  100.         foreach ($sourceModel->getAllOptions() as $option) {
  101.             $attributeValues[$attribute->getAttributeId()][$option['label']] = $option['value'];
  102.         }
  103.     }
  104.  
  105.     // Return option ID if exists
  106.     if (isset($attributeValues[$attribute->getAttributeId()][$label])) {
  107.         return $attributeValues[$attribute->getAttributeId()][$label];
  108.     }
  109.  
  110.     // Return false if does not exist
  111.     return false;
  112. }
  113.  
  114. $name = $_FILES['file']['name'];
  115. $temp_name = $_FILES['file']['tmp_name'];
  116. if (isset($name) and ! empty($name)) {
  117.     $location = './';
  118.     if (move_uploaded_file($temp_name, $location . $name)) {
  119.         $xml = simplexml_load_file($name, null, LIBXML_PARSEHUGE | LIBXML_NOWARNING);
  120.  
  121.         $deletedProductList = $xml->DeletedProducts->Product;
  122.         $updateProductsList = $xml->UpdatedProducts->Product;
  123.         $product;
  124.  
  125.         if (is_object($updateProductsList)) {
  126.             for ($i = 0; $i < count($updateProductsList); $i ++) {
  127.                 $desc = $updateProductsList[$i]->Description;
  128.                 $code = (string) $updateProductsList[$i]->Code;
  129.                 $price = (float) $updateProductsList[$i]->GrossPrice1;
  130.                 $brand = (string) $updateProductsList[$i]->ProducerName;
  131.                 $qty = (int) $updateProductsList[$i]->AvailableQty;
  132.                 try {
  133.                     $product = $productRepository->get($code);
  134.                 } catch (Exception $e) {
  135.                     $product = $objectManager->create('Magento\Catalog\Model\Product');
  136.                 }
  137.                 $product->setSku($code);
  138.                 $product->setPrice($price);
  139.                 $product->setStockData(array(
  140.                     'use_config_manage_stock' => 0, // 'Use config settings' checkbox
  141.                     'manage_stock' => 1, // manage stock
  142.                     'is_in_stock' => 1, // Stock Availability
  143.                     'qty' => $qty // qty
  144.                 ));
  145.                 $notes = (string) $updateProductsList[$i]->Notes;
  146.                 $scadenza = false;
  147.                 if (str_contains($notes, "--scadenza:")) {
  148.  
  149.                     $scadenza = explode("--scadenza:", $notes)[1];
  150.                     $scadenza = trim($scadenza);
  151.                     $scadenzaArray = explode("/", $scadenza);
  152.                     if (count($scadenzaArray) == 3) {
  153.  
  154.                         $scadenza = $scadenzaArray[1] . '/' . $scadenzaArray[0] . '/' . $scadenzaArray[2];
  155.                         $product->setCustomAttribute('scadenza', $scadenza);
  156.                     }
  157.                 }
  158.                 
  159.                 //BRANDO MIO
  160.                 $existsbrand = GetBrandIdFromName($brand);
  161.                 if(!$existsbrand) {
  162.                     $brid = createBrand($brand);
  163.                 } else {
  164.                     $brid = $existsbrand;
  165.                 }
  166.                 
  167.                 if($hasbrand = HasBrand($product->getId())) {
  168.                     $newbr = UpdateProdBrand($product->getId(), $brid);
  169.                 }
  170.                 else {
  171.                     $newbr = NewProdBrand($product->getId(), $brid);
  172.                 }
  173.                 /////////
  174.  
  175.                 if (! str_contains($desc, '--')) {
  176.                     // simple
  177.                     $product->setName($desc);
  178.                     upsertProduct($product, 'simple');
  179.                 } else {
  180.                     $prodName = explode('--', $desc)[0];
  181.                     if (str_contains($desc, 'BASE')) {
  182.                         // configurable
  183.                         $product->setName($prodName);
  184.                         $product = upsertProduct($product, 'configurable');
  185.                         $nameSkuMap->$prodName = $code;
  186.                     } else if (str_contains($desc, 'gusto:')) {
  187.                         // associated
  188.                         $product->setName($prodName);
  189.                         $gustoAttrCode = $product->getResource()
  190.                                          ->getAttribute("gusto")
  191.                                          ->getAttributeCode();
  192.                         $gustoId = createOrGetId($gustoAttrCode, trim(strtolower(explode('--gusto:', $desc)[1])));
  193.                         $product->setGusto($gustoId);
  194.  
  195.                         $product = upsertProduct($product, 'simple', 1); 
  196.                         $productId = $product->getId();
  197.                         if (property_exists($associatedIdMap, $prodName)) {
  198.                             $associatedIdArray = $associatedIdMap->$prodName;
  199.                             array_push($associatedIdArray, $productId);
  200.                         } else {
  201.                             $associatedIdArray = array(
  202.                                 $productId
  203.                             );
  204.                         }
  205.                         $associatedIdMap->$prodName = $associatedIdArray;
  206.                     } else {
  207.                         echo "unknown product type - " . $code . "\n";
  208.                         // unknown
  209.                     }
  210.                 }
  211.                 
  212.  
  213.             }
  214.         }
  215.         foreach ($associatedIdMap as $productName => $prodAssocIds) {
  216.             if (property_exists($nameSkuMap, $productName)) {
  217.                 updateAssociatedIds($nameSkuMap->$productName, $prodAssocIds);
  218.             } else {
  219.                 echo "no base product - " . $productName . "\n";
  220.             }
  221.         }
  222.         if (is_object($deletedProductList)) {
  223.             for ($i = 0; $i < count($deletedProductList); $i ++) {
  224.                 $code = $deletedProductList[$i]->Code;
  225.                 try {
  226.                     $product = $productRepository->get($code);
  227.                     $productRepository->delete($product);
  228.                 } catch (Exception $e) {
  229.                     echo "Cannot Delete - sku not exists - " . $code . "\n";
  230.                 }
  231.             }
  232.         }
  233.         echo "OK";
  234.     } else {
  235.         echo 'not uploaded';
  236.     }
  237. } else {
  238.     echo 'You should select a file to upload !!';
  239. }
  240.  
  241. ////////////////////////////
  242. function updateAssociatedIds($code, $productIds)
  243. {
  244.     global $productRepository;
  245.     $product = $productRepository->get($code);
  246.     $product_resource = $product->getResource();
  247.     $gusto_attribute = $product_resource->getAttribute('gusto');
  248.     $gusto_attribute_id = $gusto_attribute->getId();
  249.     $configurable_attributes = array(
  250.         'gusto'
  251.     );
  252.     $product->getTypeInstance()->setUsedProductAttributeIds(array(
  253.         $gusto_attribute_id
  254.     ), $product);
  255.  
  256.     $configurable_attributes_data = $product->getTypeInstance()->getConfigurableAttributesAsArray($product);
  257.     $product->setCanSaveConfigurableAttributes(true);
  258.     $product->setConfigurableAttributesData($configurable_attributes_data);
  259.  
  260.     $product->setAssociatedProductIds($productIds);
  261.  
  262.     $product->save();
  263. }
  264.  
  265. ////////////////////////////
  266. function upsertProduct($product, $type, $visibility = 4)
  267. {
  268.     $product->setTypeId($type)
  269.         ->setStatus(1)
  270.         ->
  271.     // 1 = enabled, 2 = disabled
  272.     setAttributeSetId(4)
  273.         ->
  274.     // 4 = default
  275.     setTaxClassId(2)
  276.         ->
  277.     // 0 = None, 2 = Default product tax class
  278.     setCategoryIds(array(
  279.         2
  280.     ))
  281.         ->
  282.     // 2 = Default category
  283.     setWebsiteIds(array(
  284.         1
  285.     ))
  286.         ->
  287.     // 1 = Default Website ID
  288.     setStoreId(0)
  289.         ->setUrlKey($product->getSku())
  290.         ->
  291.     // 0 = Default store ID
  292.     setVisibility($visibility); // 4 = Catalog & Search
  293.  
  294.     $product->save();
  295.  
  296.     return $product;
  297. }
  298.  
  299. //////////////////
  300. function GetBrandIdFromName($brname) {
  301.  
  302.     $conn = new mysqli($servername, $username, $password);
  303.     if ($conn->connect_error) {
  304.         die("Connection failed: " . $conn->connect_error);
  305.     }
  306.     
  307.     $stmt = $conn->prepare("SELECT brand_id FROM magento.tm_brand WHERE name = ?");
  308.     $param = "$brname";
  309.     $stmt->bind_param("s", $param);
  310.     $stmt->execute();
  311.     $stmt->store_result();
  312.     $stmt->bind_result($brid);
  313.     $rez = null;
  314.     while($stmt->fetch()){
  315.         $rez = $brid;
  316.     }
  317.     $stmt->close();
  318.     $conn->close();
  319.     
  320.     return $rez;
  321. }
  322.  
  323. //////////////////
  324. function createBrand($brname) {
  325.     $urlkey = str_replace(" ", "-", $brname);
  326.     $urlkey = str_replace("\"", "", $urlkey);
  327.     $urlkey = str_replace("'", "", $urlkey);
  328.     $urlkey = strtolower($urlkey);
  329.  
  330.     $conn = new mysqli($servername, $username, $password);
  331.     if ($conn->connect_error) {
  332.         die("Connection failed: " . $conn->connect_error);
  333.     }
  334.     
  335.     $stmt = $conn->prepare("INSERT INTO magento.tm_brand (name, status, url_key, title, website_id) VALUES (?, 1, ?, ?, 1)");
  336.     $stmt->bind_param("sss", $brname, $urlkey, $brname);
  337.     $stmt->execute();
  338.     $rinsid = $stmt->insert_id;
  339.     $stmt->close();
  340.     $conn->close();
  341.     
  342.     return $rinsid;
  343. }
  344.  
  345.  
  346. //////////////////
  347. function HasBrand($prid) {
  348.     $conn = new mysqli($servername, $username, $password);
  349.     if ($conn->connect_error) {
  350.         die("Connection failed: " . $conn->connect_error);
  351.     }
  352.     
  353.     $stmt = $conn->prepare("SELECT value FROM magento.catalog_product_entity_int  where attribute_id = 150 AND entity_id = ?");
  354.     $stmt->bind_param("i", $prid);
  355.     $stmt->execute();
  356.     $stmt->store_result();
  357.     $stmt->bind_result($bid);
  358.     $rez = null;
  359.     while($stmt->fetch()){
  360.         $rez = $bid;
  361.     }
  362.     $stmt->close();
  363.     $conn->close();
  364.     
  365.     return $rez;
  366. }
  367.  
  368. //////////////////////////
  369. function UpdateProdBrand($prid, $brid) {
  370.     $conn = new mysqli($servername, $username, $password);
  371.     if ($conn->connect_error) {
  372.         die("Connection failed: " . $conn->connect_error);
  373.     }
  374.     
  375.     $stmt = $conn->prepare("UPDATE magento.catalog_product_entity_int SET value = ? WHERE entity_id = ?; ");
  376.     $stmt->bind_param("ii", $brid, $prid);
  377.     $stmt->execute();
  378.     $rr = $stmt->affected_rows;
  379.     $stmt->close();
  380.     $conn->close();
  381.     
  382.     return $rr;
  383. }
  384.  
  385. ////////////////////////////
  386. function NewProdBrand($prid, $brid) {
  387.     $conn = new mysqli($servername, $username, $password);
  388.     if ($conn->connect_error) {
  389.         die("Connection failed: " . $conn->connect_error);
  390.     }
  391.     
  392.     $stmt = $conn->prepare("INSERT INTO magento.catalog_product_entity_int (attribute_id, store_id, entity_id, value) VALUES (150, 0, ?, ?); ");
  393.     $stmt->bind_param("ii", $prid, $brid);
  394.     $stmt->execute();
  395.     $rr = $stmt->affected_rows;
  396.     $stmt->close();
  397.     $conn->close();
  398.     
  399.     return $rr;
  400. }

Editor

You can edit this paste and save as new:


File Description
  • PHP import magento2
  • Paste Code
  • 19 Jul-2021
  • 13.8 Kb
You can Share it: