Exemple #1
0
 /**
  * Initialize product before saving
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function initialize(\Magento\Catalog\Model\Product $product)
 {
     $productData = $this->request->getPost('product');
     unset($productData['custom_attributes']);
     unset($productData['extension_attributes']);
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : [];
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     foreach (['category_ids', 'website_ids'] as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = [];
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore()) {
         $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = $this->request->getPost('use_default');
     if ($useDefaults) {
         foreach ($useDefaults as $attributeCode) {
             $product->setData($attributeCode, false);
         }
     }
     $links = $this->request->getPost('links');
     $links = is_array($links) ? $links : [];
     $linkTypes = ['related', 'upsell', 'crosssell'];
     foreach ($linkTypes as $type) {
         if (isset($links[$type])) {
             $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]);
         }
     }
     $product = $this->productLinks->initializeLinks($product, $links);
     /**
      * Initialize product options
      */
     if (isset($productData['options']) && !$product->getOptionsReadonly()) {
         // mark custom options that should to fall back to default value
         $options = $this->mergeProductOptions($productData['options'], $this->request->getPost('options_use_default'));
         $product->setProductOptions($options);
     }
     $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly());
     return $product;
 }
 /**
  * Process scope query parameters.
  *
  * @param \Magento\Framework\Url\RouteParamsResolver $subject
  * @param callable $proceed
  * @param array $data
  * @param bool $unsetOldParams
  * @return \Magento\Framework\Url\RouteParamsResolver
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundSetRouteParams(\Magento\Framework\Url\RouteParamsResolver $subject, \Closure $proceed, array $data, $unsetOldParams = true)
 {
     if (isset($data['_scope'])) {
         $subject->setScope($data['_scope']);
         unset($data['_scope']);
     }
     if (isset($data['_scope_to_url']) && (bool) $data['_scope_to_url'] === true) {
         $storeCode = $subject->getScope() ?: $this->storeManager->getStore()->getCode();
         $useStoreInUrl = $this->scopeConfig->getValue(Store::XML_PATH_STORE_IN_URL, StoreScopeInterface::SCOPE_STORE, $storeCode);
         if (!$useStoreInUrl && !$this->storeManager->hasSingleStore()) {
             $this->queryParamsResolver->setQueryParam('___store', $storeCode);
         }
     }
     unset($data['_scope_to_url']);
     return $proceed($data, $unsetOldParams);
 }
 /**
  * {@inheritdoc}
  */
 public function setRouteParams(array $data, $unsetOldParams = true)
 {
     if (isset($data['_type'])) {
         $this->setType($data['_type']);
         unset($data['_type']);
     }
     if (isset($data['_scope'])) {
         $this->setScope($data['_scope']);
         unset($data['_scope']);
     }
     if (isset($data['_forced_secure'])) {
         $this->setSecure((bool) $data['_forced_secure']);
         $this->setSecureIsForced(true);
         unset($data['_forced_secure']);
     } elseif (isset($data['_secure'])) {
         $this->setSecure((bool) $data['_secure']);
         unset($data['_secure']);
     }
     if (isset($data['_absolute'])) {
         unset($data['_absolute']);
     }
     if ($unsetOldParams) {
         $this->unsetData('route_params');
     }
     if (isset($data['_current'])) {
         if (is_array($data['_current'])) {
             foreach ($data['_current'] as $key) {
                 if (array_key_exists($key, $data) || !$this->_request->getUserParam($key)) {
                     continue;
                 }
                 $data[$key] = $this->_request->getUserParam($key);
             }
         } elseif ($data['_current']) {
             foreach ($this->_request->getUserParams() as $key => $value) {
                 if (array_key_exists($key, $data) || $this->getRouteParam($key)) {
                     continue;
                 }
                 $data[$key] = $value;
             }
             foreach ($this->_request->getQuery() as $key => $value) {
                 $this->_queryParamsResolver->setQueryParam($key, $value);
             }
         }
         unset($data['_current']);
     }
     if (isset($data['_use_rewrite'])) {
         unset($data['_use_rewrite']);
     }
     if (isset($data['_scope_to_url']) && (bool) $data['_scope_to_url'] === true) {
         $store = $this->getScope() ?: $this->_storeManager->getStore();
         if (!$this->_scopeConfig->getValue(\Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $this->getScope()) && !$this->_storeManager->hasSingleStore()) {
             $this->_queryParamsResolver->setQueryParam('___store', $store->getCode());
         }
     }
     unset($data['_scope_to_url']);
     foreach ($data as $key => $value) {
         $this->setRouteParam($key, $value);
     }
     return $this;
 }
Exemple #4
0
    /**
     * Check for unique of identifier of block to selected store(s).
     *
     * @param \Magento\Framework\Model\AbstractModel $object
     * @return bool
     * @SuppressWarnings(PHPMD.BooleanGetMethodName)
     */
    public function getIsUniqueBlockToStores(\Magento\Framework\Model\AbstractModel $object)
    {
        if ($this->_storeManager->hasSingleStore()) {
            $stores = [\Magento\Store\Model\Store::DEFAULT_STORE_ID];
        } else {
            $stores = (array)$object->getData('stores');
        }

        $select = $this->getConnection()->select()->from(
            ['cb' => $this->getMainTable()]
        )->join(
            ['cbs' => $this->getTable('cms_block_store')],
            'cb.block_id = cbs.block_id',
            []
        )->where(
            'cb.identifier = ?',
            $object->getData('identifier')
        )->where(
            'cbs.store_id IN (?)',
            $stores
        );

        if ($object->getId()) {
            $select->where('cb.block_id <> ?', $object->getId());
        }

        if ($this->getConnection()->fetchRow($select)) {
            return false;
        }

        return true;
    }
Exemple #5
0
 /**
  * Initialize product before saving
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  */
 public function initialize(\Magento\Catalog\Model\Product $product)
 {
     $productData = $this->request->getPost('product');
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : array();
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     foreach (array('category_ids', 'website_ids') as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = array();
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore()) {
         $product->setWebsiteIds(array($this->storeManager->getStore(true)->getWebsite()->getId()));
     }
     /**
      * Create Permanent Redirect for old URL key
      */
     if ($product->getId() && isset($productData['url_key_create_redirect'])) {
         $product->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = $this->request->getPost('use_default');
     if ($useDefaults) {
         foreach ($useDefaults as $attributeCode) {
             $product->setData($attributeCode, false);
         }
     }
     $links = $this->request->getPost('links');
     $links = is_array($links) ? $links : array();
     $linkTypes = array('related', 'upsell', 'crosssell');
     foreach ($linkTypes as $type) {
         if (isset($links[$type])) {
             $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]);
         }
     }
     $product = $this->productLinks->initializeLinks($product, $links);
     /**
      * Initialize product options
      */
     if (isset($productData['options']) && !$product->getOptionsReadonly()) {
         $product->setProductOptions($productData['options']);
     }
     $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly());
     return $product;
 }
 /**
  * @param \Magento\Catalog\Model\Product $product
  * @return void
  */
 private function assignProductToWebsites(\Magento\Catalog\Model\Product $product)
 {
     if (!$this->storeManager->hasSingleStore()) {
         if ($this->storeManager->getStore()->getCode() == \Magento\Store\Model\Store::ADMIN_CODE) {
             $websiteIds = array_keys($this->storeManager->getWebsites());
         } else {
             $websiteIds = [$this->storeManager->getStore()->getWebsiteId()];
         }
         $product->setWebsiteIds(array_unique(array_merge($product->getWebsiteIds(), $websiteIds)));
     }
 }
Exemple #7
0
 /**
  * Perform actions after object load
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return $this
  */
 protected function _afterLoad(AbstractModel $object)
 {
     $adapter = $this->_getReadAdapter();
     $select = $adapter->select()->from($this->_reviewStoreTable, ['store_id'])->where('review_id = :review_id');
     $stores = $adapter->fetchCol($select, [':review_id' => $object->getId()]);
     if (empty($stores) && $this->_storeManager->hasSingleStore()) {
         $object->setStores([$this->_storeManager->getStore(true)->getId()]);
     } else {
         $object->setStores($stores);
     }
     return $this;
 }
Exemple #8
0
 /**
  * @param \Magento\Framework\App\Request\Http $request
  * @param \Magento\Framework\Session\SidResolverInterface $sidResolver
  * @param \Magento\Framework\Session\Config\ConfigInterface $sessionConfig
  * @param \Magento\Framework\Session\SaveHandlerInterface $saveHandler
  * @param \Magento\Framework\Session\ValidatorInterface $validator
  * @param \Magento\Framework\Session\StorageInterface $storage
  * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
  * @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
  * @param \Magento\Framework\App\State $appState
  * @param CustomerRepositoryInterface $customerRepository
  * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
  * @param \Magento\Sales\Model\OrderFactory $orderFactory
  * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  * @param GroupManagementInterface $groupManagement
  * @throws \Magento\Framework\Exception\SessionException
  * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  */
 public function __construct(\Magento\Framework\App\Request\Http $request, \Magento\Framework\Session\SidResolverInterface $sidResolver, \Magento\Framework\Session\Config\ConfigInterface $sessionConfig, \Magento\Framework\Session\SaveHandlerInterface $saveHandler, \Magento\Framework\Session\ValidatorInterface $validator, \Magento\Framework\Session\StorageInterface $storage, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager, \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory, \Magento\Framework\App\State $appState, CustomerRepositoryInterface $customerRepository, \Magento\Quote\Model\QuoteRepository $quoteRepository, \Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, GroupManagementInterface $groupManagement)
 {
     $this->customerRepository = $customerRepository;
     $this->quoteRepository = $quoteRepository;
     $this->_orderFactory = $orderFactory;
     $this->_storeManager = $storeManager;
     $this->groupManagement = $groupManagement;
     parent::__construct($request, $sidResolver, $sessionConfig, $saveHandler, $validator, $storage, $cookieManager, $cookieMetadataFactory, $appState);
     if ($this->_storeManager->hasSingleStore()) {
         $this->setStoreId($this->_storeManager->getStore(true)->getId());
     }
 }
Exemple #9
0
 /**
  * @param \Magento\Framework\App\Request\Http $request
  * @param \Magento\Framework\Session\SidResolverInterface $sidResolver
  * @param \Magento\Framework\Session\Config\ConfigInterface $sessionConfig
  * @param \Magento\Framework\Session\SaveHandlerInterface $saveHandler
  * @param \Magento\Framework\Session\ValidatorInterface $validator
  * @param \Magento\Framework\Session\StorageInterface $storage
  * @param \Magento\Framework\Stdlib\CookieManager $cookieManager
  * @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
  * @param \Magento\Sales\Model\QuoteFactory $quoteFactory
  * @param \Magento\Customer\Service\V1\CustomerAccountServiceInterface $customerService
  * @param \Magento\Sales\Model\OrderFactory $orderFactory
  * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  */
 public function __construct(\Magento\Framework\App\Request\Http $request, \Magento\Framework\Session\SidResolverInterface $sidResolver, \Magento\Framework\Session\Config\ConfigInterface $sessionConfig, \Magento\Framework\Session\SaveHandlerInterface $saveHandler, \Magento\Framework\Session\ValidatorInterface $validator, \Magento\Framework\Session\StorageInterface $storage, \Magento\Framework\Stdlib\CookieManager $cookieManager, \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory, \Magento\Sales\Model\QuoteFactory $quoteFactory, \Magento\Customer\Service\V1\CustomerAccountServiceInterface $customerService, \Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
 {
     $this->_quoteFactory = $quoteFactory;
     $this->_customerService = $customerService;
     $this->_orderFactory = $orderFactory;
     $this->_storeManager = $storeManager;
     $this->_scopeConfig = $scopeConfig;
     parent::__construct($request, $sidResolver, $sessionConfig, $saveHandler, $validator, $storage, $cookieManager, $cookieMetadataFactory);
     $this->start();
     if ($this->_storeManager->hasSingleStore()) {
         $this->setStoreId($this->_storeManager->getStore(true)->getId());
     }
 }
Exemple #10
0
 /**
  * Retrieve processed template
  *
  * @param array $variables
  * @param bool $usePreprocess
  * @return string
  */
 public function getProcessedTemplate(array $variables = array(), $usePreprocess = false)
 {
     if (!$this->_preprocessFlag) {
         $variables['this'] = $this;
     }
     if ($this->_storeManager->hasSingleStore()) {
         $this->_filter->setStoreId($this->_storeManager->getStore()->getId());
     } else {
         $this->_filter->setStoreId($this->_request->getParam('store_id'));
     }
     $this->_filter->setIncludeProcessor(array($this, 'getInclude'))->setVariables($variables);
     if ($usePreprocess && $this->isPreprocessed()) {
         return $this->_filter->filter($this->getPreparedTemplateText(true));
     }
     return $this->_filter->filter($this->getPreparedTemplateText());
 }
Exemple #11
0
 /**
  * check if url key is unique
  *
  * @param AbstractModel|\Sample\News\Model\Author $object
  * @return bool
  */
 public function getIsUniqueAuthorToStores(AbstractModel $object)
 {
     if ($this->storeManager->hasSingleStore() || !$object->hasStores()) {
         $stores = [Store::DEFAULT_STORE_ID];
     } else {
         $stores = (array) $object->getData('stores');
     }
     $select = $this->getLoadByUrlKeySelect($object->getData('url_key'), $stores);
     if ($object->getId()) {
         $select->where('author_store.author_id <> ?', $object->getId());
     }
     if ($this->getConnection()->fetchRow($select)) {
         return false;
     }
     return true;
 }
Exemple #12
0
 /**
  * Check for unique of identifier of page to selected store(s).
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @return bool
  */
 public function getIsUniquePageToStores(\Magento\Framework\Model\AbstractModel $object)
 {
     if ($this->_storeManager->hasSingleStore() || !$object->hasStores()) {
         $stores = array(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     } else {
         $stores = (array) $object->getData('stores');
     }
     $select = $this->_getLoadByIdentifierSelect($object->getData('identifier'), $stores);
     if ($object->getId()) {
         $select->where('cps.page_id <> ?', $object->getId());
     }
     if ($this->_getWriteAdapter()->fetchRow($select)) {
         return false;
     }
     return true;
 }
Exemple #13
0
 /**
  * Check for unique of identifier of block to selected store(s).
  *
  * @param AbstractModel $object
  * @return bool
  * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  */
 public function getIsUniqueBlockToStores(AbstractModel $object)
 {
     $entityMetadata = $this->metadataPool->getMetadata(BlockInterface::class);
     $linkField = $entityMetadata->getLinkField();
     if ($this->_storeManager->hasSingleStore()) {
         $stores = [Store::DEFAULT_STORE_ID];
     } else {
         $stores = (array) $object->getData('stores');
     }
     $select = $this->getConnection()->select()->from(['cb' => $this->getMainTable()])->join(['cbs' => $this->getTable('cms_block_store')], 'cb.' . $linkField . ' = cbs.' . $linkField, [])->where('cb.identifier = ?', $object->getData('identifier'))->where('cbs.store_id IN (?)', $stores);
     if ($object->getId()) {
         $select->where('cb.' . $entityMetadata->getIdentifierField() . ' <> ?', $object->getId());
     }
     if ($this->getConnection()->fetchRow($select)) {
         return false;
     }
     return true;
 }
Exemple #14
0
 /**
  * Insert or Update attribute data
  *
  * @param \Magento\Catalog\Model\AbstractModel $object
  * @param AbstractAttribute $attribute
  * @param mixed $value
  * @return $this
  */
 protected function _saveAttributeValue($object, $attribute, $value)
 {
     $connection = $this->getConnection();
     $storeId = (int) $this->_storeManager->getStore($object->getStoreId())->getId();
     $table = $attribute->getBackend()->getTable();
     /**
      * If we work in single store mode all values should be saved just
      * for default store id
      * In this case we clear all not default values
      */
     $entityIdField = $this->getLinkField();
     if ($this->_storeManager->hasSingleStore()) {
         $storeId = $this->getDefaultStoreId();
         $connection->delete($table, ['attribute_id = ?' => $attribute->getAttributeId(), "{$entityIdField} = ?" => $object->getId(), 'store_id <> ?' => $storeId]);
     }
     $data = new \Magento\Framework\DataObject(['attribute_id' => $attribute->getAttributeId(), 'store_id' => $storeId, $entityIdField => $object->getId(), 'value' => $this->_prepareValueForSave($value, $attribute)]);
     $bind = $this->_prepareDataForTable($data, $table);
     if ($attribute->isScopeStore()) {
         /**
          * Update attribute value for store
          */
         $this->_attributeValuesToSave[$table][] = $bind;
     } elseif ($attribute->isScopeWebsite() && $storeId != $this->getDefaultStoreId()) {
         /**
          * Update attribute value for website
          */
         $storeIds = $this->_storeManager->getStore($storeId)->getWebsite()->getStoreIds(true);
         foreach ($storeIds as $storeId) {
             $bind['store_id'] = (int) $storeId;
             $this->_attributeValuesToSave[$table][] = $bind;
         }
     } else {
         /**
          * Update global attribute value
          */
         $bind['store_id'] = $this->getDefaultStoreId();
         $this->_attributeValuesToSave[$table][] = $bind;
     }
     return $this;
 }
Exemple #15
0
 /**
  * Initialize product from data
  *
  * @param \Magento\Catalog\Model\Product $product
  * @param array $productData
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function initializeFromData(\Magento\Catalog\Model\Product $product, array $productData)
 {
     unset($productData['custom_attributes']);
     unset($productData['extension_attributes']);
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : [];
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     $productData = $this->normalize($productData);
     if (!empty($productData['is_downloadable'])) {
         $productData['product_has_weight'] = 0;
     }
     foreach (['category_ids', 'website_ids'] as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = [];
         }
     }
     foreach ($productData['website_ids'] as $websiteId => $checkboxValue) {
         if (!$checkboxValue) {
             unset($productData['website_ids'][$websiteId]);
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $dateFieldFilters = [];
     $attributes = $product->getAttributes();
     foreach ($attributes as $attrKey => $attribute) {
         if ($attribute->getBackend()->getType() == 'datetime') {
             if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') {
                 $dateFieldFilters[$attrKey] = $this->getDateTimeFilter();
             }
         }
     }
     $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData);
     $productData = $inputFilter->getUnescaped();
     if (isset($productData['options'])) {
         $productOptions = $productData['options'];
         unset($productData['options']);
     } else {
         $productOptions = [];
     }
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore() && empty($product->getWebsiteIds())) {
         $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = (array) $this->request->getPost('use_default', []);
     foreach ($useDefaults as $attributeCode => $useDefaultState) {
         if ($useDefaultState) {
             $product->setData($attributeCode, null);
         }
     }
     $product = $this->setProductLinks($product);
     /**
      * Initialize product options
      */
     if ($productOptions && !$product->getOptionsReadonly()) {
         // mark custom options that should to fall back to default value
         $options = $this->mergeProductOptions($productOptions, $this->request->getPost('options_use_default'));
         $customOptions = [];
         foreach ($options as $customOptionData) {
             if (empty($customOptionData['is_delete'])) {
                 if (isset($customOptionData['values'])) {
                     $customOptionData['values'] = array_filter($customOptionData['values'], function ($valueData) {
                         return empty($valueData['is_delete']);
                     });
                 }
                 $customOption = $this->getCustomOptionFactory()->create(['data' => $customOptionData]);
                 $customOption->setProductSku($product->getSku());
                 $customOption->setOptionId(null);
                 $customOptions[] = $customOption;
             }
         }
         $product->setOptions($customOptions);
     }
     $product->setCanSaveCustomOptions(!empty($productData['affect_product_custom_options']) && !$product->getOptionsReadonly());
     return $product;
 }
Exemple #16
0
 /**
  * Initialize product before saving
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function initialize(\Magento\Catalog\Model\Product $product)
 {
     $productData = $this->request->getPost('product');
     unset($productData['custom_attributes']);
     unset($productData['extension_attributes']);
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : [];
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     foreach (['category_ids', 'website_ids'] as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = [];
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $dateFieldFilters = [];
     $attributes = $product->getAttributes();
     foreach ($attributes as $attrKey => $attribute) {
         if ($attribute->getBackend()->getType() == 'datetime') {
             if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') {
                 $dateFieldFilters[$attrKey] = $this->dateFilter;
             }
         }
     }
     $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData);
     $productData = $inputFilter->getUnescaped();
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore()) {
         $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = $this->request->getPost('use_default');
     if ($useDefaults) {
         foreach ($useDefaults as $attributeCode) {
             $product->setData($attributeCode, false);
         }
     }
     $links = $this->request->getPost('links');
     $links = is_array($links) ? $links : [];
     $linkTypes = ['related', 'upsell', 'crosssell'];
     foreach ($linkTypes as $type) {
         if (isset($links[$type])) {
             $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]);
         }
     }
     $product = $this->productLinks->initializeLinks($product, $links);
     $productLinks = $product->getProductLinks();
     $linkTypes = ['related' => $product->getRelatedReadonly(), 'upsell' => $product->getUpsellReadonly(), 'crosssell' => $product->getCrosssellReadonly()];
     foreach ($linkTypes as $linkType => $readonly) {
         if (isset($links[$linkType]) && !$readonly) {
             foreach ($links[$linkType] as $linkId => $linkData) {
                 $linkProduct = $this->productRepository->getById($linkId);
                 $link = $this->productLinkFactory->create();
                 $link->setSku($product->getSku())->setLinkedProductSku($linkProduct->getSku())->setLinkType($linkType)->setPosition(isset($linkData['position']) ? (int) $linkData['position'] : 0);
                 $productLinks[] = $link;
             }
         }
     }
     $product->setProductLinks($productLinks);
     /**
      * Initialize product options
      */
     if (isset($productData['options']) && !$product->getOptionsReadonly()) {
         // mark custom options that should to fall back to default value
         $options = $this->mergeProductOptions($productData['options'], $this->request->getPost('options_use_default'));
         $customOptions = [];
         foreach ($options as $customOptionData) {
             if (!(bool) $customOptionData['is_delete']) {
                 $customOption = $this->customOptionFactory->create(['data' => $customOptionData]);
                 $customOption->setProductSku($product->getSku());
                 $customOption->setOptionId(null);
                 $customOptions[] = $customOption;
             }
         }
         $product->setOptions($customOptions);
     }
     $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly());
     return $product;
 }