Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Copyright © Magento, Inc. All rights reserved.
- * See COPYING.txt for license details.
- */
- namespace Froogal\Catalog\Model\Import;
- use Magento\Catalog\Api\ProductRepositoryInterface;
- use Magento\Catalog\Model\Config as CatalogConfig;
- use Magento\Catalog\Model\Product\Visibility;
- use Magento\CatalogImportExport\Model\Import\Product\ImageTypeProcessor;
- use Magento\CatalogImportExport\Model\Import\Product\LinkProcessor;
- use Magento\CatalogImportExport\Model\Import\Product\MediaGalleryProcessor;
- use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface as ValidatorInterface;
- use Magento\CatalogImportExport\Model\Import\Product\StatusProcessor;
- use Magento\CatalogImportExport\Model\Import\Product\StockProcessor;
- use Magento\CatalogImportExport\Model\StockItemImporterInterface;
- use Magento\CatalogInventory\Api\Data\StockItemInterface;
- use Magento\Framework\App\Filesystem\DirectoryList;
- use Magento\Framework\App\ObjectManager;
- use Magento\Framework\Exception\LocalizedException;
- use Magento\Framework\Exception\NoSuchEntityException;
- use Magento\Framework\Filesystem;
- use Magento\Framework\Filesystem\Driver\File;
- use Magento\Framework\Filesystem\DriverPool;
- use Magento\Framework\Intl\DateTimeFactory;
- use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor;
- use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface;
- use Magento\Framework\Stdlib\DateTime;
- use Magento\ImportExport\Model\Import;
- use Magento\ImportExport\Model\Import\Entity\AbstractEntity;
- use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError;
- use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
- use Magento\Store\Model\Store;
- use Magento\CatalogImportExport\Model\Import\Product as ProductImport;
- /**
- * Import entity product model
- *
- * @api
- *
- * @SuppressWarnings(PHPMD.TooManyFields)
- * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
- * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
- * @SuppressWarnings(PHPMD.ExcessivePublicCount)
- * @since 100.0.2
- */
- class Product extends ProductImport
- {
- private const DEFAULT_GLOBAL_MULTIPLE_VALUE_SEPARATOR = ',';
- public const CONFIG_KEY_PRODUCT_TYPES = 'global/importexport/import_product_types';
- private const HASH_ALGORITHM = 'sha256';
- /**
- * Size of bunch - part of products to save in one step.
- */
- public const BUNCH_SIZE = 20;
- /**
- * Size of bunch to delete attributes of products in one step.
- */
- public const ATTRIBUTE_DELETE_BUNCH = 1000;
- /**
- * Pseudo multi line separator in one cell.
- *
- * Can be used as custom option value delimiter or in configurable fields cells.
- */
- public const PSEUDO_MULTI_LINE_SEPARATOR = '|';
- /**
- * Symbol between Name and Value between Pairs.
- */
- public const PAIR_NAME_VALUE_SEPARATOR = '=';
- /**
- * Value that means all entities (e.g. websites, groups etc.)
- */
- public const VALUE_ALL = 'all';
- /**
- * Data row scopes.
- */
- public const SCOPE_DEFAULT = 1;
- public const SCOPE_WEBSITE = 2;
- public const SCOPE_STORE = 0;
- public const SCOPE_NULL = -1;
- /**
- * Permanent column names.
- *
- * Names that begins with underscore is not an attribute. This name convention is for
- * to avoid interference with same attribute name.
- */
- /**
- * Column product store.
- */
- public const COL_STORE = '_store';
- /**
- * Column product store view code.
- */
- public const COL_STORE_VIEW_CODE = 'store_view_code';
- /**
- * Column website.
- */
- public const COL_WEBSITE = 'website_code';
- /**
- * Column product attribute set.
- */
- public const COL_ATTR_SET = '_attribute_set';
- /**
- * Column product type.
- */
- public const COL_TYPE = 'product_type';
- /**
- * Column product category.
- */
- public const COL_CATEGORY = 'categories';
- /**
- * Column product visibility.
- */
- public const COL_VISIBILITY = 'visibility';
- /**
- * Column product sku.
- */
- public const COL_SKU = 'sku';
- /**
- * Column product name.
- */
- public const COL_NAME = 'name';
- /**
- * Column product website.
- */
- public const COL_PRODUCT_WEBSITES = '_product_websites';
- /**
- * Attribute code for media gallery.
- */
- public const MEDIA_GALLERY_ATTRIBUTE_CODE = 'media_gallery';
- /**
- * Column media image.
- */
- public const COL_MEDIA_IMAGE = '_media_image';
- /**
- * Inventory use config label.
- */
- public const INVENTORY_USE_CONFIG = 'Use Config';
- /**
- * Prefix for inventory use config.
- */
- public const INVENTORY_USE_CONFIG_PREFIX = 'use_config_';
- /**
- * Url key attribute code
- */
- public const URL_KEY = 'url_key';
- /**
- * @var array
- */
- protected $_attributeCache = [];
- /**
- * Pairs of attribute set ID-to-name.
- *
- * @var array
- */
- protected $_attrSetIdToName = [];
- /**
- * Pairs of attribute set name-to-ID.
- *
- * @var array
- */
- protected $_attrSetNameToId = [];
- /**
- * @var string
- * @since 100.0.4
- */
- protected $mediaGalleryTableName;
- /**
- * @var string
- * @since 100.0.4
- */
- protected $mediaGalleryValueTableName;
- /**
- * @var string
- * @since 100.0.4
- */
- protected $mediaGalleryEntityToValueTableName;
- /**
- * @var string
- * @since 100.0.4
- */
- protected $productEntityTableName;
- /**
- * Attributes with index (not label) value.
- *
- * @var string[]
- */
- protected $_indexValueAttributes = [
- 'status',
- 'tax_class_id',
- ];
- /**
- * Links attribute name-to-link type ID.
- *
- * @deprecated 101.1.0 use DI for LinkProcessor class if you want to add additional types
- *
- * @var array
- */
- protected $_linkNameToId = [
- '_related_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_RELATED,
- '_crosssell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_CROSSSELL,
- '_upsell_' => \Magento\Catalog\Model\Product\Link::LINK_TYPE_UPSELL,
- ];
- /**
- * @var array
- * @since 100.1.2
- */
- protected $dateAttrCodes = [
- 'special_from_date',
- 'special_to_date',
- 'news_from_date',
- 'news_to_date',
- 'custom_design_from',
- 'custom_design_to'
- ];
- /**
- * @var bool
- */
- protected $logInHistory = true;
- /**
- * Attribute id for product images storage.
- *
- * @var array
- */
- protected $_mediaGalleryAttributeId = null;
- /**
- * @var array
- * @codingStandardsIgnoreStart
- */
- protected $_messageTemplates = [
- ValidatorInterface::ERROR_INVALID_SCOPE => 'Invalid value in Scope column',
- ValidatorInterface::ERROR_INVALID_WEBSITE => 'Invalid value in Website column (website does not exist?)',
- ValidatorInterface::ERROR_INVALID_STORE => 'Invalid value in Store column (store doesn\'t exist?)',
- ValidatorInterface::ERROR_INVALID_ATTR_SET => 'Invalid value for Attribute Set column (set doesn\'t exist?)',
- ValidatorInterface::ERROR_INVALID_TYPE => 'Product Type is invalid or not supported',
- ValidatorInterface::ERROR_INVALID_CATEGORY => 'Category does not exist',
- ValidatorInterface::ERROR_VALUE_IS_REQUIRED => 'Please make sure attribute "%s" is not empty.',
- ValidatorInterface::ERROR_TYPE_CHANGED => 'Trying to change type of existing products',
- ValidatorInterface::ERROR_SKU_IS_EMPTY => 'SKU is empty',
- ValidatorInterface::ERROR_NO_DEFAULT_ROW => 'Default values row does not exist',
- ValidatorInterface::ERROR_CHANGE_TYPE => 'Product type change is not allowed',
- ValidatorInterface::ERROR_DUPLICATE_SCOPE => 'Duplicate scope',
- ValidatorInterface::ERROR_DUPLICATE_SKU => 'Duplicate SKU',
- ValidatorInterface::ERROR_CHANGE_ATTR_SET => 'Attribute set change is not allowed',
- ValidatorInterface::ERROR_TYPE_UNSUPPORTED => 'Product type is not supported',
- ValidatorInterface::ERROR_ROW_IS_ORPHAN => 'Orphan rows that will be skipped due default row errors',
- ValidatorInterface::ERROR_INVALID_TIER_PRICE_QTY => 'Tier Price data price or quantity value is invalid',
- ValidatorInterface::ERROR_INVALID_TIER_PRICE_SITE => 'Tier Price data website is invalid',
- ValidatorInterface::ERROR_INVALID_TIER_PRICE_GROUP => 'Tier Price customer group ID is invalid',
- ValidatorInterface::ERROR_TIER_DATA_INCOMPLETE => 'Tier Price data is incomplete',
- ValidatorInterface::ERROR_SKU_NOT_FOUND_FOR_DELETE => 'Product with specified SKU not found',
- ValidatorInterface::ERROR_SUPER_PRODUCTS_SKU_NOT_FOUND => 'Product with specified super products SKU not found',
- ValidatorInterface::ERROR_MEDIA_DATA_INCOMPLETE => 'Media data is incomplete',
- ValidatorInterface::ERROR_EXCEEDED_MAX_LENGTH => 'Attribute %s exceeded max length',
- ValidatorInterface::ERROR_INVALID_ATTRIBUTE_TYPE => 'Value for \'%s\' attribute contains incorrect value',
- ValidatorInterface::ERROR_ABSENT_REQUIRED_ATTRIBUTE => 'Attribute %s is required',
- ValidatorInterface::ERROR_INVALID_ATTRIBUTE_OPTION => 'Value for \'%s\' attribute contains incorrect value, see acceptable values on settings specified for Admin',
- ValidatorInterface::ERROR_DUPLICATE_UNIQUE_ATTRIBUTE => 'Duplicated unique attribute',
- ValidatorInterface::ERROR_INVALID_VARIATIONS_CUSTOM_OPTIONS => 'Value for \'%s\' sub attribute in \'%s\' attribute contains incorrect value, acceptable values are: \'dropdown\', \'checkbox\', \'radio\', \'text\'',
- ValidatorInterface::ERROR_INVALID_MEDIA_URL_OR_PATH => 'Wrong URL/path used for attribute %s',
- ValidatorInterface::ERROR_MEDIA_PATH_NOT_ACCESSIBLE => 'Imported resource (image) does not exist in the local media storage',
- ValidatorInterface::ERROR_MEDIA_URL_NOT_ACCESSIBLE => 'Imported resource (image) could not be downloaded from external resource due to timeout or access permissions',
- ValidatorInterface::ERROR_INVALID_WEIGHT => 'Product weight is invalid',
- ValidatorInterface::ERROR_DUPLICATE_URL_KEY => 'Url key: \'%s\' was already generated for an item with the SKU: \'%s\'. You need to specify the unique URL key manually',
- ValidatorInterface::ERROR_DUPLICATE_MULTISELECT_VALUES => 'Value for multiselect attribute %s contains duplicated values',
- 'invalidNewToDateValue' => 'Make sure new_to_date is later than or the same as new_from_date',
- // Can't add new translated strings in patch release
- 'invalidLayoutUpdate' => 'Invalid format.',
- 'insufficientPermissions' => 'Invalid format.',
- ValidatorInterface::ERROR_SKU_MARGINAL_WHITESPACES => 'SKU contains marginal whitespaces'
- ];
- //@codingStandardsIgnoreEnd
- /**
- * Map between import file fields and system fields/attributes.
- *
- * @var array
- */
- protected $_fieldsMap = [
- 'image' => 'base_image',
- 'image_label' => "base_image_label",
- 'thumbnail' => 'thumbnail_image',
- 'thumbnail_label' => 'thumbnail_image_label',
- self::COL_MEDIA_IMAGE => 'additional_images',
- '_media_image_label' => 'additional_image_labels',
- '_media_is_disabled' => 'hide_from_product_page',
- Product::COL_STORE => 'store_view_code',
- Product::COL_ATTR_SET => 'attribute_set_code',
- Product::COL_TYPE => 'product_type',
- Product::COL_PRODUCT_WEBSITES => 'product_websites',
- 'status' => 'product_online',
- 'news_from_date' => 'new_from_date',
- 'news_to_date' => 'new_to_date',
- 'options_container' => 'display_product_options_in',
- 'minimal_price' => 'map_price',
- 'msrp' => 'msrp_price',
- 'msrp_enabled' => 'map_enabled',
- 'special_from_date' => 'special_price_from_date',
- 'special_to_date' => 'special_price_to_date',
- 'min_qty' => 'out_of_stock_qty',
- 'backorders' => 'allow_backorders',
- 'min_sale_qty' => 'min_cart_qty',
- 'max_sale_qty' => 'max_cart_qty',
- 'notify_stock_qty' => 'notify_on_stock_below',
- '_related_sku' => 'related_skus',
- '_related_position' => 'related_position',
- '_crosssell_sku' => 'crosssell_skus',
- '_crosssell_position' => 'crosssell_position',
- '_upsell_sku' => 'upsell_skus',
- '_upsell_position' => 'upsell_position',
- 'meta_keyword' => 'meta_keywords',
- ];
- /**
- * Existing products SKU-related information in form of array:
- *
- * [SKU] => array(
- * 'type_id' => (string) product type
- * 'attr_set_id' => (int) product attribute set ID
- * 'entity_id' => (int) product ID
- * 'supported_type' => (boolean) is product type supported by current version of import module
- * )
- *
- * @var array
- */
- protected $_oldSku = [];
- /**
- * Column names that holds values with particular meaning.
- *
- * @var string[]
- */
- protected $_specialAttributes = [
- self::COL_STORE,
- self::COL_ATTR_SET,
- self::COL_TYPE,
- self::COL_CATEGORY,
- '_product_websites',
- self::COL_PRODUCT_WEBSITES,
- '_tier_price_website',
- '_tier_price_customer_group',
- '_tier_price_qty',
- '_tier_price_price',
- '_related_sku',
- '_related_position',
- '_crosssell_sku',
- '_crosssell_position',
- '_upsell_sku',
- '_upsell_position',
- '_custom_option_store',
- '_custom_option_type',
- '_custom_option_title',
- '_custom_option_is_required',
- '_custom_option_price',
- '_custom_option_sku',
- '_custom_option_max_characters',
- '_custom_option_sort_order',
- '_custom_option_file_extension',
- '_custom_option_image_size_x',
- '_custom_option_image_size_y',
- '_custom_option_row_title',
- '_custom_option_row_price',
- '_custom_option_row_sku',
- '_custom_option_row_sort',
- '_media_attribute_id',
- self::COL_MEDIA_IMAGE,
- '_media_label',
- '_media_position',
- '_media_is_disabled',
- ];
- /**
- * @var array
- */
- protected $defaultStockData = [
- 'manage_stock' => 1,
- 'use_config_manage_stock' => 1,
- 'qty' => 0,
- 'min_qty' => 0,
- 'use_config_min_qty' => 1,
- 'min_sale_qty' => 1,
- 'use_config_min_sale_qty' => 1,
- 'max_sale_qty' => 10000,
- 'use_config_max_sale_qty' => 1,
- 'is_qty_decimal' => 0,
- 'backorders' => 0,
- 'use_config_backorders' => 1,
- 'notify_stock_qty' => 1,
- 'use_config_notify_stock_qty' => 1,
- 'enable_qty_increments' => 0,
- 'use_config_enable_qty_inc' => 1,
- 'qty_increments' => 0,
- 'use_config_qty_increments' => 1,
- 'is_in_stock' => 1,
- 'low_stock_date' => null,
- 'stock_status_changed_auto' => 0,
- 'is_decimal_divided' => 0,
- ];
- /**
- * Column names that holds images files names
- *
- * Note: the order of array items has a value in order to properly set 'position' value
- * of media gallery items.
- *
- * @var string[]
- */
- protected $_imagesArrayKeys = [];
- /**
- * Permanent entity columns.
- *
- * @var string[]
- */
- protected $_permanentAttributes = [self::COL_SKU];
- /**
- * Array of supported product types as keys with appropriate model object as value.
- *
- * @var \Magento\CatalogImportExport\Model\Import\Product\Type\AbstractType[]
- */
- protected $_productTypeModels = [];
- /**
- * Media files uploader
- *
- * @var \Magento\CatalogImportExport\Model\Import\Uploader
- */
- protected $_fileUploader;
- /**
- * Import entity which provide import of product custom options
- *
- * @var \Magento\CatalogImportExport\Model\Import\Product\Option
- */
- protected $_optionEntity;
- /**
- * @var \Magento\Catalog\Helper\Data
- */
- protected $_catalogData = null;
- /**
- * @var \Magento\CatalogInventory\Api\StockRegistryInterface
- */
- protected $stockRegistry;
- /**
- * @var \Magento\CatalogInventory\Api\StockConfigurationInterface
- */
- protected $stockConfiguration;
- /**
- * @var \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface
- */
- protected $stockStateProvider;
- /**
- * Core event manager proxy
- *
- * @var \Magento\Framework\Event\ManagerInterface
- */
- protected $_eventManager = null;
- /**
- * @var \Magento\ImportExport\Model\Import\Config
- */
- protected $_importConfig;
- /**
- * @var \Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModelFactory
- */
- protected $_resourceFactory;
- /**
- * @var \Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModel
- */
- protected $_resource;
- /**
- * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory
- */
- protected $_setColFactory;
- /**
- * @var \Magento\CatalogImportExport\Model\Import\Product\Type\Factory
- */
- protected $_productTypeFactory;
- /**
- * @var \Magento\Catalog\Model\ResourceModel\Product\LinkFactory
- */
- protected $_linkFactory;
- /**
- * @var \Magento\CatalogImportExport\Model\Import\Proxy\ProductFactory
- */
- protected $_proxyProdFactory;
- /**
- * @var \Magento\CatalogImportExport\Model\Import\UploaderFactory
- */
- protected $_uploaderFactory;
- /**
- * @var \Magento\Framework\Filesystem\Directory\WriteInterface
- */
- protected $_mediaDirectory;
- /**
- * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory
- * @deprecated 101.0.0 this variable isn't used anymore.
- */
- protected $_stockResItemFac;
- /**
- * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
- */
- protected $_localeDate;
- /**
- * @var DateTime
- */
- protected $dateTime;
- /**
- * @var \Magento\Framework\Indexer\IndexerRegistry
- */
- protected $indexerRegistry;
- /**
- * @var Product\StoreResolver
- */
- protected $storeResolver;
- /**
- * @var Product\SkuProcessor
- */
- protected $skuProcessor;
- /**
- * @var Product\CategoryProcessor
- */
- protected $categoryProcessor;
- /**
- * @var \Magento\Framework\App\Config\ScopeConfigInterface
- * @since 100.0.3
- */
- protected $scopeConfig;
- /**
- * @var \Magento\Catalog\Model\Product\Url
- * @since 100.0.3
- */
- protected $productUrl;
- /**
- * @var array
- */
- protected $websitesCache = [];
- /**
- * @var array
- */
- protected $categoriesCache = [];
- /**
- * @var array
- * @since 100.0.3
- */
- protected $productUrlSuffix = [];
- /**
- * @var array
- * @deprecated 100.0.3
- * @since 100.0.3
- */
- protected $productUrlKeys = [];
- /**
- * Instance of product tax class processor.
- *
- * @var Product\TaxClassProcessor
- */
- protected $taxClassProcessor;
- /**
- * @var Product\Validator
- */
- protected $validator;
- /**
- * Array of validated rows.
- *
- * @var array
- */
- protected $validatedRows;
- /**
- * @var \Psr\Log\LoggerInterface
- */
- private $_logger;
- /**
- * @var string
- */
- protected $masterAttributeCode = 'sku';
- /**
- * @var ObjectRelationProcessor
- */
- protected $objectRelationProcessor;
- /**
- * @var TransactionManagerInterface
- */
- protected $transactionManager;
- /**
- * Flag for replace operation.
- *
- * @var null
- */
- protected $_replaceFlag = null;
- /**
- * Flag for replace operation.
- *
- * @var null
- */
- protected $cachedImages = null;
- /**
- * @var array
- * @since 100.0.3
- */
- protected $urlKeys = [];
- /**
- * @var array
- * @since 100.0.3
- */
- protected $rowNumbers = [];
- /**
- * @var string
- */
- private $productEntityLinkField;
- /**
- * @var string
- */
- private $productEntityIdentifierField;
- /**
- * Escaped separator value for regular expression.
- * The value is based on PSEUDO_MULTI_LINE_SEPARATOR constant.
- * @var string
- */
- private $multiLineSeparatorForRegexp;
- /**
- * Container for filesystem object.
- *
- * @var Filesystem
- */
- private $filesystem;
- /**
- * @var CatalogConfig
- */
- private $catalogConfig;
- /**
- * @var StockItemImporterInterface
- */
- private $stockItemImporter;
- /**
- * @var ImageTypeProcessor
- */
- private $imageTypeProcessor;
- /**
- * Provide ability to process and save images during import.
- *
- * @var MediaGalleryProcessor
- */
- private $mediaProcessor;
- /**
- * @var DateTimeFactory
- */
- private $dateTimeFactory;
- /**
- * @var ProductRepositoryInterface
- */
- private $productRepository;
- /**
- * @var StatusProcessor
- */
- private $statusProcessor;
- /**
- * @var StockProcessor
- */
- private $stockProcessor;
- /**
- * @var LinkProcessor
- */
- private $linkProcessor;
- public $productFactoryData;
- /**
- * @param \Magento\Framework\Json\Helper\Data $jsonHelper
- * @param \Magento\ImportExport\Helper\Data $importExportData
- * @param \Magento\ImportExport\Model\ResourceModel\Import\Data $importData
- * @param \Magento\Eav\Model\Config $config
- * @param \Magento\Framework\App\ResourceConnection $resource
- * @param \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper
- * @param \Magento\Framework\Stdlib\StringUtils $string
- * @param ProcessingErrorAggregatorInterface $errorAggregator
- * @param \Magento\Framework\Event\ManagerInterface $eventManager
- * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
- * @param \Magento\CatalogInventory\Api\StockConfigurationInterface $stockConfiguration
- * @param \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface $stockStateProvider
- * @param \Magento\Catalog\Helper\Data $catalogData
- * @param \Magento\ImportExport\Model\Import\Config $importConfig
- * @param Proxy\Product\ResourceModelFactory $resourceFactory
- * @param Product\OptionFactory $optionFactory
- * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setColFactory
- * @param Product\Type\Factory $productTypeFactory
- * @param \Magento\Catalog\Model\ResourceModel\Product\LinkFactory $linkFactory
- * @param Proxy\ProductFactory $proxyProdFactory
- * @param UploaderFactory $uploaderFactory
- * @param \Magento\Framework\Filesystem $filesystem
- * @param \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory $stockResItemFac
- * @param DateTime\TimezoneInterface $localeDate
- * @param DateTime $dateTime
- * @param \Psr\Log\LoggerInterface $logger
- * @param \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry
- * @param Product\StoreResolver $storeResolver
- * @param Product\SkuProcessor $skuProcessor
- * @param Product\CategoryProcessor $categoryProcessor
- * @param Product\Validator $validator
- * @param ObjectRelationProcessor $objectRelationProcessor
- * @param TransactionManagerInterface $transactionManager
- * @param Product\TaxClassProcessor $taxClassProcessor
- * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
- * @param \Magento\Catalog\Model\Product\Url $productUrl
- * @param array $data
- * @param array $dateAttrCodes
- * @param CatalogConfig $catalogConfig
- * @param ImageTypeProcessor $imageTypeProcessor
- * @param MediaGalleryProcessor $mediaProcessor
- * @param StockItemImporterInterface|null $stockItemImporter
- * @param DateTimeFactory $dateTimeFactory
- * @param ProductRepositoryInterface|null $productRepository
- * @param StatusProcessor|null $statusProcessor
- * @param StockProcessor|null $stockProcessor
- * @param LinkProcessor|null $linkProcessor
- * @param File|null $fileDriver
- * @throws LocalizedException
- * @throws \Magento\Framework\Exception\FileSystemException
- * @SuppressWarnings(PHPMD.ExcessiveParameterList)
- * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
- * @SuppressWarnings(PHPMD.UnusedFormalParameter)
- */
- public function __construct(
- \Magento\Framework\Json\Helper\Data $jsonHelper,
- \Magento\ImportExport\Helper\Data $importExportData,
- \Magento\ImportExport\Model\ResourceModel\Import\Data $importData,
- \Magento\Eav\Model\Config $config,
- \Magento\Framework\App\ResourceConnection $resource,
- \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper,
- \Magento\Framework\Stdlib\StringUtils $string,
- ProcessingErrorAggregatorInterface $errorAggregator,
- \Magento\Framework\Event\ManagerInterface $eventManager,
- \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
- \Magento\CatalogInventory\Api\StockConfigurationInterface $stockConfiguration,
- \Magento\CatalogInventory\Model\Spi\StockStateProviderInterface $stockStateProvider,
- \Magento\Catalog\Helper\Data $catalogData,
- \Magento\ImportExport\Model\Import\Config $importConfig,
- \Magento\CatalogImportExport\Model\Import\Proxy\Product\ResourceModelFactory $resourceFactory,
- \Magento\CatalogImportExport\Model\Import\Product\OptionFactory $optionFactory,
- \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setColFactory,
- \Magento\CatalogImportExport\Model\Import\Product\Type\Factory $productTypeFactory,
- \Magento\Catalog\Model\ResourceModel\Product\LinkFactory $linkFactory,
- \Magento\CatalogImportExport\Model\Import\Proxy\ProductFactory $proxyProdFactory,
- \Magento\CatalogImportExport\Model\Import\UploaderFactory $uploaderFactory,
- \Magento\Framework\Filesystem $filesystem,
- \Magento\CatalogInventory\Model\ResourceModel\Stock\ItemFactory $stockResItemFac,
- \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
- DateTime $dateTime,
- \Psr\Log\LoggerInterface $logger,
- \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry,
- \Magento\CatalogImportExport\Model\Import\Product\StoreResolver $storeResolver,
- \Magento\CatalogImportExport\Model\Import\Product\SkuProcessor $skuProcessor,
- \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor $categoryProcessor,
- \Magento\CatalogImportExport\Model\Import\Product\Validator $validator,
- ObjectRelationProcessor $objectRelationProcessor,
- TransactionManagerInterface $transactionManager,
- \Magento\CatalogImportExport\Model\Import\Product\TaxClassProcessor $taxClassProcessor,
- \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
- \Magento\Catalog\Model\Product\Url $productUrl,
- array $data = [],
- array $dateAttrCodes = [],
- CatalogConfig $catalogConfig = null,
- ImageTypeProcessor $imageTypeProcessor = null,
- MediaGalleryProcessor $mediaProcessor = null,
- StockItemImporterInterface $stockItemImporter = null,
- DateTimeFactory $dateTimeFactory = null,
- ProductRepositoryInterface $productRepository = null,
- StatusProcessor $statusProcessor = null,
- StockProcessor $stockProcessor = null,
- LinkProcessor $linkProcessor = null,
- File $fileDriver = null,
- \Magento\Catalog\Model\ProductFactory $productFactoryData,
- \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
- ) {
- $this->_eventManager = $eventManager;
- $this->stockRegistry = $stockRegistry;
- $this->stockConfiguration = $stockConfiguration;
- $this->stockStateProvider = $stockStateProvider;
- $this->_catalogData = $catalogData;
- $this->_importConfig = $importConfig;
- $this->_resourceFactory = $resourceFactory;
- $this->_setColFactory = $setColFactory;
- $this->_productTypeFactory = $productTypeFactory;
- $this->_linkFactory = $linkFactory;
- $this->_proxyProdFactory = $proxyProdFactory;
- $this->_uploaderFactory = $uploaderFactory;
- $this->filesystem = $filesystem;
- $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::ROOT);
- $this->_stockResItemFac = $stockResItemFac;
- $this->_localeDate = $localeDate;
- $this->dateTime = $dateTime;
- $this->indexerRegistry = $indexerRegistry;
- $this->_logger = $logger;
- $this->storeResolver = $storeResolver;
- $this->skuProcessor = $skuProcessor;
- $this->categoryProcessor = $categoryProcessor;
- $this->validator = $validator;
- $this->objectRelationProcessor = $objectRelationProcessor;
- $this->transactionManager = $transactionManager;
- $this->taxClassProcessor = $taxClassProcessor;
- $this->scopeConfig = $scopeConfig;
- $this->productUrl = $productUrl;
- $this->dateAttrCodes = array_merge($this->dateAttrCodes, $dateAttrCodes);
- $this->catalogConfig = $catalogConfig ?: ObjectManager::getInstance()->get(CatalogConfig::class);
- $this->imageTypeProcessor = $imageTypeProcessor ?: ObjectManager::getInstance()->get(ImageTypeProcessor::class);
- $this->mediaProcessor = $mediaProcessor ?: ObjectManager::getInstance()->get(MediaGalleryProcessor::class);
- $this->stockItemImporter = $stockItemImporter ?: ObjectManager::getInstance()
- ->get(StockItemImporterInterface::class);
- $this->statusProcessor = $statusProcessor ?: ObjectManager::getInstance()
- ->get(StatusProcessor::class);
- $this->stockProcessor = $stockProcessor ?: ObjectManager::getInstance()
- ->get(StockProcessor::class);
- $this->linkProcessor = $linkProcessor ?? ObjectManager::getInstance()
- ->get(LinkProcessor::class);
- $this->linkProcessor->addNameToIds($this->_linkNameToId);
- $this->data = $data;
- $this->productFactoryData = $productFactoryData;
- $this->productCollectionFactory = $productCollectionFactory;
- parent::__construct(
- $jsonHelper,
- $importExportData,
- $importData,
- $config,
- $resource,
- $resourceHelper,
- $string,
- $errorAggregator,
- $eventManager,
- $stockRegistry,
- $stockConfiguration,
- $stockStateProvider,
- $catalogData,$importConfig,$resourceFactory,$optionFactory,$setColFactory,$productTypeFactory,
- $linkFactory,$proxyProdFactory,$uploaderFactory,$filesystem,$stockResItemFac,$localeDate,$dateTime,$logger,$indexerRegistry,$storeResolver,$skuProcessor,$categoryProcessor,$validator,$objectRelationProcessor,$transactionManager,$taxClassProcessor,
- $scopeConfig,$productUrl,$data,$dateAttrCodes,$catalogConfig,$imageTypeProcessor,$mediaProcessor,
- $stockItemImporter,$dateTimeFactory,$productRepository,$statusProcessor,$stockProcessor,
- $linkProcessor,$fileDriver
- );
- $this->_optionEntity = $data['option_entity'] ??
- $optionFactory->create(['data' => ['product_entity' => $this]]);
- $this->_initAttributeSets()
- ->_initTypeModels()
- ->_initSkus()
- ->initImagesArrayKeys();
- $this->validator->init($this);
- $this->dateTimeFactory = $dateTimeFactory ?? ObjectManager::getInstance()->get(DateTimeFactory::class);
- $this->productRepository = $productRepository ?? ObjectManager::getInstance()
- ->get(ProductRepositoryInterface::class);
- }
- /**
- * Save products data.
- *
- * @return $this
- * @throws LocalizedException
- */
- protected function _saveProductsData()
- {
- $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
- $logger = new \Zend_Log();
- $logger->addWriter($writer);
- $logger->info('_saveProductsData');
- $this->_saveProducts();
- foreach ($this->_productTypeModels as $productTypeModel) {
- $productTypeModel->saveData();
- }
- $this->linkProcessor->saveLinks($this, $this->_dataSourceModel, $this->getProductEntityLinkField());
- $this->_saveStockItem();
- if ($this->_replaceFlag) {
- $this->getOptionEntity()->clearProductsSkuToId();
- }
- $this->getOptionEntity()->importData();
- return $this;
- }
- /**
- * Stock item saving.
- *
- * @return $this
- */
- protected function _saveStockItem()
- {
- $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
- $logger = new \Zend_Log();
- $logger->addWriter($writer);
- $logger->info('save stockitem');
- while ($bunch = $this->_dataSourceModel->getNextBunch()) {
- $stockData = [];
- $productIdsToReindex = [];
- $stockChangedProductIds = [];
- // Format bunch to stock data rows
- foreach ($bunch as $rowNum => $rowData) {
- $logger->info('rowdata'.json_encode($rowData));
- $logger->info('rowNum'.json_encode($rowNum));
- if($rowNum == 0)
- {
- $this->getConnection()->truncateTable('product_constituents');
- }
- if (!$this->isRowAllowedToImport($rowData, $rowNum)) {
- continue;
- }
- $row = [];
- $sku = $rowData[self::COL_SKU];
- if ($this->skuProcessor->getNewSku($sku) !== null) {
- $stockItem = $this->getRowExistingStockItem($rowData);
- $existingStockItemData = $stockItem->getData();
- $row = $this->formatStockDataForRow($rowData);
- $productIdsToReindex[] = $row['product_id'];
- $storeId = $this->getRowStoreId($rowData);
- if (!empty(array_diff_assoc($row, $existingStockItemData))
- || $this->statusProcessor->isStatusChanged($sku, $storeId)
- ) {
- $stockChangedProductIds[] = $row['product_id'];
- }
- $this->productConstitutesProcess($row, $rowData);
- }
- if (!isset($stockData[$sku])) {
- $stockData[$sku] = $row;
- }
- }
- // Insert rows
- if (!empty($stockData)) {
- $this->stockItemImporter->import($stockData);
- //$logger->info('stockData ='.json_encode($stockData));
- foreach($stockData as $product)
- {
- //$logger->info('stock product ='.json_encode($product));
- }
- }
- $this->reindexStockStatus($stockChangedProductIds);
- $this->reindexProducts($productIdsToReindex);
- }
- return $this;
- }
- public function getDefaultVariantId($product)
- {
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $productVariantIds = $objectManager->create('Froogal\Catalog\Model\ProductVariant')
- ->getCollection()
- ->addFieldToFilter('product_id', $product['product_id'])
- ->addFieldToFilter('variant_name', 'default')
- ->getData();
- if(empty($productVariantIds))
- {
- $model = $objectManager->create('Froogal\Catalog\Model\ProductVariantFactory')->create();
- $model->addData([
- "product_id" => $product['product_id'],
- "variant_name" => "default"
- ]);
- $model->save();
- return $model->getData()['id'];
- } else {
- return $productVariantIds[0]['id'];
- }
- }
- public function deleteAllConsituents($product, $variantId)
- {
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $model = $objectManager->create('Froogal\Catalog\Model\ProductRelation')
- ->getCollection()
- ->addFieldToFilter('product_id', $product['product_id'])
- ->addFieldToFilter('variant_id', $variantId)
- ->load();
- foreach ($model as $m) {
- $m->delete();
- }
- }
- protected $customLogger;
- public function productConstitutesProcess($product,$rowData)
- {
- $variantId = $this->getDefaultVariantId($product);
- // $this->deleteAllConsituents($product, $variantId);
- $this->saveGoldProductConstituents($product, $variantId, $rowData);
- $this->savePlatinumProductConstituents($product, $variantId, $rowData);
- $this->saveDiamondProductConstituents($product, $variantId, $rowData);
- }
- public function saveGoldProductConstituents($product, $variantId, $rowData)
- {
- $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
- $logger = new \Zend_Log();
- $logger->addWriter($writer);
- if (isset($rowData['gold_weight']) && $rowData['gold_weight'] > 0) {
- if (empty($rowData['gold_carat'])) {
- throw new LocalizedException(__('gold_carat not found!'));
- }
- if (empty($rowData['gold_color'])) {
- throw new LocalizedException(__('gold_color not found!'));
- }
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $productId = $product['product_id'];
- $goldWeight = $rowData['gold_weight'];
- $goldCarat = $rowData['gold_carat'];
- $goldColor = $rowData['gold_color'];
- $logger->info('row gold color'.$goldColor);
- $logger->info('row gold carat'.$goldCarat);
- $attribute = $objectManager->create('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
- $attributeColor= $attribute->get('gold_color');
- $attributeCarat= $attribute->get('gold_carat');
- $attributeConstituentType= $attribute->get('constituent_type');
- $attributeColorId = $attributeColor->getAttributeId();
- $attributeCaratId = $attributeCarat->getAttributeId();
- $attributeConstituentTypeId = $attributeConstituentType->getAttributeId();
- $attributeconfig = $objectManager->create('\Magento\Eav\Model\Config');
- $attributeType = $attributeconfig->getAttribute('catalog_product', $attributeConstituentTypeId);
- $attributeColor = $attributeconfig->getAttribute('catalog_product', $attributeColorId);
- $attributeCarat = $attributeconfig->getAttribute('catalog_product', $attributeCaratId);
- $attributeColoroptions = $attributeColor->getSource()->getAllOptions();
- $attributeCaratoptions = $attributeCarat->getSource()->getAllOptions();
- $attributeTypeoptions = $attributeType->getSource()->getAllOptions();
- $constitute_type_id = null;
- foreach($attributeTypeoptions as $type)
- {
- if($type['label'] == "Gold")
- {
- $constitute_type_id = $type['value'];
- break;
- }
- }
- foreach($attributeColoroptions as $option)
- {
- $goldColorId = $option['value'];
- $logger->info('inside foreach color id'.$goldColorId);
- if($option['label'] == ucfirst($goldColor))
- {
- $logger->info('inside foreach color label'.$option['label']);
- foreach($attributeCaratoptions as $optionvalues)
- {
- $goldCaratId = $optionvalues['value'];
- $logger->info('inside foreach carat id'.$goldCarat);
- if($optionvalues['label'] == $goldCarat)
- {
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $productCollectionFactory = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
- $collection = $productCollectionFactory->create();
- $collection->addAttributeToFilter('is_constituent', array('like' => '%1%'));
- $collection->addAttributeToFilter('constituent_type', array('like' => "%$constitute_type_id%"));
- $collection->addAttributeToFilter('gold_color', array('like' => "%$goldColorId%"));
- $collection->addAttributeToFilter('gold_carat', array('like' => "%$goldCaratId%"));
- $collection->addAttributeToSelect('*')->setPageSize(1,1);
- $logger->info('gold collection'.json_encode($collection->getData()));
- $collectionData = $collection->getData();
- if(!empty($collectionData))
- {
- $model = $objectManager->create('Froogal\Catalog\Model\ProductRelationFactory')->create();
- $model->addData([
- "product_id" => $productId,
- "contituent_product_id" => $collectionData[0]['entity_id'],
- "variant_id" => $variantId,
- 'carat' => null,
- "qty" => $goldWeight,
- ]);
- $model->save();
- $logger->info('goldcolor'.$goldColor);
- $logger->info('goldcarat'.$goldCarat);
- }
- // else
- // {
- // throw new LocalizedException(__('constituent product not found!'));
- // }
- }
- }
- }
- }
- }
- }
- public function savePlatinumProductConstituents($product,$variantId,$rowData)
- {
- $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
- $logger = new \Zend_Log();
- $logger->addWriter($writer);
- if (isset($rowData['platinum_weight']) && $rowData['platinum_weight'] > 0) {
- if (empty($rowData['platinum_weight'])) {
- throw new LocalizedException(__('platinum_weight not found!'));
- }
- $productId = $product['product_id'];
- $platinumWeight = $rowData['platinum_weight'];
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $attribute = $objectManager->create('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
- $attributeConstituentType= $attribute->get('constituent_type');
- $attributeConstituentTypeId = $attributeConstituentType->getAttributeId();
- $attributeConstituentTypeId = $attributeConstituentType->getAttributeId();
- $attributeconfig = $objectManager->create('\Magento\Eav\Model\Config');
- $attributeType = $attributeconfig->getAttribute('catalog_product', $attributeConstituentTypeId);
- $attributeTypeoptions = $attributeType->getSource()->getAllOptions();
- $constitute_type_id = null;
- foreach($attributeTypeoptions as $type)
- {
- if($type['label'] == "Platinum")
- {
- $constitute_type_id = $type['value'];
- break;
- }
- }
- // $constituentProduct = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()->addFieldToFilter('product_id', $productId)->getFirstItem();
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $productCollectionFactory = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
- $collection = $productCollectionFactory->create();
- $collection->addAttributeToFilter('is_constituent', array('like' => '%1%'));
- $collection->addAttributeToFilter('constituent_type', array('like' => "%$constitute_type_id%"));
- $collection->addAttributeToSelect('*')->setPageSize(1,1);
- $logger->info('platinum constituentProduct'.json_encode($collection->getData()));
- $collectionData = $collection->getData();
- if(!empty($collectionData))
- {
- $model = $objectManager->create('Froogal\Catalog\Model\ProductRelationFactory')->create();
- // $model = $productRelationFactory->create(getAllOptionsgetAllOptions);
- $model->addData([
- "product_id" => $productId,
- "contituent_product_id" => $collectionData[0]['entity_id'],
- "variant_id" => $variantId,
- 'carat' => null,
- "qty" => $platinumWeight,
- ]);
- $model->save();
- }
- else
- {
- throw new LocalizedException(
- __('Please enter a correct entity model')
- );
- }
- }
- }
- public function saveDiamondProductConstituents($product, $variantId, $rowData)
- {
- $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
- $logger = new \Zend_Log();
- $logger->addWriter($writer);
- $logger->info('row data elements'.json_encode($rowData));
- if(isset($rowData['diamond_shape']))
- {
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $attribute = $objectManager->create('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
- $attributeConstituentType= $attribute->get('constituent_type');
- $attributeShape= $attribute->get('diamond_shape');
- $attributeQuality= $attribute->get('diamond_quality');
- $attributeDiamondSlab= $attribute->get('diamond_slab');
- $attributeConstituentTypeId = $attributeConstituentType->getAttributeId();
- $attributeShapeId = $attributeShape->getAttributeId();
- $attributeQualityId = $attributeQuality->getAttributeId();
- $attributeDiamondSlabId = $attributeDiamondSlab->getAttributeId();
- $attributeconfig = $objectManager->create('\Magento\Eav\Model\Config');
- $attributeType = $attributeconfig->getAttribute('catalog_product', $attributeConstituentTypeId);
- $attributeShape = $attributeconfig->getAttribute('catalog_product', $attributeShapeId);
- $attributeQuality = $attributeconfig->getAttribute('catalog_product', $attributeQualityId);
- $attributeSlab = $attributeconfig->getAttribute('catalog_product', $attributeDiamondSlabId);
- $attributeShapeoptions = $attributeShape->getSource()->getAllOptions();
- $attributeQualityoptions = $attributeQuality->getSource()->getAllOptions();
- $attributeTypeoptions = $attributeType->getSource()->getAllOptions();
- $attributeSlabOptions = $attributeSlab->getSource()->getAllOptions();
- $constitute_type_id = null;
- $slabId=null;
- $carat = null;
- $qty = 0;
- foreach($attributeTypeoptions as $type)
- {
- if($type['label'] == "Diamond")
- {
- $constitute_type_id = $type['value'];
- break;
- }
- }
- if(!empty($rowData))
- {
- $productId = $product['product_id'];
- // $diamondType = $rowData['constituent_type'];
- $shape = $rowData['diamond_shape'];
- // $category = $rowData['diamond_category'];
- $quality = $rowData['diamond_quality'];
- $slab = $rowData['diamond_slab'];
- $carat = $rowData['diamond_carat'];
- $qty = $rowData['diamond_qty'];
- if($attributeSlabOptions)
- {
- foreach($attributeSlabOptions as $slaboption)
- {
- if($slaboption['label'] == $slab)
- {
- $slabId = $slaboption['value'];
- break;
- }
- }
- }
- foreach($attributeShapeoptions as $option)
- {
- $shapeId = $option['value'];
- if($option['label'] == $shape)
- {
- foreach($attributeQualityoptions as $optionvalues)
- {
- $qualityId = $optionvalues['value'];
- if($optionvalues['label'] == $quality)
- {
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $productCollectionFactory = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
- $collection = $productCollectionFactory->create();
- $collection->addAttributeToFilter('is_constituent', array('like' => '%1%'));
- $collection->addAttributeToFilter('constituent_type', array('like' => "%$constitute_type_id%"));
- $collection->addAttributeToFilter('diamond_shape', array('like' => "%$shapeId%"));
- $collection->addAttributeToFilter('diamond_quality', array('like' => "%$qualityId%"));
- $collection->addAttributeToFilter('diamond_slab', array('like' => $slabId));
- $collection->addAttributeToSelect('*')->setPageSize(1,1);
- $collectionData = $collection->getData();
- $logger->info('collection data'.json_encode($collectionData));
- if(!empty($collectionData))
- {
- $model = $objectManager->create('Froogal\Catalog\Model\ProductRelationFactory')->create();
- // $model = $productRelationFactory->create();
- $model->addData([
- "product_id" => $productId,
- "contituent_product_id" => $collectionData[0]['entity_id'],
- "variant_id" => $variantId,
- 'carat' => $carat,
- "qty" => $qty,
- ]);
- $model->save();
- }
- else
- {
- $cproduct = $shape.'_'.$quality.'_'.$slab;
- throw new LocalizedException(__($cproduct.' constituent product not found!'));
- }
- }
- }
- }
- }
- }
- }
- }
- // {
- // return $this->productFactoryData->create()->loadByAttribute($field, $value);
- // }
- /**
- * Initialize image array keys.
- *
- * @return $this
- */
- private function initImagesArrayKeys()
- {
- $this->_imagesArrayKeys = $this->imageTypeProcessor->getImageTypes();
- return $this;
- }
- /**
- * Whether a url key is needed to be change.
- *
- * @param array $rowData
- * @return bool
- */
- private function isNeedToChangeUrlKey(array $rowData): bool
- {
- $urlKey = $this->getUrlKey($rowData);
- $productExists = $this->isSkuExist($rowData[self::COL_SKU]);
- $markedToEraseUrlKey = isset($rowData[self::URL_KEY]);
- // The product isn't new and the url key index wasn't marked for change.
- if (!$urlKey && $productExists && !$markedToEraseUrlKey) {
- // Seems there is no need to change the url key
- return false;
- }
- return true;
- }
- /**
- * Get product entity link field
- *
- * @return string
- */
- private function getProductEntityLinkField()
- {
- if (!$this->productEntityLinkField) {
- $this->productEntityLinkField = $this->getMetadataPool()
- ->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class)
- ->getLinkField();
- }
- return $this->productEntityLinkField;
- }
- /**
- * Get product entity identifier field
- *
- * @return string
- */
- private function getProductIdentifierField()
- {
- if (!$this->productEntityIdentifierField) {
- $this->productEntityIdentifierField = $this->getMetadataPool()
- ->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class)
- ->getIdentifierField();
- }
- return $this->productEntityIdentifierField;
- }
- /**
- * Update media gallery labels
- *
- * @param array $labels
- * @return void
- */
- private function updateMediaGalleryLabels(array $labels)
- {
- if (!empty($labels)) {
- $this->mediaProcessor->updateMediaGalleryLabels($labels);
- }
- }
- /**
- * Update 'disabled' field for media gallery entity
- *
- * @param array $images
- * @return $this
- */
- private function updateMediaGalleryVisibility(array $images)
- {
- if (!empty($images)) {
- $this->mediaProcessor->updateMediaGalleryVisibility($images);
- }
- return $this;
- }
- /**
- * Parse values from multiple attributes fields
- *
- * @param string $labelRow
- * @return array
- */
- private function parseMultipleValues($labelRow)
- {
- return $this->parseMultiselectValues(
- $labelRow,
- $this->getMultipleValueSeparator()
- );
- }
- /**
- * Check if product exists for specified SKU
- *
- * @param string $sku
- * @return bool
- */
- private function isSkuExist($sku)
- {
- if ($sku !== null) {
- $sku = strtolower($sku);
- return isset($this->_oldSku[$sku]);
- }
- return false;
- }
- /**
- * Get existing product data for specified SKU
- *
- * @param string $sku
- * @return array
- */
- private function getExistingSku($sku)
- {
- return $this->_oldSku[strtolower($sku)];
- }
- /**
- * Format row data to DB compatible values.
- *
- * @param array $rowData
- * @return array
- */
- private function formatStockDataForRow(array $rowData): array
- {
- $sku = $rowData[self::COL_SKU];
- $row['product_id'] = $this->skuProcessor->getNewSku($sku)['entity_id'];
- $row['website_id'] = $this->stockConfiguration->getDefaultScopeId();
- $row['stock_id'] = $this->stockRegistry->getStock($row['website_id'])->getStockId();
- $stockItemDo = $this->stockRegistry->getStockItem($row['product_id'], $row['website_id']);
- $existStockData = $stockItemDo->getData();
- $row = array_merge(
- $this->defaultStockData,
- array_intersect_key($existStockData, $this->defaultStockData),
- array_intersect_key($rowData, $this->defaultStockData),
- $row
- );
- if ($this->stockConfiguration->isQty($this->skuProcessor->getNewSku($sku)['type_id'])) {
- $stockItemDo->setData($row);
- $row['is_in_stock'] = $this->stockStateProvider->verifyStock($stockItemDo)
- ? (int) $row['is_in_stock']
- : 0;
- if ($this->stockStateProvider->verifyNotification($stockItemDo)) {
- $date = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC'));
- $row['low_stock_date'] = $date->format(DateTime::DATETIME_PHP_FORMAT);
- }
- $row['stock_status_changed_auto'] = (int)!$this->stockStateProvider->verifyStock($stockItemDo);
- } else {
- $row['qty'] = 0;
- }
- return $row;
- }
- /**
- * Retrieve product by sku.
- *
- * @param string $sku
- * @return \Magento\Catalog\Api\Data\ProductInterface|null
- */
- private function retrieveProductBySku($sku)
- {
- try {
- $product = $this->productRepository->get($sku);
- } catch (NoSuchEntityException $e) {
- return null;
- }
- return $product;
- }
- /**
- * Add row as skipped
- *
- * @param int $rowNum
- * @param string $errorCode Error code or simply column name
- * @param string $errorLevel error level
- * @param string|null $colName optional column name
- * @return $this
- */
- private function skipRow(
- $rowNum,
- string $errorCode,
- string $errorLevel = ProcessingError::ERROR_LEVEL_NOT_CRITICAL,
- $colName = null
- ): self {
- $this->addRowError($errorCode, $rowNum, $colName, null, $errorLevel);
- $this->getErrorAggregator()
- ->addRowToSkip($rowNum);
- return $this;
- }
- /**
- * Returns errorLevel for validation
- *
- * @param string $sku
- * @return string
- */
- private function getValidationErrorLevel($sku): string
- {
- return (!$this->isSkuExist($sku) && Import::BEHAVIOR_REPLACE !== $this->getBehavior())
- ? ProcessingError::ERROR_LEVEL_CRITICAL
- : ProcessingError::ERROR_LEVEL_NOT_CRITICAL;
- }
- /**
- * Get row store ID
- *
- * @param array $rowData
- * @return int
- */
- private function getRowStoreId(array $rowData): int
- {
- return !empty($rowData[self::COL_STORE])
- ? (int) $this->getStoreIdByCode($rowData[self::COL_STORE])
- : Store::DEFAULT_STORE_ID;
- }
- /**
- * Get row stock item model
- *
- * @param array $rowData
- * @return StockItemInterface
- */
- private function getRowExistingStockItem(array $rowData): StockItemInterface
- {
- $productId = $this->skuProcessor->getNewSku($rowData[self::COL_SKU])['entity_id'];
- $websiteId = $this->stockConfiguration->getDefaultScopeId();
- return $this->stockRegistry->getStockItem($productId, $websiteId);
- }
- /**
- * Returns image that matches the provided hash
- *
- * @param array $images
- * @param string $hash
- * @return string
- */
- private function findImageByHash(array $images, string $hash): string
- {
- $value = '';
- if ($hash) {
- foreach ($images as $image) {
- if (isset($image['hash']) && $image['hash'] === $hash) {
- $value = $image['value'];
- break;
- }
- }
- }
- return $value;
- }
- /**
- * Returns product media
- *
- * @return string relative path to root folder
- */
- private function getProductMediaPath(): string
- {
- return $this->joinFilePaths($this->getMediaBasePath(), 'catalog', 'product');
- }
- /**
- * Returns media base path
- *
- * @return string relative path to root folder
- */
- private function getMediaBasePath(): string
- {
- $mediaDir = !is_a($this->_mediaDirectory->getDriver(), File::class)
- // make media folder a primary folder for media in external storages
- ? $this->filesystem->getDirectoryReadByPath(DirectoryList::MEDIA)
- : $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
- return $this->_mediaDirectory->getRelativePath($mediaDir->getAbsolutePath());
- }
- /**
- * Joins two paths and remove redundant directory separator
- *
- * @param array $paths
- * @return string
- */
- private function joinFilePaths(...$paths): string
- {
- $result = '';
- if ($paths) {
- $firstPath = array_shift($paths);
- $result = $firstPath !== null ? rtrim($firstPath, DIRECTORY_SEPARATOR) : '';
- foreach ($paths as $path) {
- $result .= DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR);
- }
- }
- return $result;
- }
- /**
- * Reindex stock status for provided product IDs
- *
- * @param array $productIds
- */
- private function reindexStockStatus(array $productIds): void
- {
- if ($productIds) {
- $this->stockProcessor->reindexList($productIds);
- }
- }
- /**
- * Initiate product reindex by product ids
- *
- * @param array $productIdsToReindex
- * @return void
- */
- private function reindexProducts($productIdsToReindex = [])
- {
- $indexer = $this->indexerRegistry->get('catalog_product_category');
- if (is_array($productIdsToReindex) && count($productIdsToReindex) > 0 && !$indexer->isScheduled()) {
- $indexer->reindexList($productIdsToReindex);
- }
- }
- }
Add Comment
Please, Sign In to add comment