PageRenderTime 121ms CodeModel.GetById 24ms RepoModel.GetById 3ms app.codeStats 0ms

/app/code/community/ZetaPrints/WebToPrint/Model/Convert/Mapper/Product/Creating.php

http://magento-w2p.googlecode.com/
PHP | 338 lines | 233 code | 86 blank | 19 comment | 29 complexity | 419502356b0a2cb384eccc37f77a1cbd MD5 | raw file
  1. <?php
  2. class ZetaPrints_WebToPrint_Model_Convert_Mapper_Product_Creating
  3. extends Mage_Dataflow_Model_Convert_Mapper_Abstract
  4. implements ZetaPrints_Api {
  5. protected $_new_products_category_id;
  6. public function map () {
  7. //Always print debug information. Issue #80
  8. $this->debug = true;
  9. $this->warning('Product type: ' .
  10. $this->getAction()->getParam('product-type', 'simple') );
  11. if (!$assignToWebsites = $this->_getWebsitesForAssign())
  12. return;
  13. //Get all web-to-print templates
  14. $templates = Mage::getModel('webtoprint/template')->getCollection()->load();
  15. //Get all products
  16. $products = Mage::getModel('catalog/product')
  17. ->getCollection()
  18. ->addAttributeToSelect('webtoprint_template')
  19. ->load();
  20. //If there're products then...
  21. if ($has_products = (bool) count($products)) {
  22. //... create array to store used web-to-print template GUIDs
  23. $used_templates = array();
  24. //For every product...
  25. foreach($products as $product) {
  26. //... remember its ID
  27. $used_templates[$product->getId()] = null;
  28. //And if it has web-to-print attribute set then...
  29. if($product->hasWebtoprintTemplate() && $product->getWebtoprintTemplate())
  30. //... also remember the value of the attribute
  31. $used_templates[$product->getWebtoprintTemplate()] = null;
  32. }
  33. }
  34. unset($products);
  35. // Get ID of source product if present and try to load source product
  36. $sourceId = $this->getAction()->getParam('source-product-id');
  37. $sourceProduct = null;
  38. if($sourceId) {
  39. $sourceProduct = Mage::getModel('catalog/product')->load($sourceId);
  40. if($sourceProduct->getId()) {
  41. $this->warning('Base product: ' . $sourceProduct->getName());
  42. $sourceProduct->getCategoryIds();
  43. $sourceProduct->setId(null);
  44. $sourceData = $sourceProduct->getData();
  45. $sourceData['stock_item'] = null;
  46. $sourceData['url_key'] = null;
  47. }
  48. else
  49. $sourceProduct = null;
  50. }
  51. $url = Mage::getStoreConfig('webtoprint/settings/url');
  52. $key = Mage::getStoreConfig('webtoprint/settings/key');
  53. $_catalogues = zetaprints_get_list_of_catalogs($url, $key);
  54. $cataloguesMapping = array();
  55. foreach ($_catalogues as $_catalogue)
  56. $cataloguesMapping[$_catalogue['guid']] = $_catalogue['title'];
  57. $_catalogues = array();
  58. $categoryMappingStore = $this
  59. ->getAction()
  60. ->getParam('category-mapping-store');
  61. $categoryMappingStore = Mage::app()->getStore($categoryMappingStore);
  62. $assignToParents = (bool) $this
  63. ->getAction()
  64. ->getParam('assign-to-parents');
  65. if (!$categoryMappingStore->getId())
  66. $categoryMappingStore = null;
  67. $useProductPopulateDefaults
  68. = Mage::getStoreConfig('webtoprint/settings/products-populate-defaults');
  69. $_defaultCategory = array();
  70. $helper = Mage::helper('webtoprint/category');
  71. $line = 0;
  72. $number_of_templates = count($templates);
  73. $number_of_created_products = 0;
  74. foreach ($templates as $template) {
  75. $line++;
  76. if ($has_products)
  77. if (array_key_exists($template->getGuid(), $used_templates)) {
  78. $this->debug("{$line}. Product {$template->getGuid()} already exists");
  79. continue;
  80. }
  81. if (!$sourceProduct) {
  82. $product_model = Mage::getModel('catalog/product');
  83. $product_model
  84. ->setWebsiteIds($assignToWebsites)
  85. ->setAttributeSetId($product_model->getDefaultAttributeSetId())
  86. ->setTypeId($this->getAction()->getParam('product-type', 'simple'))
  87. ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_DISABLED)
  88. ->setVisibility(0);
  89. if ($useProductPopulateDefaults) {
  90. $product_model
  91. ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
  92. ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
  93. ->setWeight(0)
  94. ->setPrice(0)
  95. ->setTaxClassId(0);
  96. }
  97. $templateDetails = zetaprints_parse_template_details(
  98. new SimpleXMLElement($template->getXml())
  99. );
  100. $templateDetails['catalogue']
  101. = $cataloguesMapping[$template->getCatalogGuid()];
  102. $categoryIds = $helper->getCategoriesIds(
  103. $templateDetails,
  104. $assignToParents,
  105. $categoryMappingStore
  106. );
  107. if (!$categoryIds && $useProductPopulateDefaults)
  108. $categoryIds = $this->_getDefaultCategoryId();
  109. $product_model->setCategoryIds($categoryIds);
  110. } else {
  111. $product_model = $sourceProduct;
  112. $product_model
  113. ->setOrigData()
  114. ->setData($sourceData);
  115. }
  116. $product_model
  117. ->setSku(zetaprints_generate_guid() . '-rename-me')
  118. ->setName($template->getTitle())
  119. ->setDescription($template->getDescription())
  120. ->setShortDescription($template->getDescription())
  121. ->setRequiredOptions(true)
  122. ->setWebtoprintTemplate($template->getGuid());
  123. Mage::dispatchEvent(
  124. 'webtoprint_product_create',
  125. array(
  126. 'product' => $product_model,
  127. 'template' => $templateDetails,
  128. 'params' => array(
  129. 'process-quantities' => $this->_isProcessQuantities()
  130. )
  131. )
  132. );
  133. try {
  134. $product_model->save();
  135. } catch (Exception $e) {
  136. $this->error("{$line}. Error creating product from template: {$template->getGuid()}");
  137. $this->error($e->getMessage());
  138. continue;
  139. }
  140. $stock_item = Mage::getModel('cataloginventory/stock_item');
  141. $stock_item->setStockId(1)
  142. ->setUseConfigManageStock(0)
  143. ->setProduct($product_model)
  144. ->save();
  145. $this->debug("{$line}. Product for template {$template->getGuid()} was created.");
  146. $number_of_created_products++;
  147. unset($product_model);
  148. unset($stock_item);
  149. }
  150. $this->notice("Number of templates: {$number_of_templates}");
  151. $this->notice("Number of created products: {$number_of_created_products}");
  152. $this->warning('Warning: products were created with general set of properties. Update other product properties using bulk edit to make them operational.');
  153. }
  154. /**
  155. * Try to get category ID by category name
  156. *
  157. * If category exists return its ID, if not try to create it.
  158. * Only create category if there is one root category in the store.
  159. *
  160. * @param string $name
  161. * @return null|int
  162. */
  163. protected function _getDefaultCategoryId () {
  164. if (!isset($this->_defaultCategory))
  165. $this->_defaultCategory = $this->_createDefaultCategory();
  166. return $this->_defaultCategory;
  167. }
  168. protected function _createDefaultCategory () {
  169. $model = Mage::getModel('catalog/category');
  170. $name = 'New templates';
  171. $collection = $model
  172. ->getCollection()
  173. ->addAttributeToFilter('name', $name);
  174. if ($collection->count())
  175. return array($collection->getFirstItem()->getId());
  176. $collection
  177. ->clear()
  178. ->getSelect()
  179. ->reset('where');
  180. $collection->addAttributeToFilter('parent_id', 1);
  181. if ($collection->count() > 1) {
  182. $this->debug('Not a single root category');
  183. return array();
  184. } elseif ($collection->count() == 0) {
  185. $this->warning('Couldn\'t find root category.');
  186. return array();
  187. }
  188. $rootCategory = $collection->getFirstItem();
  189. if(!$rootCategory->getId()) {
  190. $this->warning('Couldn\'t load root category');
  191. return array();
  192. }
  193. $model
  194. ->setStoreId($rootCategory->getStoreId())
  195. ->setData(array(
  196. 'name' => $name,
  197. 'is_active' => 1,
  198. 'include_in_menu' => 1 ))
  199. ->setPath($rootCategory->getPath())
  200. ->setAttributeSetId($model->getDefaultAttributeSetId());
  201. try {
  202. $model->save();
  203. return array($model->getId());
  204. } catch (Exception $e) {
  205. $this->error($e->getMessage());
  206. return array();
  207. }
  208. }
  209. protected function _getWebsitesForAssign () {
  210. if (count(Mage::app()->getWebsites()) < 2)
  211. return array(Mage::app()->getWebsite(true)->getId());
  212. $websites = Mage::getStoreConfig('webtoprint/settings/assign-to-websites');
  213. if (!$websites) {
  214. $url = Mage::getModel('adminhtml/url')->getUrl(
  215. 'adminhtml/system_config/edit',
  216. array(
  217. 'section' => 'webtoprint',
  218. '_fragment' => 'row_webtoprint_settings_assign-to-stores')
  219. );
  220. $msg = 'Magento installation has multiple websites. Please select '
  221. . 'website(s) in Assign new products to website(s) setting on '
  222. . '<a href="' . $url . '">web-to-print settings page.</a> '
  223. . 'Newly created products will be assigned to selected website(s)';
  224. $this->error($msg);
  225. return;
  226. }
  227. return explode(',', $websites);
  228. }
  229. protected function _isProcessQuantities () {
  230. $value = $this
  231. ->getAction()
  232. ->getParam('process-quantities', false);
  233. if ($value === false)
  234. return false;
  235. $value = trim($value);
  236. return $value == 'true' || $value == 'yes' || $value == '1';
  237. }
  238. private function error ($message) {
  239. $this->addException($message, Mage_Dataflow_Model_Convert_Exception::ERROR);
  240. }
  241. private function notice ($message) {
  242. $this->addException($message, Mage_Dataflow_Model_Convert_Exception::NOTICE);
  243. }
  244. private function warning ($message) {
  245. $this->addException($message, Mage_Dataflow_Model_Convert_Exception::WARNING);
  246. }
  247. private function debug ($message) {
  248. if ($this->debug)
  249. $this->notice($message);
  250. }
  251. }
  252. ?>