Advertisement
Guest User

Untitled

a guest
Jun 8th, 2016
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.17 KB | None | 0 0
  1. <?php
  2. namespace Sanimarkt\Import\Service;
  3.  
  4. use Magento\Catalog\Api\Data\ProductExtensionFactory;
  5. use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
  6. use Magento\Catalog\Api\ProductRepositoryInterface;
  7. use Magento\Catalog\Model\ProductFactory;
  8. use Magento\CatalogInventory\Api\Data\StockItemInterface;
  9. use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory;
  10. use Magento\ConfigurableProduct\Api\Data\OptionInterface;
  11. use Magento\Framework\App\ObjectManager;
  12. use Magento\Framework\App\Filesystem\DirectoryList;
  13. use Sanimarkt\Import\Helper\Attribute;
  14. use Sanimarkt\Import\Logger\Logger;
  15. use Sanimarkt\Import\Service\CategoryImporter;
  16.  
  17. class ProductImporter extends AbstractImporter
  18. {
  19.     /**
  20.      * @var Attribute
  21.      */
  22.     private $attributeHelper;
  23.  
  24.     /**
  25.      * @var ProductRepositoryInterface
  26.      */
  27.     private $productRepository;
  28.  
  29.     /**
  30.      * @var StockItemInterface
  31.      */
  32.     private $stockFactory;
  33.  
  34.     /**
  35.      * @var ProductAttributeRepositoryInterface
  36.      */
  37.     private $productAttributeRepository;
  38.  
  39.     /**
  40.      * @var OptionInterface
  41.      */
  42.     private $option;
  43.  
  44.     /**
  45.      * @var ProductFactory
  46.      */
  47.     private $productFactory;
  48.  
  49.     /**
  50.      * @var ProductExtensionFactory
  51.      */
  52.     private $productExtensionFactory;
  53.  
  54.     /**
  55.      * @var Logger
  56.      */
  57.     private $logger;
  58.  
  59.     /**
  60.      * @var \Magento\Framework\App\Filesystem\DirectoryList
  61.      */
  62.     protected $directoryList;
  63.     /**
  64.      * @var \Sanimarkt\Import\Service\CategoryImporter
  65.      */
  66.     protected $categoryImporter;
  67.  
  68.     protected $filePath = "import/articles.csv";
  69.     protected $resultSet = [];
  70.     protected $categories = [];
  71.  
  72.     /**
  73.      * ProductImporter constructor.
  74.      * @param Attribute $attributeHelper
  75.      * @param ProductRepositoryInterface $productRepository
  76.      * @param ProductFactory $productFactory
  77.      * @param StockItemInterfaceFactory $stockFactory
  78.      * @param ProductAttributeRepositoryInterface $productAttributeRepository
  79.      * @param OptionInterface $option
  80.      * @param ProductExtensionFactory $productExtensionFactory
  81.      * @param CategoryImporter $categoryImporter
  82.      * @internal param ObjectManager $objectManager
  83.      */
  84.     public function __construct(Attribute $attributeHelper,
  85.                                 ProductRepositoryInterface $productRepository,
  86.                                 ProductFactory $productFactory,
  87.                                 StockItemInterfaceFactory $stockFactory,
  88.                                 ProductAttributeRepositoryInterface $productAttributeRepository,
  89.                                 OptionInterface $option,
  90.                                 ProductExtensionFactory $productExtensionFactory,
  91.                                 Logger $logger,
  92.                                 DirectoryList $directoryList,
  93.                                 CategoryImporter $categoryImporter
  94. )
  95.     {
  96.         $this->attributeHelper = $attributeHelper;
  97.         $this->productRepository = $productRepository;
  98.         $this->productFactory = $productFactory;
  99.         $this->stockFactory = $stockFactory;
  100.         $this->productAttributeRepository = $productAttributeRepository;
  101.         $this->option = $option;
  102.         $this->productExtensionFactory = $productExtensionFactory;
  103.         $this->logger = $logger;
  104.         $this->directoryList = $directoryList;
  105.         $this->categoryImporter = $categoryImporter;
  106.         $this->objectManager = ObjectManager::getInstance();
  107.         $this->storeManager = $this->objectManager->get('\Magento\Store\Model\StoreManagerInterface');
  108.         $this->file = $this->objectManager->get('\Magento\Framework\Filesystem\Io\File');
  109.  
  110.         $this->createImagesDir();
  111.  
  112.         parent::__construct();
  113.     }
  114.  
  115.     /**
  116.      * @return void
  117.      */
  118.     public function startImport()
  119.     {
  120.         $this->logger->info('Start new atricle importer');
  121.         $this->readImportFile();
  122.         $this->import();
  123.         $this->logger->info('Finished article importer');
  124.     }
  125.  
  126.     /**
  127.      * Import simple products
  128.      *
  129.      * @return array
  130.      * @throws \Magento\Framework\Exception\LocalizedException
  131.      */
  132.     public function import()
  133.     {
  134.         //Execution time may be very long
  135.         set_time_limit(0);
  136.  
  137.         $productIds = [];
  138.         $i = 0;
  139.  
  140.         foreach($this->resultSet as $resultData) {
  141.             $product = $this->productFactory->create();
  142.  
  143.             $categoryId = $this->getCategoryId($resultData['category_id']);
  144.             $manufacturer = ucfirst(trim(strtolower($resultData['producer_name'])));
  145.             $product->setSku($resultData['producercode']);
  146.             $product->setName($resultData['name_nl']);
  147.             $product->setPrice($resultData['net_sales_price']);
  148.             $product->setTypeId('simple');
  149.             $product->setAttributeSetId(9); // sanimarkt attribute set ID
  150.             $product->setVisibility(4);
  151.  
  152.             if (! empty($resultData['net_weight_in_kg'])) {
  153.                 $product->setWeight($resultData['net_weight_in_kg']);
  154.             }
  155.  
  156.             // manufacturer
  157.             if ( ! empty($manufacturer)) {
  158.                 $product->setCustomAttribute('manufacturer', $this->attributeHelper->createOrGetId('manufacturer', $manufacturer));
  159.             }
  160.  
  161.             // category IDS
  162.             if ( ! empty($categoryId)) {
  163.                 $product->setCustomAttribute('category_ids', [$categoryId]);
  164.             }
  165.  
  166.             $product = $this->productRepository->save($product);
  167.  
  168.             // Images
  169.             $this->saveImagesToProduct($product, $resultData['image_urls']);
  170.  
  171.             // save stock
  172.             $productId = $product->getId();
  173.             $stockItem = $this->stockFactory->create();
  174.             $stockItemResource = $this->objectManager->get('Magento\CatalogInventory\Model\ResourceModel\Stock\Item');
  175.             $stockItemResource->loadByProductId($stockItem, $productId,$this->storeManager->getWebsite()->getId());
  176.             $stockItem->setQty(100.00);
  177.             $stockItem->setIsInStock(1);
  178.             $stockItem->save();
  179.             $productIds[] = $productId;
  180.  
  181.             $this->logger->info('create simple product - '.$resultData['name_nl']);
  182.         }
  183.  
  184.         return $productIds;
  185.     }
  186.  
  187.     /**
  188.      * Find name of category by category_id of initial data
  189.      *
  190.      * @param  int $dataCategoryId
  191.      * @return int
  192.      */
  193.     private function getCategoryId($dataCategoryId)
  194.     {
  195.         // first find id in array cache
  196.         if (isset($this->categories[$dataCategoryId])) {
  197.             return $this->categories[$dataCategoryId];
  198.         }
  199.  
  200.         $categories = $this->categoryImporter->getResultSet();
  201.         $categoryId = 0;
  202.  
  203.         if ( ! empty($categories) && isset($categories[$dataCategoryId])) {
  204.             $category = $categories[$dataCategoryId]['name_nl'];
  205.             $categoryId = $this->categoryImporter->getCategoryId($category);
  206.  
  207.             // set id in array cache
  208.             $this->categories[$dataCategoryId] = $categoryId;
  209.         }
  210.  
  211.         return $categoryId;
  212.     }
  213.  
  214.     /**
  215.      * Download images to local storage
  216.      * and return path
  217.      *
  218.      * @param  string $imageUrls
  219.      * @return array
  220.      */
  221.     private function getImages($imageUrls)
  222.     {
  223.         $images = [];
  224.         $imageUrls = explode('|', $imageUrls);
  225.  
  226.         foreach($imageUrls as $index => $imageUrl){
  227.             $path = $this->downloadImage($imageUrl);
  228.  
  229.             if ($index == 0) {
  230.                 $images[] = ['path' => $path, 'definitions' => ['image', 'small_image', 'thumbnail']];
  231.             } else {
  232.                 $images[] = ['path' => $path, 'definitions' => []];
  233.             }
  234.         }
  235.  
  236.         return $images;
  237.     }
  238.  
  239.     /**
  240.      * Save image to import/images map
  241.      *
  242.      * @param  string $url
  243.      * @return strin
  244.      */
  245.     private function downloadImage($url)
  246.     {
  247.         $key = substr($url, strpos($url, 'key=') + 4);
  248.         $path = $this->directoryList->getPath('media').'/import/images/'.$key.'.jpg';
  249.  
  250.         if ( file_exists($path)) {
  251.             return $path;
  252.         }
  253.  
  254.         $ch = curl_init($url);
  255.         $fp = fopen($path, 'wb');
  256.         curl_setopt($ch, CURLOPT_FILE, $fp);
  257.         curl_setopt($ch, CURLOPT_HEADER, 0);
  258.         curl_exec($ch);
  259.         curl_close($ch);
  260.         fclose($fp);
  261.  
  262.         return $path;
  263.     }
  264.  
  265.     /**
  266.      * save images to product
  267.      *
  268.      * @param  Magento\Catalog\Model\Product $product
  269.      * @param  string $data
  270.      * @return void
  271.      */
  272.     private function saveImagesToProduct($product, $imageUrls)
  273.     {
  274.         $images = $this->getImages($imageUrls);
  275.  
  276.         if ( ! empty($product) && ! empty($images)) {
  277.             foreach($images as $image) {
  278.                 $product->addImageToMediaGallery($image['path'], $image['definitions'], false);
  279.             }
  280.         }
  281.  
  282.         $product->save();
  283.     }
  284.  
  285.     /**
  286.      * Create image dir
  287.      * @return void
  288.      */
  289.     private function createImagesDir()
  290.     {
  291.         if ( ! file_exists($this->directoryList->getPath('media').'/import/images')) {
  292.             $this->file->mkdir($this->directoryList->getPath('media').'/import/images', 0775);
  293.         }
  294.     }
  295. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement