PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php

https://github.com/FiveDigital/magento2
PHP | 837 lines | 554 code | 103 blank | 180 comment | 102 complexity | b848b5143fc28a8af6621b7962709b39 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@magentocommerce.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Catalog
  23. * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. class Mage_Catalog_Model_Convert_Adapter_Product
  27. extends Mage_Eav_Model_Convert_Adapter_Entity
  28. {
  29. const MULTI_DELIMITER = ' , ';
  30. const ENTITY = 'catalog_product_import';
  31. /**
  32. * Event prefix
  33. *
  34. * @var string
  35. */
  36. protected $_eventPrefix = 'catalog_product_import';
  37. /**
  38. * Product model
  39. *
  40. * @var Mage_Catalog_Model_Product
  41. */
  42. protected $_productModel;
  43. /**
  44. * product types collection array
  45. *
  46. * @var array
  47. */
  48. protected $_productTypes;
  49. /**
  50. * Product Type Instances singletons
  51. *
  52. * @var array
  53. */
  54. protected $_productTypeInstances = array();
  55. /**
  56. * product attribute set collection array
  57. *
  58. * @var array
  59. */
  60. protected $_productAttributeSets;
  61. protected $_stores;
  62. protected $_attributes = array();
  63. protected $_configs = array();
  64. protected $_requiredFields = array();
  65. protected $_ignoreFields = array();
  66. /**
  67. * Inventory Fields array
  68. *
  69. * @var array
  70. */
  71. protected $_inventoryFields = array();
  72. /**
  73. * Inventory Fields by product Types
  74. *
  75. * @var array
  76. */
  77. protected $_inventoryFieldsProductTypes = array();
  78. protected $_toNumber = array();
  79. /**
  80. * Retrieve event prefix for adapter
  81. *
  82. * @return string
  83. */
  84. public function getEventPrefix()
  85. {
  86. return $this->_eventPrefix;
  87. }
  88. /**
  89. * Affected entity ids
  90. *
  91. * @var array
  92. */
  93. protected $_affectedEntityIds = array();
  94. /**
  95. * Store affected entity ids
  96. *
  97. * @param int|array $ids
  98. * @return Mage_Catalog_Model_Convert_Adapter_Product
  99. */
  100. protected function _addAffectedEntityIds($ids)
  101. {
  102. if (is_array($ids)) {
  103. foreach ($ids as $id) {
  104. $this->_addAffectedEntityIds($id);
  105. }
  106. } else {
  107. $this->_affectedEntityIds[] = $ids;
  108. }
  109. return $this;
  110. }
  111. /**
  112. * Retrieve affected entity ids
  113. *
  114. * @return array
  115. */
  116. public function getAffectedEntityIds()
  117. {
  118. return $this->_affectedEntityIds;
  119. }
  120. /**
  121. * Clear affected entity ids results
  122. *
  123. * @return Mage_Catalog_Model_Convert_Adapter_Product
  124. */
  125. public function clearAffectedEntityIds()
  126. {
  127. $this->_affectedEntityIds = array();
  128. return $this;
  129. }
  130. /**
  131. * Load product collection Id(s)
  132. */
  133. public function load()
  134. {
  135. $attrFilterArray = array();
  136. $attrFilterArray ['name'] = 'like';
  137. $attrFilterArray ['sku'] = 'startsWith';
  138. $attrFilterArray ['type'] = 'eq';
  139. $attrFilterArray ['attribute_set'] = 'eq';
  140. $attrFilterArray ['visibility'] = 'eq';
  141. $attrFilterArray ['status'] = 'eq';
  142. $attrFilterArray ['price'] = 'fromTo';
  143. $attrFilterArray ['qty'] = 'fromTo';
  144. $attrFilterArray ['store_id'] = 'eq';
  145. $attrToDb = array(
  146. 'type' => 'type_id',
  147. 'attribute_set' => 'attribute_set_id'
  148. );
  149. $filters = $this->_parseVars();
  150. if ($qty = $this->getFieldValue($filters, 'qty')) {
  151. $qtyFrom = isset($qty['from']) ? (float) $qty['from'] : 0;
  152. $qtyTo = isset($qty['to']) ? (float) $qty['to'] : 0;
  153. $qtyAttr = array();
  154. $qtyAttr['alias'] = 'qty';
  155. $qtyAttr['attribute'] = 'cataloginventory_stock_item';
  156. $qtyAttr['field'] = 'qty';
  157. $qtyAttr['bind'] = 'product_id=entity_id';
  158. $qtyAttr['cond'] = "{{table}}.qty between '{$qtyFrom}' AND '{$qtyTo}'";
  159. $qtyAttr['joinType'] = 'inner';
  160. $this->setJoinField($qtyAttr);
  161. }
  162. parent::setFilter($attrFilterArray, $attrToDb);
  163. if ($price = $this->getFieldValue($filters, 'price')) {
  164. $this->_filter[] = array(
  165. 'attribute' => 'price',
  166. 'from' => $price['from'],
  167. 'to' => $price['to']
  168. );
  169. $this->setJoinAttr(array(
  170. 'alias' => 'price',
  171. 'attribute' => 'catalog_product/price',
  172. 'bind' => 'entity_id',
  173. 'joinType' => 'LEFT'
  174. ));
  175. }
  176. return parent::load();
  177. }
  178. /**
  179. * Retrieve product model cache
  180. *
  181. * @return Mage_Catalog_Model_Product
  182. */
  183. public function getProductModel()
  184. {
  185. if (is_null($this->_productModel)) {
  186. $productModel = Mage::getModel('Mage_Catalog_Model_Product');
  187. $this->_productModel = Mage::objects()->save($productModel);
  188. }
  189. return Mage::objects()->load($this->_productModel);
  190. }
  191. /**
  192. * Retrieve eav entity attribute model
  193. *
  194. * @param string $code
  195. * @return Mage_Eav_Model_Entity_Attribute
  196. */
  197. public function getAttribute($code)
  198. {
  199. if (!isset($this->_attributes[$code])) {
  200. $this->_attributes[$code] = $this->getProductModel()->getResource()->getAttribute($code);
  201. }
  202. if ($this->_attributes[$code] instanceof Mage_Catalog_Model_Resource_Eav_Attribute) {
  203. $applyTo = $this->_attributes[$code]->getApplyTo();
  204. if ($applyTo && !in_array($this->getProductModel()->getTypeId(), $applyTo)) {
  205. return false;
  206. }
  207. }
  208. return $this->_attributes[$code];
  209. }
  210. /**
  211. * Retrieve product type collection array
  212. *
  213. * @return array
  214. */
  215. public function getProductTypes()
  216. {
  217. if (is_null($this->_productTypes)) {
  218. $this->_productTypes = array();
  219. $options = Mage::getModel('Mage_Catalog_Model_Product_Type')
  220. ->getOptionArray();
  221. foreach ($options as $k => $v) {
  222. $this->_productTypes[$k] = $k;
  223. }
  224. }
  225. return $this->_productTypes;
  226. }
  227. /**
  228. * ReDefine Product Type Instance to Product
  229. *
  230. * @param Mage_Catalog_Model_Product $product
  231. * @return Mage_Catalog_Model_Convert_Adapter_Product
  232. */
  233. public function setProductTypeInstance(Mage_Catalog_Model_Product $product)
  234. {
  235. $type = $product->getTypeId();
  236. if (!isset($this->_productTypeInstances[$type])) {
  237. $this->_productTypeInstances[$type] = Mage::getSingleton('Mage_Catalog_Model_Product_Type')
  238. ->factory($product);
  239. }
  240. $product->setTypeInstance($this->_productTypeInstances[$type]);
  241. return $this;
  242. }
  243. /**
  244. * Retrieve product attribute set collection array
  245. *
  246. * @return array
  247. */
  248. public function getProductAttributeSets()
  249. {
  250. if (is_null($this->_productAttributeSets)) {
  251. $this->_productAttributeSets = array();
  252. $entityTypeId = Mage::getModel('Mage_Eav_Model_Entity')
  253. ->setType('catalog_product')
  254. ->getTypeId();
  255. $collection = Mage::getResourceModel('Mage_Eav_Model_Resource_Entity_Attribute_Set_Collection')
  256. ->setEntityTypeFilter($entityTypeId);
  257. foreach ($collection as $set) {
  258. $this->_productAttributeSets[$set->getAttributeSetName()] = $set->getId();
  259. }
  260. }
  261. return $this->_productAttributeSets;
  262. }
  263. /**
  264. * Init stores
  265. */
  266. protected function _initStores ()
  267. {
  268. if (is_null($this->_stores)) {
  269. $this->_stores = Mage::app()->getStores(true, true);
  270. foreach ($this->_stores as $code => $store) {
  271. $this->_storesIdCode[$store->getId()] = $code;
  272. }
  273. }
  274. }
  275. /**
  276. * Retrieve store object by code
  277. *
  278. * @param string $store
  279. * @return Mage_Core_Model_Store
  280. */
  281. public function getStoreByCode($store)
  282. {
  283. $this->_initStores();
  284. /**
  285. * In single store mode all data should be saved as default
  286. */
  287. if (Mage::app()->hasSingleStore()) {
  288. return Mage::app()->getStore(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
  289. }
  290. if (isset($this->_stores[$store])) {
  291. return $this->_stores[$store];
  292. }
  293. return false;
  294. }
  295. /**
  296. * Retrieve store object by code
  297. *
  298. * @param string $store
  299. * @return Mage_Core_Model_Store
  300. */
  301. public function getStoreById($id)
  302. {
  303. $this->_initStores();
  304. /**
  305. * In single store mode all data should be saved as default
  306. */
  307. if (Mage::app()->hasSingleStore()) {
  308. return Mage::app()->getStore(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
  309. }
  310. if (isset($this->_storesIdCode[$id])) {
  311. return $this->getStoreByCode($this->_storesIdCode[$id]);
  312. }
  313. return false;
  314. }
  315. public function parse()
  316. {
  317. $batchModel = Mage::getSingleton('Mage_Dataflow_Model_Batch');
  318. /* @var $batchModel Mage_Dataflow_Model_Batch */
  319. $batchImportModel = $batchModel->getBatchImportModel();
  320. $importIds = $batchImportModel->getIdCollection();
  321. foreach ($importIds as $importId) {
  322. //print '<pre>'.memory_get_usage().'</pre>';
  323. $batchImportModel->load($importId);
  324. $importData = $batchImportModel->getBatchData();
  325. $this->saveRow($importData);
  326. }
  327. }
  328. protected $_productId = '';
  329. /**
  330. * Initialize convert adapter model for products collection
  331. *
  332. */
  333. public function __construct()
  334. {
  335. $fieldset = Mage::getConfig()->getFieldset('catalog_product_dataflow', 'admin');
  336. foreach ($fieldset as $code => $node) {
  337. /* @var $node Mage_Core_Model_Config_Element */
  338. if ($node->is('inventory')) {
  339. foreach ($node->product_type->children() as $productType) {
  340. $productType = $productType->getName();
  341. $this->_inventoryFieldsProductTypes[$productType][] = $code;
  342. if ($node->is('use_config')) {
  343. $this->_inventoryFieldsProductTypes[$productType][] = 'use_config_' . $code;
  344. }
  345. }
  346. $this->_inventoryFields[] = $code;
  347. if ($node->is('use_config')) {
  348. $this->_inventoryFields[] = 'use_config_'.$code;
  349. }
  350. }
  351. if ($node->is('required')) {
  352. $this->_requiredFields[] = $code;
  353. }
  354. if ($node->is('ignore')) {
  355. $this->_ignoreFields[] = $code;
  356. }
  357. if ($node->is('to_number')) {
  358. $this->_toNumber[] = $code;
  359. }
  360. }
  361. $this->setVar('entity_type', 'catalog/product')
  362. ->setVar('entity_resource', 'Mage_Catalog_Model_Resource_Product');
  363. if (!Mage::registry('Object_Cache_Product')) {
  364. $this->setProduct(Mage::getModel('Mage_Catalog_Model_Product'));
  365. }
  366. if (!Mage::registry('Object_Cache_StockItem')) {
  367. $this->setStockItem(Mage::getModel('Mage_CatalogInventory_Model_Stock_Item'));
  368. }
  369. }
  370. /**
  371. * Retrieve not loaded collection
  372. *
  373. * @param string $entityResource
  374. * @return Mage_Catalog_Model_Resource_Product_Collection
  375. */
  376. protected function _getCollectionForLoad($entityResource)
  377. {
  378. $collection = parent::_getCollectionForLoad($entityResource)
  379. ->setStoreId($this->getStoreId())
  380. ->addStoreFilter($this->getStoreId());
  381. return $collection;
  382. }
  383. public function setProduct(Mage_Catalog_Model_Product $object)
  384. {
  385. $id = Mage::objects()->save($object);
  386. //$this->_product = $object;
  387. Mage::register('Object_Cache_Product', $id);
  388. }
  389. public function getProduct()
  390. {
  391. return Mage::objects()->load(Mage::registry('Object_Cache_Product'));
  392. }
  393. public function setStockItem(Mage_CatalogInventory_Model_Stock_Item $object)
  394. {
  395. $id = Mage::objects()->save($object);
  396. Mage::register('Object_Cache_StockItem', $id);
  397. }
  398. public function getStockItem()
  399. {
  400. return Mage::objects()->load(Mage::registry('Object_Cache_StockItem'));
  401. }
  402. public function save()
  403. {
  404. $stores = array();
  405. foreach (Mage::getConfig()->getNode('stores')->children() as $storeNode) {
  406. $stores[(int)$storeNode->system->store->id] = $storeNode->getName();
  407. }
  408. $collections = $this->getData();
  409. if ($collections instanceof Mage_Catalog_Model_Entity_Product_Collection) {
  410. $collections = array($collections->getEntity()->getStoreId()=>$collections);
  411. } elseif (!is_array($collections)) {
  412. $this->addException(
  413. Mage::helper('Mage_Catalog_Helper_Data')->__('No product collections found.'),
  414. Mage_Dataflow_Model_Convert_Exception::FATAL
  415. );
  416. }
  417. $stockItems = Mage::registry('current_imported_inventory');
  418. if ($collections) foreach ($collections as $storeId=>$collection) {
  419. $this->addException(Mage::helper('Mage_Catalog_Helper_Data')->__('Records for "%s" store found.', $stores[$storeId]));
  420. if (!$collection instanceof Mage_Catalog_Model_Entity_Product_Collection) {
  421. $this->addException(
  422. Mage::helper('Mage_Catalog_Helper_Data')->__('Product collection expected.'),
  423. Mage_Dataflow_Model_Convert_Exception::FATAL
  424. );
  425. }
  426. try {
  427. $i = 0;
  428. foreach ($collection->getIterator() as $model) {
  429. $new = false;
  430. // if product is new, create default values first
  431. if (!$model->getId()) {
  432. $new = true;
  433. $model->save();
  434. // if new product and then store is not default
  435. // we duplicate product as default product with store_id -
  436. if (0 !== $storeId ) {
  437. $data = $model->getData();
  438. $default = Mage::getModel('Mage_Catalog_Model_Product');
  439. $default->setData($data);
  440. $default->setStoreId(0);
  441. $default->save();
  442. unset($default);
  443. } // end
  444. }
  445. if (!$new || 0!==$storeId) {
  446. if (0!==$storeId) {
  447. Mage::getResourceSingleton('Mage_Catalog_Model_Resource_Convert')->addProductToStore(
  448. $model->getId(),
  449. $storeId
  450. );
  451. }
  452. $model->save();
  453. }
  454. if (isset($stockItems[$model->getSku()]) && $stock = $stockItems[$model->getSku()]) {
  455. $stockItem = Mage::getModel('Mage_CatalogInventory_Model_Stock_Item')->loadByProduct($model->getId());
  456. $stockItemId = $stockItem->getId();
  457. if (!$stockItemId) {
  458. $stockItem->setData('product_id', $model->getId());
  459. $stockItem->setData('stock_id', 1);
  460. $data = array();
  461. } else {
  462. $data = $stockItem->getData();
  463. }
  464. foreach($stock as $field => $value) {
  465. if (!$stockItemId) {
  466. if (in_array($field, $this->_configs)) {
  467. $stockItem->setData('use_config_'.$field, 0);
  468. }
  469. $stockItem->setData($field, $value?$value:0);
  470. } else {
  471. if (in_array($field, $this->_configs)) {
  472. if ($data['use_config_'.$field] == 0) {
  473. $stockItem->setData($field, $value?$value:0);
  474. }
  475. } else {
  476. $stockItem->setData($field, $value?$value:0);
  477. }
  478. }
  479. }
  480. $stockItem->save();
  481. unset($data);
  482. unset($stockItem);
  483. unset($stockItemId);
  484. }
  485. unset($model);
  486. $i++;
  487. }
  488. $this->addException(Mage::helper('Mage_Catalog_Helper_Data')->__("Saved %d record(s)", $i));
  489. } catch (Exception $e) {
  490. if (!$e instanceof Mage_Dataflow_Model_Convert_Exception) {
  491. $this->addException(
  492. Mage::helper('Mage_Catalog_Helper_Data')->__('An error occurred while saving the collection, aborting. Error message: %s', $e->getMessage()),
  493. Mage_Dataflow_Model_Convert_Exception::FATAL
  494. );
  495. }
  496. }
  497. }
  498. unset($collections);
  499. return $this;
  500. }
  501. /**
  502. * Save product (import)
  503. *
  504. * @param array $importData
  505. * @throws Mage_Core_Exception
  506. * @return bool
  507. */
  508. public function saveRow(array $importData)
  509. {
  510. $product = $this->getProductModel()
  511. ->reset();
  512. if (empty($importData['store'])) {
  513. if (!is_null($this->getBatchParams('store'))) {
  514. $store = $this->getStoreById($this->getBatchParams('store'));
  515. } else {
  516. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skipping import row, required field "%s" is not defined.', 'store');
  517. Mage::throwException($message);
  518. }
  519. } else {
  520. $store = $this->getStoreByCode($importData['store']);
  521. }
  522. if ($store === false) {
  523. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
  524. Mage::throwException($message);
  525. }
  526. if (empty($importData['sku'])) {
  527. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skipping import row, required field "%s" is not defined.', 'sku');
  528. Mage::throwException($message);
  529. }
  530. $product->setStoreId($store->getId());
  531. $productId = $product->getIdBySku($importData['sku']);
  532. if ($productId) {
  533. $product->load($productId);
  534. } else {
  535. $productTypes = $this->getProductTypes();
  536. $productAttributeSets = $this->getProductAttributeSets();
  537. /**
  538. * Check product define type
  539. */
  540. if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
  541. $value = isset($importData['type']) ? $importData['type'] : '';
  542. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
  543. Mage::throwException($message);
  544. }
  545. $product->setTypeId($productTypes[strtolower($importData['type'])]);
  546. /**
  547. * Check product define attribute set
  548. */
  549. if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
  550. $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
  551. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
  552. Mage::throwException($message);
  553. }
  554. $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
  555. foreach ($this->_requiredFields as $field) {
  556. $attribute = $this->getAttribute($field);
  557. if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
  558. $message = Mage::helper('Mage_Catalog_Helper_Data')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
  559. Mage::throwException($message);
  560. }
  561. }
  562. }
  563. $this->setProductTypeInstance($product);
  564. if (isset($importData['category_ids'])) {
  565. $product->setCategoryIds($importData['category_ids']);
  566. }
  567. foreach ($this->_ignoreFields as $field) {
  568. if (isset($importData[$field])) {
  569. unset($importData[$field]);
  570. }
  571. }
  572. if ($store->getId() != 0) {
  573. $websiteIds = $product->getWebsiteIds();
  574. if (!is_array($websiteIds)) {
  575. $websiteIds = array();
  576. }
  577. if (!in_array($store->getWebsiteId(), $websiteIds)) {
  578. $websiteIds[] = $store->getWebsiteId();
  579. }
  580. $product->setWebsiteIds($websiteIds);
  581. }
  582. if (isset($importData['websites'])) {
  583. $websiteIds = $product->getWebsiteIds();
  584. if (!is_array($websiteIds) || !$store->getId()) {
  585. $websiteIds = array();
  586. }
  587. $websiteCodes = explode(',', $importData['websites']);
  588. foreach ($websiteCodes as $websiteCode) {
  589. try {
  590. $website = Mage::app()->getWebsite(trim($websiteCode));
  591. if (!in_array($website->getId(), $websiteIds)) {
  592. $websiteIds[] = $website->getId();
  593. }
  594. } catch (Exception $e) {}
  595. }
  596. $product->setWebsiteIds($websiteIds);
  597. unset($websiteIds);
  598. }
  599. foreach ($importData as $field => $value) {
  600. if (in_array($field, $this->_inventoryFields)) {
  601. continue;
  602. }
  603. if (is_null($value)) {
  604. continue;
  605. }
  606. $attribute = $this->getAttribute($field);
  607. if (!$attribute) {
  608. continue;
  609. }
  610. $isArray = false;
  611. $setValue = $value;
  612. if ($attribute->getFrontendInput() == 'multiselect') {
  613. $value = explode(self::MULTI_DELIMITER, $value);
  614. $isArray = true;
  615. $setValue = array();
  616. }
  617. if ($value && $attribute->getBackendType() == 'decimal') {
  618. $setValue = $this->getNumber($value);
  619. }
  620. if ($attribute->usesSource()) {
  621. $options = $attribute->getSource()->getAllOptions(false);
  622. if ($isArray) {
  623. foreach ($options as $item) {
  624. if (in_array($item['label'], $value)) {
  625. $setValue[] = $item['value'];
  626. }
  627. }
  628. } else {
  629. $setValue = false;
  630. foreach ($options as $item) {
  631. if (is_array($item['value'])) {
  632. foreach ($item['value'] as $subValue) {
  633. if (isset($subValue['value']) && $subValue['value'] == $value) {
  634. $setValue = $value;
  635. }
  636. }
  637. } else if ($item['label'] == $value) {
  638. $setValue = $item['value'];
  639. }
  640. }
  641. }
  642. }
  643. $product->setData($field, $setValue);
  644. }
  645. if (!$product->getVisibility()) {
  646. $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
  647. }
  648. $stockData = array();
  649. $inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
  650. ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
  651. : array();
  652. foreach ($inventoryFields as $field) {
  653. if (isset($importData[$field])) {
  654. if (in_array($field, $this->_toNumber)) {
  655. $stockData[$field] = $this->getNumber($importData[$field]);
  656. } else {
  657. $stockData[$field] = $importData[$field];
  658. }
  659. }
  660. }
  661. $product->setStockData($stockData);
  662. $mediaGalleryBackendModel = $this->getAttribute('media_gallery')->getBackend();
  663. $arrayToMassAdd = array();
  664. foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
  665. if (isset($importData[$mediaAttributeCode])) {
  666. $file = trim($importData[$mediaAttributeCode]);
  667. if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
  668. $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
  669. }
  670. }
  671. }
  672. $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
  673. $product,
  674. $arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import',
  675. false,
  676. false
  677. );
  678. foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
  679. $addedFile = '';
  680. if (isset($importData[$mediaAttributeCode . '_label'])) {
  681. $fileLabel = trim($importData[$mediaAttributeCode . '_label']);
  682. if (isset($importData[$mediaAttributeCode])) {
  683. $keyInAddedFile = array_search($importData[$mediaAttributeCode],
  684. $addedFilesCorrespondence['alreadyAddedFiles']);
  685. if ($keyInAddedFile !== false) {
  686. $addedFile = $addedFilesCorrespondence['alreadyAddedFilesNames'][$keyInAddedFile];
  687. }
  688. }
  689. if (!$addedFile) {
  690. $addedFile = $product->getData($mediaAttributeCode);
  691. }
  692. if ($fileLabel && $addedFile) {
  693. $mediaGalleryBackendModel->updateImage($product, $addedFile, array('label' => $fileLabel));
  694. }
  695. }
  696. }
  697. $product->setIsMassupdate(true);
  698. $product->setExcludeUrlRewrite(true);
  699. $product->save();
  700. // Store affected products ids
  701. $this->_addAffectedEntityIds($product->getId());
  702. return true;
  703. }
  704. /**
  705. * Silently save product (import)
  706. *
  707. * @param array $importData
  708. * @return bool
  709. */
  710. public function saveRowSilently(array $importData)
  711. {
  712. try {
  713. $result = $this->saveRow($importData);
  714. return $result;
  715. } catch (Exception $e) {
  716. return false;
  717. }
  718. }
  719. /**
  720. * Process after import data
  721. * Init indexing process after catalog product import
  722. */
  723. public function finish()
  724. {
  725. /**
  726. * Back compatibility event
  727. */
  728. Mage::dispatchEvent($this->_eventPrefix . '_after', array());
  729. $entity = new Varien_Object();
  730. Mage::getSingleton('Mage_Index_Model_Indexer')->processEntityAction(
  731. $entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
  732. );
  733. }
  734. }