Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Sanimarkt\Import\Service;
- use Magento\Catalog\Api\Data\ProductExtensionFactory;
- use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
- use Magento\Catalog\Api\ProductRepositoryInterface;
- use Magento\Catalog\Model\ProductFactory;
- use Magento\CatalogInventory\Api\Data\StockItemInterface;
- use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory;
- use Magento\ConfigurableProduct\Api\Data\OptionInterface;
- use Magento\Framework\App\ObjectManager;
- use Magento\Framework\App\Filesystem\DirectoryList;
- use Sanimarkt\Import\Helper\Attribute;
- use Sanimarkt\Import\Logger\Logger;
- use Sanimarkt\Import\Service\CategoryImporter;
- class ProductImporter extends AbstractImporter
- {
- /**
- * @var Attribute
- */
- private $attributeHelper;
- /**
- * @var ProductRepositoryInterface
- */
- private $productRepository;
- /**
- * @var StockItemInterface
- */
- private $stockFactory;
- /**
- * @var ProductAttributeRepositoryInterface
- */
- private $productAttributeRepository;
- /**
- * @var OptionInterface
- */
- private $option;
- /**
- * @var ProductFactory
- */
- private $productFactory;
- /**
- * @var ProductExtensionFactory
- */
- private $productExtensionFactory;
- /**
- * @var Logger
- */
- private $logger;
- /**
- * @var \Magento\Framework\App\Filesystem\DirectoryList
- */
- protected $directoryList;
- /**
- * @var \Sanimarkt\Import\Service\CategoryImporter
- */
- protected $categoryImporter;
- protected $filePath = "import/articles.csv";
- protected $resultSet = [];
- protected $categories = [];
- /**
- * ProductImporter constructor.
- * @param Attribute $attributeHelper
- * @param ProductRepositoryInterface $productRepository
- * @param ProductFactory $productFactory
- * @param StockItemInterfaceFactory $stockFactory
- * @param ProductAttributeRepositoryInterface $productAttributeRepository
- * @param OptionInterface $option
- * @param ProductExtensionFactory $productExtensionFactory
- * @param CategoryImporter $categoryImporter
- * @internal param ObjectManager $objectManager
- */
- public function __construct(Attribute $attributeHelper,
- ProductRepositoryInterface $productRepository,
- ProductFactory $productFactory,
- StockItemInterfaceFactory $stockFactory,
- ProductAttributeRepositoryInterface $productAttributeRepository,
- OptionInterface $option,
- ProductExtensionFactory $productExtensionFactory,
- Logger $logger,
- DirectoryList $directoryList,
- CategoryImporter $categoryImporter
- )
- {
- $this->attributeHelper = $attributeHelper;
- $this->productRepository = $productRepository;
- $this->productFactory = $productFactory;
- $this->stockFactory = $stockFactory;
- $this->productAttributeRepository = $productAttributeRepository;
- $this->option = $option;
- $this->productExtensionFactory = $productExtensionFactory;
- $this->logger = $logger;
- $this->directoryList = $directoryList;
- $this->categoryImporter = $categoryImporter;
- $this->objectManager = ObjectManager::getInstance();
- $this->storeManager = $this->objectManager->get('\Magento\Store\Model\StoreManagerInterface');
- $this->file = $this->objectManager->get('\Magento\Framework\Filesystem\Io\File');
- $this->createImagesDir();
- parent::__construct();
- }
- /**
- * @return void
- */
- public function startImport()
- {
- $this->logger->info('Start new atricle importer');
- $this->readImportFile();
- $this->import();
- $this->logger->info('Finished article importer');
- }
- /**
- * Import simple products
- *
- * @return array
- * @throws \Magento\Framework\Exception\LocalizedException
- */
- public function import()
- {
- //Execution time may be very long
- set_time_limit(0);
- $productIds = [];
- $i = 0;
- foreach($this->resultSet as $resultData) {
- $product = $this->productFactory->create();
- $categoryId = $this->getCategoryId($resultData['category_id']);
- $manufacturer = ucfirst(trim(strtolower($resultData['producer_name'])));
- $product->setSku($resultData['producercode']);
- $product->setName($resultData['name_nl']);
- $product->setPrice($resultData['net_sales_price']);
- $product->setTypeId('simple');
- $product->setAttributeSetId(9); // sanimarkt attribute set ID
- $product->setVisibility(4);
- if (! empty($resultData['net_weight_in_kg'])) {
- $product->setWeight($resultData['net_weight_in_kg']);
- }
- // manufacturer
- if ( ! empty($manufacturer)) {
- $product->setCustomAttribute('manufacturer', $this->attributeHelper->createOrGetId('manufacturer', $manufacturer));
- }
- // category IDS
- if ( ! empty($categoryId)) {
- $product->setCustomAttribute('category_ids', [$categoryId]);
- }
- $product = $this->productRepository->save($product);
- // Images
- $this->saveImagesToProduct($product, $resultData['image_urls']);
- // save stock
- $productId = $product->getId();
- $stockItem = $this->stockFactory->create();
- $stockItemResource = $this->objectManager->get('Magento\CatalogInventory\Model\ResourceModel\Stock\Item');
- $stockItemResource->loadByProductId($stockItem, $productId,$this->storeManager->getWebsite()->getId());
- $stockItem->setQty(100.00);
- $stockItem->setIsInStock(1);
- $stockItem->save();
- $productIds[] = $productId;
- $this->logger->info('create simple product - '.$resultData['name_nl']);
- }
- return $productIds;
- }
- /**
- * Find name of category by category_id of initial data
- *
- * @param int $dataCategoryId
- * @return int
- */
- private function getCategoryId($dataCategoryId)
- {
- // first find id in array cache
- if (isset($this->categories[$dataCategoryId])) {
- return $this->categories[$dataCategoryId];
- }
- $categories = $this->categoryImporter->getResultSet();
- $categoryId = 0;
- if ( ! empty($categories) && isset($categories[$dataCategoryId])) {
- $category = $categories[$dataCategoryId]['name_nl'];
- $categoryId = $this->categoryImporter->getCategoryId($category);
- // set id in array cache
- $this->categories[$dataCategoryId] = $categoryId;
- }
- return $categoryId;
- }
- /**
- * Download images to local storage
- * and return path
- *
- * @param string $imageUrls
- * @return array
- */
- private function getImages($imageUrls)
- {
- $images = [];
- $imageUrls = explode('|', $imageUrls);
- foreach($imageUrls as $index => $imageUrl){
- $path = $this->downloadImage($imageUrl);
- if ($index == 0) {
- $images[] = ['path' => $path, 'definitions' => ['image', 'small_image', 'thumbnail']];
- } else {
- $images[] = ['path' => $path, 'definitions' => []];
- }
- }
- return $images;
- }
- /**
- * Save image to import/images map
- *
- * @param string $url
- * @return strin
- */
- private function downloadImage($url)
- {
- $key = substr($url, strpos($url, 'key=') + 4);
- $path = $this->directoryList->getPath('media').'/import/images/'.$key.'.jpg';
- if ( file_exists($path)) {
- return $path;
- }
- $ch = curl_init($url);
- $fp = fopen($path, 'wb');
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_exec($ch);
- curl_close($ch);
- fclose($fp);
- return $path;
- }
- /**
- * save images to product
- *
- * @param Magento\Catalog\Model\Product $product
- * @param string $data
- * @return void
- */
- private function saveImagesToProduct($product, $imageUrls)
- {
- $images = $this->getImages($imageUrls);
- if ( ! empty($product) && ! empty($images)) {
- foreach($images as $image) {
- $product->addImageToMediaGallery($image['path'], $image['definitions'], false);
- }
- }
- $product->save();
- }
- /**
- * Create image dir
- * @return void
- */
- private function createImagesDir()
- {
- if ( ! file_exists($this->directoryList->getPath('media').'/import/images')) {
- $this->file->mkdir($this->directoryList->getPath('media').'/import/images', 0775);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement