Advertisement
Guest User

MainFormController.php

a guest
Feb 14th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 22.89 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4.  * Links
  5.  *
  6.  * Configurable Products in Magento
  7.  * http://blog.omnisubsole.com/2009/07/01/configurable-products-in-magento/
  8.  *
  9.  * Create configurable product in Magento programmatically
  10.  * http://www.codetweet.com/magento/create-configurable-product-magento-programmatically/
  11.  *
  12.  * http://www.jackecommerce.com/magento-programmatically-create-configurable-product-and-assgin-simple-product/
  13.  */
  14.  
  15. /*
  16.  * TODO
  17.  * Load all attribute sets and their attributes on load (a bit of optimisation)
  18.  * Perform actions with AJAX (timeLimit and user sees process progress)
  19.  * Categories
  20.  * Images
  21.  */
  22.  
  23. class SpartakusMd_CustomProductImporter_Adminhtml_MainformController extends Mage_Adminhtml_Controller_Action
  24. {
  25.  
  26.     private $_fieldNames = array();
  27.     private $_fileData = array();
  28.  
  29.     public function indexAction()
  30.     {
  31.         $this->loadLayout()->renderLayout();
  32.     }
  33.  
  34.     public function postAction()
  35.     {
  36.         echo '<pre>';
  37.         $this->importFromXML();
  38.         echo '</pre>';
  39.     }
  40.  
  41.     private function createSimpleProduct($args) {
  42.         $defaults = array(
  43.             'TypeId' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
  44.             'TaxClassId' => 0,
  45.             'WebsiteIds' => array(1),
  46.             'AttributeSetId' => $this->getAttributeSetId('Default'),
  47.             'Description' => '',
  48.             'ShortDescription' => '',
  49.             'Weight' => 0,
  50.             'Status' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED,
  51.             'Visibility' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE, //1 - Not Visible Individually
  52.             'StockQty' => '99',
  53.             'MetaTitle' => '',
  54.             'MetaDescription' => '',
  55.             'MetaKeywords' => '',
  56.         );
  57.  
  58.         $o = array_merge($defaults, $args);
  59.  
  60.         //create product
  61.         $product = Mage::getModel('catalog/product');
  62.         $product->setTypeId($o['TypeId']);
  63.         $product->setTaxClassId($o['TaxClassId']); //none
  64.         $product->setWebsiteIds($o['WebsiteIds']);  // store id
  65.  
  66.         //setting product attributes
  67.         $productAttributes = array();
  68.         $attributesData = array();
  69.         $_attributes = array();
  70.         $product->setAttributeSetId($o['AttributeSetId']);
  71.  
  72. //      echo '$o = '; print_r($o);
  73. //      die;
  74.  
  75.         foreach( $o['Attributes'] as $key=>$value ) {
  76.             $attrID = $this->getAttributeId($key);
  77.             $_attributes[$key] = $attrID;
  78.             $this->addAttributeValue($key, $value);
  79.             $value_index = $this->attributeValueExists($key, $value);
  80.             $product->setData($key, $value);
  81.  
  82.             $productAttributes[] = array(
  83.                 'attribute_id' => $attrID,
  84.                 'label' => $value,
  85.                 'value_index' => $value_index,
  86.                 'is_percent' => 0,
  87.                 'pricing_value' => 0
  88.             );
  89.  
  90.             $attributesData[$key][$attrID . '-' . $value . '-' . $value_index] = array(
  91.                 'attribute_id' => $attrID,
  92.                 'label' => $value,
  93.                 'value_index' => $value_index,
  94.                 'is_percent' => 0,
  95.                 'pricing_value' => 0
  96.             );
  97.         }
  98.  
  99.         $product->setSku($o['Sku']);
  100.         $product->setName($o['Name']);
  101.         $product->setPrice(sprintf("%0.2f", floatval($o['Price'])));
  102.  
  103.         $product->setDescription($o['Description']);
  104.         $product->setShortDescription($o['ShortDescription']);
  105.         $product->setInDepth($o['Description']);
  106.         $product->setWeight($o['Weight']);
  107.         $product->setStatus($o['Status']); //enabled
  108.         $product->setVisibility($o['Visibility']);
  109.         $product->setStockData(
  110.             array(
  111.                 'use_config_manage_stock' => 1,
  112.                 'is_in_stock' => 1,
  113.                 'is_salable' => 1,
  114.                 'qty' => $o['StockQty']
  115.             )
  116.         );
  117.         $product->setMetaTitle($o['MetaTitle']);
  118.         $product->setMetaDescription($o['MetaDescription']);
  119.         $product->setMetaKeywords($o['MetaKeywords']);
  120.         $product->setCategoryIds($o['categoryids']);
  121.  
  122.         echo 'Simple[o] = '; print_r($o);
  123.  
  124.         /*
  125.         // use the directory path to images you want to save for the product
  126.         $mode = array("image");
  127.         $img = 'full_directory_path_to_image_stored_img_0001.jpg';
  128.         $sProduct->addImageToMediaGallery($img, $mode, false, false);
  129.  
  130.         $mode = array("small_image", "thumbnail", "image");
  131.         $img = 'full_directory_path_to_image_stored_img_0002.jpg';
  132.         $sProduct->addImageToMediaGallery($img, $mode, false, false);
  133.         */
  134.  
  135.         try{
  136.             $product->save();
  137.             echo 'Simple product ' . $product->getId() . '(' . $o['Name'] . '), successfully added!<br />';
  138.  
  139.             $ret = array();
  140.             $ret['product'] = array($product->getId() => $productAttributes);
  141.             $ret['_attributes'] = $_attributes;
  142.             $ret['attributesData'] = $attributesData;
  143.             echo '$simple_ret = '; print_r($ret);
  144.             echo '<hr>';
  145.  
  146.             return $ret;
  147.         }
  148.         catch (Exception $e){
  149.             echo 'Error! Product not added!';
  150.             echo 'Exception: ' . $e;
  151.         }
  152.  
  153.         return false;
  154.     }
  155.  
  156.     private function createConfigurableProduct($args) {
  157.         $defaults = array(
  158.             '_typeId' => Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE,
  159.             '_taxClassId' => 0,
  160.             '_websiteIds' => array(1),
  161.             'AttributeSetId' => $this->getAttributeSetId('Default'),
  162.             'Description' => '',
  163.             'ShortDescription' => '',
  164.             'Weight' => 0,
  165.             'Status' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED,
  166.             'Visibility' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, //4 - Catalog, Search
  167.             'StockQty' => '99',
  168.             'MetaTitle' => '',
  169.             'MetaDescription' => '',
  170.             'MetaKeywords' => '',
  171.         );
  172.  
  173.         $o = array_merge($defaults, $args);
  174.  
  175.         //get combinations of attributes
  176.         $setOfAttributes = $this->cartesianProduct($args['attributes']);
  177.  
  178.         //create simple products
  179.         $configurableProductsData = array();
  180.         $_attributeIds = array();
  181.         $attributesData = array();
  182.         $i=0;
  183.         foreach( $setOfAttributes as $attrs ) {
  184.             $simpleArgs = $o;
  185.             $simpleArgs['Attributes'] = $attrs;
  186.             unset($simpleArgs['Visibility']);
  187.             foreach( $attrs as $value ) {
  188.                 $simpleArgs['Name'] .= '-' . $value;
  189.                 $simpleArgs['Sku'] .= '-' . $value;
  190.             }
  191.  
  192.             $sp = $this->createSimpleProduct($simpleArgs);
  193.  
  194.             if( $sp !== false ) {
  195.                 foreach( $sp['product'] as $key=>$value ) {
  196.                     $configurableProductsData[$key] = $value;
  197.                 }
  198.  
  199.  
  200.                 $_attributeIds = array_merge($_attributeIds, $sp['_attributes']);
  201.  
  202.                 foreach( $sp['attributesData'] as $key=>$value ) {
  203.                     if( !isset($attributesData[$key]) ) $attributesData[$key] = array();
  204.                     $attributesData[$key] = array_merge($attributesData[$key], $value);
  205.                 }
  206.                 //$attributesData = array_merge_recursive($attributesData, $sp['attributesData']); //TODO
  207.  
  208.                 echo '$configurableProductsData = '; print_r($sp['product']);
  209.             }
  210.  
  211.             if($i++ == 2) break; //TODO Limit 2
  212.         }
  213.  
  214.         //create product
  215.         $product = Mage::getModel('catalog/product');
  216.         $product->setTypeId($o['_typeId']);
  217.         $product->setTaxClassId($o['_taxClassId']); //none
  218.         $product->setWebsiteIds($o['_websiteIds']);  // store id
  219.  
  220.         $product->setAttributeSetId($o['AttributeSetId']); //Default Attribute Set
  221.  
  222. //      foreach( $o['Attributes'] as $key=>$value ) {
  223. //          $product->setData($key, $value);
  224. //      }
  225.  
  226.         $product->setSku($o['Sku']);
  227.         $product->setName($o['Name']);
  228.         $product->setPrice(sprintf("%0.2f", floatval($o['Price'])));
  229.  
  230.         $product->setDescription($o['Description']);
  231.         $product->setShortDescription($o['ShortDescription']);
  232.         $product->setInDepth($o['Description']);
  233.         $product->setWeight($o['Weight']);
  234.         $product->setStatus($o['Status']); //enabled
  235.         $product->setVisibility($o['Visibility']);
  236.         $product->setStockData(
  237.             array(
  238.                 'use_config_manage_stock' => 1,
  239.                 'is_in_stock' => 1,
  240.                 'is_salable' => 1,
  241.                 'qty' => $o['StockQty']
  242.             )
  243.         );
  244.         $product->setMetaTitle($o['MetaTitle']);
  245.         $product->setMetaDescription($o['MetaDescription']);
  246.         $product->setMetaKeywords($o['MetaKeywords']);
  247.         $product->setCategoryIds($o['categoryids']);
  248.  
  249.         echo 'Configurable[o] = '; print_r($o);
  250.         echo '#categoryids = '; print_r($o['categoryids']);
  251.  
  252.         // Set configurable info
  253.         $cProductTypeInstance = $product->getTypeInstance();
  254.         $cProductTypeInstance->setUsedProductAttributeIds($_attributeIds);
  255.  
  256.         // Now we need to get the information back in Magento's own format, and add bits of data to what it gives us..
  257.         $attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
  258.         $i = 0;
  259.         foreach($attributes_array as $key => $attribute_array) {
  260.             $attributes_array[$key]['use_default'] = 1;
  261.             $attributes_array[$key]['position'] = $i++;
  262.             $attributes_array[$key]['html_id'] = 'config_super_product__attribute_' . $attributes_array[$key]['position'];
  263.  
  264.             if (isset($attribute_array['frontend_label'])) {
  265.                 $attributes_array[$key]['label'] = $attribute_array['frontend_label'];
  266.             } else {
  267.                 $attributes_array[$key]['label'] = $attribute_array['attribute_code'];
  268.             }
  269.  
  270.             if( isset($attributesData[$attribute_array['attribute_code']]) ) {
  271.                 foreach( $attributesData[$attribute_array['attribute_code']] as $value ) {
  272.                     $attributes_array[$key]['values'][] = $value;
  273.                 }
  274.             }
  275.         }
  276.  
  277.         echo '$_attributeIds = '; print_r($_attributeIds);
  278.         echo '$attributes_array = '; print_r($attributes_array);
  279.         echo '$attributesData = '; print_r($attributesData);
  280.         echo '$configurableProductsData = '; print_r($configurableProductsData);
  281. //      die;
  282.  
  283.         $product->setConfigurableProductsData($configurableProductsData);
  284.         $product->setConfigurableAttributesData($attributes_array);
  285.         $product->setCanSaveConfigurableAttributes(true);
  286.         $product->setCanSaveCustomOptions(true);
  287.  
  288. /* TODO
  289.         $configurableProductsData = array(
  290.             '5791' => array(
  291.                 '0' => array('attribute_id' => '491', 'label' => 'vhs', 'value_index' => '5', 'is_percent' => 0, 'pricing_value' => ''),
  292.                 '1' => array('attribute_id' => '500', 'label' => 'English', 'value_index' => '9', 'is_percent' => 0, 'pricing_value' => '')
  293.             ),
  294.             '5792' => array(
  295.                 '0' => array('attribute_id' => '491', 'label' => 'dvd', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
  296.                 '1' => array('attribute_id' => '500', 'label' => 'English', 'value_index' => '9', 'is_percent' => 0, 'pricing_value' => '')
  297.             ),
  298.             '5807' => array(
  299.                 '0' => array('attribute_id' => '491', 'label' => 'dvd', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
  300.                 '1' => array('attribute_id' => '500', 'label' => 'Spanish', 'value_index' => '8', 'is_percent' => 0, 'pricing_value' => '')
  301.             ),
  302.             '5808' => array(
  303.                 '0' => array('attribute_id' => '491', 'label' => 'vhs', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
  304.                 '1' => array('attribute_id' => '500', 'label' => 'Spanish', 'value_index' => '8', 'is_percent' => 0, 'pricing_value' => '')
  305.             )
  306.         );
  307.        
  308.         $configurableAttributesData = array(
  309.             '0' => array(
  310.                 'id' => NULL,
  311.                 'label' => 'Media Format',
  312.                 'position' => NULL,
  313.                 'values' => array(
  314.                     '0' =>
  315.                     array(
  316.                         'value_index' => 5,
  317.                         'label' => 'vhs',
  318.                         'is_percent' => 0,
  319.                         'pricing_value' => '0',
  320.                         'attribute_id' => '491'
  321.                     ),
  322.                     '1' =>
  323.                         array(
  324.                             'value_index' => 6,
  325.                             'label' => 'dvd',
  326.                             'is_percent' => 0,
  327.                             'pricing_value' => '0',
  328.                             'attribute_id' => '491'
  329.                         )
  330.                 ),
  331.                 'attribute_id' => 491, 'attribute_code' => 'media_format', 'frontend_label' => 'Media Format', 'html_id' => 'config_super_product__attribute_0'
  332.             ),
  333.             '1' => array(
  334.                 'id' => NULL,
  335.                 'label' => 'Language',
  336.                 'position' => NULL,
  337.                 'values' => array(
  338.                     '0' => array(
  339.                         'value_index' => 8,
  340.                         'label' => 'Spanish',
  341.                         'is_percent' => 0,
  342.                         'pricing_value' => '0',
  343.                         'attribute_id' => '500'
  344.                     ),
  345.                     '1' => array(
  346.                         'value_index' => 9,
  347.                         'label' => 'English',
  348.                         'is_percent' => 0,
  349.                         'pricing_value' => '0',
  350.                         'attribute_id' => '500'
  351.                     )
  352.                 ),
  353.                 'attribute_id' => 500, 'attribute_code' => 'media_format', 'frontend_label' => 'Language', 'html_id' => 'config_super_product__attribute_1')
  354.         );
  355.  
  356.         $product->setConfigurableProductsData($configurableProductsData);
  357.         $product->getTypeInstance()->setUsedProductAttributeIds(array(491,500));
  358.         $product->setConfigurableAttributesData($configurableAttributesData);
  359.         $product->setCanSaveConfigurableAttributes(1);
  360. */
  361.  
  362.         try{
  363.             $product->save();
  364.             echo 'Configurable Product ' . $product->getId() . '(' . $o['Name'] . '), successfully added!';
  365.             echo '<hr><hr><hr>';
  366.             return $product;
  367.         }
  368.         catch (Exception $e){
  369.             echo 'Error! Configurable Product not added!';
  370.             echo 'Exception: ' . $e;
  371.         }
  372.     }
  373.  
  374.     /**
  375.      * Retrive an attribute set ID based on it's name
  376.      *
  377.      * @param string $attributeSetName
  378.      * @return mixed
  379.      */
  380.     private function getAttributeSetId($attributeSetName = 'Default') {
  381.         $entityTypeId = Mage::getModel('eav/entity')
  382.             ->setType('catalog_product')
  383.             ->getTypeId();
  384.         $attributeSetId = Mage::getModel('eav/entity_attribute_set')
  385.             ->getCollection()
  386.             ->setEntityTypeFilter($entityTypeId)
  387.             ->addFieldToFilter('attribute_set_name', $attributeSetName)
  388.             ->getFirstItem()
  389.             ->getAttributeSetId();
  390.         return $attributeSetId;
  391.     }
  392.  
  393.     /**
  394.      * Retrieve the attribute id by code
  395.      *
  396.      * @param $attributeCode
  397.      * @return int
  398.      */
  399.     private function getAttributeId($attributeCode) {
  400.         $attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);
  401.         return $attributeModel->getAttributeId();
  402.     }
  403.  
  404.     /**
  405.      * Retrieve attributes from a set
  406.      *
  407.      * @param int|string $attributeSetId Attribute Set ID or Name
  408.      * @return Array|false Array of attributes
  409.      */
  410.     private function getAttributesFromSet($attributeSetId) {
  411.         if( is_string($attributeSetId) ) {
  412.             $attributeSetId = $this->getAttributeSetId($attributeSetId);
  413.         }
  414.  
  415.         $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
  416.  
  417.         return $attributes;
  418.     }
  419.  
  420.     /**
  421.      * Get individual attribute from array based on it's code
  422.      *
  423.      * @param $attributeCode
  424.      * @param $attributeSet
  425.      * @return Array|bool
  426.      */
  427.     private function getAttributeFromAttributesSetArray($attributeCode, $attributeSet) {
  428.         foreach($attributeSet as $attribute) {
  429.             if( $attribute['code'] == $attributeCode ) {
  430.                 return $attribute;
  431.             }
  432.         }
  433.  
  434.         return false;
  435.     }
  436.  
  437.     /**
  438.      * Retrieve dropdown attribute options
  439.      *
  440.      * @param $attributeCode
  441.      * @return Array|bool
  442.      */
  443.     private function getAttributeOptions($attributeCode) {
  444.         $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attributeCode);
  445.         return $attribute->getSource()->getAllOptions(true, true);
  446.     }
  447.  
  448.     /**
  449.      * Check whether given attribute value exists
  450.      *
  451.      * @param $arg_attribute
  452.      * @param $arg_value
  453.      * @return bool
  454.      */
  455.     public function attributeValueExists($arg_attribute, $arg_value)
  456.     {
  457.         $attribute_model        = Mage::getModel('eav/entity_attribute');
  458.         $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
  459.  
  460.         $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
  461.         $attribute              = $attribute_model->load($attribute_code);
  462.  
  463.         $attribute_table        = $attribute_options_model->setAttribute($attribute);
  464.         $options                = $attribute_options_model->getAllOptions(false);
  465.  
  466.         foreach($options as $option)
  467.         {
  468.             if ($option['label'] == $arg_value)
  469.             {
  470.                 return $option['value'];
  471.             }
  472.         }
  473.  
  474.         return false;
  475.     }
  476.  
  477.     /**
  478.      * Add attribute option to magento
  479.      *
  480.      * @param $arg_attribute
  481.      * @param $arg_value
  482.      * @return int|bool Id of value
  483.      */
  484.     public function addAttributeValue($arg_attribute, $arg_value)
  485.     {
  486.         $attribute_model        = Mage::getModel('eav/entity_attribute');
  487.         $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
  488.  
  489.         $attribute_code         = $attribute_model->getIdByCode(1, $arg_attribute);
  490.         $attribute              = $attribute_model->load($attribute_code);
  491.  
  492.         $attribute_table        = $attribute_options_model->setAttribute($attribute);
  493.         $options                = $attribute_options_model->getAllOptions(false);
  494.  
  495.         if(!$this->attributeValueExists($arg_attribute, $arg_value))
  496.         {
  497.             $value['option'] = array($arg_value,$arg_value);
  498.             $result = array('value' => $value);
  499.             $attribute->setData('option',$result);
  500.             $attribute->save();
  501.         }
  502.  
  503.         foreach($options as $option)
  504.         {
  505.             if ($option['label'] == $arg_value)
  506.             {
  507.                 return $option['value'];
  508.             }
  509.         }
  510.         return true;
  511.     }
  512.  
  513.     /**
  514.      * Get individual attribute option from array based on it's label
  515.      *
  516.      * @param $optionLabel
  517.      * @param $options
  518.      * @return Array|bool
  519.      */
  520.     private function getAttributeOptionByLabel($optionLabel, $options) {
  521.         foreach($options as $option) {
  522.             if( $option['label'] == $optionLabel ) {
  523.                 return $option;
  524.             }
  525.         }
  526.  
  527.         return false;
  528.     }
  529.  
  530.     /**
  531.      * Retrieve store category id based on the one from XML
  532.      *
  533.      * @param $id
  534.      * @return Array|bool array with the category, or false if not mapped
  535.      */
  536.     private function getStoreCategory( $id ) {
  537.         $categoryRelations = array(
  538.             '59229' => array(187),
  539.             '59296' => array(190),
  540.             '59297' => array(193),
  541.             '73050' => array(190),
  542.             '68406' => array(194),
  543.             '68407' => array(193),
  544.             '59207' => array(187),
  545.             '60569' => array(190),
  546.             '59203' => array(190),
  547.             '59204' => array(190),
  548.             '65397' => array(187),
  549.             '59211' => array(190),
  550.             '59214' => array(198),
  551.             '61471' => array(198),
  552.             '59217' => array(187),
  553.             '68445' => array(194),
  554.             '68446' => array(193),
  555.             '59257' => array(186),
  556.             '69611' => array(190),
  557.             '60175' => array(187),
  558.             '59264' => array(190),
  559.             '59228' => array(209),
  560.             '59219' => array(209),
  561.             '68816' => array(195),
  562.             '67653' => array(195),
  563.             '59213' => array(195),
  564.             '67650' => array(202),
  565.             '69572' => array(200),
  566.             '70018' => array(202),
  567.             '70994' => array(210, 204),
  568.             '70989' => array(210, 204),
  569.             '70991' => array(210, 204),
  570.             '70995' => array(210, 204),
  571.             '70987' => array(210, 204),
  572.             '70848' => array(210, 204),
  573.             '70990' => array(210, 204),
  574.             '70996' => array(210, 204),
  575.             '70993' => array(210, 204),
  576.             '70847' => array(210, 204),
  577.             '70844' => array(210, 204),
  578.             '70998' => array(206),
  579.             '68151' => array(206),
  580.             '59397' => array(206),
  581.             '68165' => array(206),
  582.             '72076' => array(206),
  583.             '70722' => array(206),
  584.             '71109' => array(206),
  585.             '70721' => array(206),
  586.             '71116' => array(206),
  587.             '70740' => array(206),
  588.             '70723' => array(206),
  589.             '70720' => array(206),
  590.             '71003' => array(206),
  591.             '71028' => array(206),
  592.             '71117' => array(206),
  593.             '59401' => array(206),
  594.             '70043' => array(205),
  595.             '70044' => array(205),
  596.             '70045' => array(205),
  597.             '70049' => array(205),
  598.             '71496' => array(205),
  599.             '70048' => array(205),
  600.             '70047' => array(205),
  601.             '70050' => array(205)
  602.         );
  603.  
  604.         if( isset($categoryRelations[(string) $id]) ) return $categoryRelations[(string) $id];
  605.  
  606.         return false;
  607.     }
  608.  
  609.     /**
  610.      * Parse and import products from an XML file
  611.      */
  612.     private function importFromXML() {
  613.         $categoryProducts = $this->getProductsArrayFromXML();
  614.         $prodCountByCatID = array();
  615.         foreach( $categoryProducts as $products ) {
  616.             foreach( $products as $product ) {
  617.                 //count products per category
  618.                 if( !isset($prodCountByCatID[$product['catid']]) ) $prodCountByCatID[$product['catid']] = 1;
  619.                 else $prodCountByCatID[$product['catid']]++;
  620.  
  621.                 //if limit reached skip the product
  622.                 if( $prodCountByCatID[$product['catid']] >= 20 ) continue;
  623.  
  624.                 //create the product
  625.                 $this->createConfigurableProduct($product);
  626.  
  627.                 break; //TODO remove limit 1
  628.             }
  629.             break; //TODO remove limit 1
  630.         }
  631.     }
  632.  
  633.     /**
  634.      * Get products from the XML file
  635.      *
  636.      * @return array Products info array from XML
  637.      */
  638.     private function getProductsArrayFromXML() {
  639.         //Parse XML
  640.         $data = trim(file_get_contents('http://feed485.efashioncentral.com/df/feed.php'));
  641.         $XML = new SimpleXmlElement($data);
  642.         $productsToImport = array();
  643.  
  644.         if( isset($XML->product) ) {
  645.             foreach ( $XML->product as $product ) {
  646.                 $p = array(); //new array
  647.  
  648.                 $attributes = $product->attributes();
  649.                 $p['id'] = (int) $attributes['id'];
  650.                 $p['catid'] = (int) $product->catid;
  651.                 $p['categoryids'] = $this->getStoreCategory($product->catid); //TODO: get correct category
  652.                 $p['Sku'] = (string) $product->stylenum;
  653.                 $p['Price'] = (float) $product->price;
  654.                 $p['StockQty'] = 99;
  655.                 $p['Name'] = (string) $product->name;
  656.                 $p['ShortDescription'] = (string) $product->shortdesc;
  657.                 $p['Description'] = (string) $product->desc;
  658.                 $p['Keywords'] = (string) $product->keywords;
  659.  
  660.                 $p['images'] = array();
  661.                 if( isset($product->images) && isset($product->images->image) ) {
  662.                     foreach( $product->images->image as $image ) {
  663.                         $p['images'][] = (string) $image->bigimage;
  664.                     }
  665.                 }
  666.  
  667.                 $p['attributes'] = array();
  668.                 $p['attributes']['size'] = array();
  669.                 if( isset($product->sizes) && isset($product->sizes->size) ) {
  670.                     foreach( $product->sizes->size as $size ) {
  671.                         $p['attributes']['size'][] = (string) $size;
  672.                     }
  673.                 }
  674.  
  675.                 $p['attributes']['color'] = array();
  676.                 if( isset($product->colors) && isset($product->colors->color) ) {
  677.                     foreach( $product->colors->color as $color ) {
  678.                         $p['attributes']['color'][] = (string) $color->colorname;
  679.                     }
  680.                 }
  681.  
  682.                 //skip if store hasn't such category
  683.                 if( !isset($p['categoryids']) || $p['categoryids'] === false ) continue;
  684.  
  685.                 //store import cat num as array index
  686.                 $productsToImport[$p['catid']][$p['id']] = $p;
  687.             }
  688.         }
  689.  
  690.         return $productsToImport;
  691.     }
  692.  
  693.     /**
  694.      * Generate cartesian product for configurable products
  695.      *
  696.      * @param $input
  697.      * @return array
  698.      */
  699.     public function cartesianProduct( $input ) {
  700.         $result = array();
  701.  
  702.         while (list($key, $values) = each($input)) {
  703.             // If a sub-array is empty, it doesn't affect the cartesian product
  704.             if (empty($values)) {
  705.                 continue;
  706.             }
  707.  
  708.             // Seeding the product array with the values from the first sub-array
  709.             if (empty($result)) {
  710.                 foreach($values as $value) {
  711.                     $result[] = array($key => $value);
  712.                 }
  713.             }
  714.             else {
  715.                 // Second and subsequent input sub-arrays work like this:
  716.                 //   1. In each existing array inside $product, add an item with
  717.                 //      key == $key and value == first item in input sub-array
  718.                 //   2. Then, for each remaining item in current input sub-array,
  719.                 //      add a copy of each existing array inside $product with
  720.                 //      key == $key and value == first item of input sub-array
  721.  
  722.                 // Store all items to be added to $product here; adding them
  723.                 // inside the foreach will result in an infinite loop
  724.                 $append = array();
  725.  
  726.                 foreach($result as &$product) {
  727.                     // Do step 1 above. array_shift is not the most efficient, but
  728.                     // it allows us to iterate over the rest of the items with a
  729.                     // simple foreach, making the code short and easy to read.
  730.                     $product[$key] = array_shift($values);
  731.  
  732.                     // $product is by reference (that's why the key we added above
  733.                     // will appear in the end result), so make a copy of it here
  734.                     $copy = $product;
  735.  
  736.                     // Do step 2 above.
  737.                     foreach($values as $item) {
  738.                         $copy[$key] = $item;
  739.                         $append[] = $copy;
  740.                     }
  741.  
  742.                     // Undo the side effecst of array_shift
  743.                     array_unshift($values, $product[$key]);
  744.                 }
  745.  
  746.                 // Out of the foreach, we can add to $results now
  747.                 $result = array_merge($result, $append);
  748.             }
  749.         }
  750.  
  751.         return $result;
  752.     }
  753.  
  754. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement