Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 21st, 2012  |  syntax: None  |  size: 8.60 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2.  
  3. /*
  4. error_reporting(E_ALL | E_STRICT);
  5. Mage::setIsDeveloperMode(true);
  6. ini_set('display_errors', 1);
  7. */
  8.  
  9. require_once 'abstract.php';
  10.  
  11. class Mage_Shell_DataFlow extends Mage_Shell_Abstract
  12. {
  13.     protected $_last_profile_exceptions;
  14.     protected $_last_batch_exceptions;
  15.  
  16.     protected function printListLine($elements) {
  17.         printf("%6s| %-40s| %-20s| %-20s\n", $elements[0], $elements[1], $elements[2], $elements[3]);
  18.     }
  19.  
  20.     /**
  21.      * @param $id_or_name string
  22.      * @return Mage_Dataflow_Model_Profile|bool
  23.      */
  24.     protected function getDataFlowProfile($id_or_name) {
  25.         $profile_collection = Mage::getModel('dataflow/profile')
  26.                                       ->getCollection();
  27.  
  28.         foreach($profile_collection as $profile) {
  29.             if ($profile->getId() == $id_or_name || $profile->getName() == $id_or_name)
  30.                 return $profile;
  31.         }
  32.  
  33.         return false;
  34.     }
  35.  
  36.     protected function doGetList() {
  37.         $profile_collection = Mage::getModel('dataflow/profile')
  38.                               ->getCollection();
  39.  
  40.         $this->printListLine(array("Id", "Name", "Direction", "Entity"));
  41.         printf("-------------------------------------------------------------------------------\n");
  42.         foreach($profile_collection as $profile) {
  43.             $this->printListLine(array($profile->getId(),
  44.                                        $profile->getName(),
  45.                                        $profile->getDirection(),
  46.                                        $profile->getEntityType()));
  47.         }
  48.     }
  49.  
  50.     protected function convertProfileExceptionsArray($exceptions) {
  51.         if (! $exceptions)
  52.             return array();
  53.  
  54.         $ret = array();
  55.         foreach ($exceptions as $e) {
  56.  
  57.             switch ($e->getLevel()) {
  58.                 case Varien_Convert_Exception::FATAL:
  59.                     $level = Varien_Convert_Exception::FATAL;
  60.                     $level_str = 'Fatal';
  61.                     break;
  62.                 case Varien_Convert_Exception::ERROR:
  63.                     $level = Varien_Convert_Exception::ERROR;
  64.                     $level_str = 'Error';
  65.                     break;
  66.                 case Varien_Convert_Exception::WARNING:
  67.                     $level = Varien_Convert_Exception::WARNING;
  68.                     $level_str = 'Warning';
  69.                     break;
  70.                 case Varien_Convert_Exception::NOTICE:
  71.                     $level = Varien_Convert_Exception::NOTICE;
  72.                     $level_str = 'Notice';
  73.                     break;
  74.             }
  75.  
  76.             $ret[] = new Varien_Object(array(
  77.                 "level"     => $level,
  78.                 "level_str" => $level_str,
  79.                 "message"   => $e->getMessage(),
  80.                 "exception" => $e
  81.             ));
  82.         }
  83.  
  84.         return $ret;
  85.     }
  86.  
  87.     /**
  88.      * @return bool
  89.      */
  90.     protected function inspectProfileExceptions() {
  91.         if (! $this->_last_profile_exceptions)
  92.             return false;
  93.  
  94.         fprintf(STDERR, "### Profile ###\n");
  95.  
  96.         $has_critical_error_happened = false;
  97.         foreach ($this->_last_profile_exceptions as $e) {
  98.             fprintf(STDERR, "**%s**: %s\n\n", $e->getLevelStr(), $e->getMessage());
  99.  
  100.             if (   $e->getLevel() == Varien_Convert_Exception::ERROR
  101.                 || $e->getLevel() == Varien_Convert_Exception::FATAL)
  102.             {
  103.                 Mage::logException($e->getException());
  104.                 $has_critical_error_happened = true;
  105.             }
  106.         }
  107.  
  108.         return $has_critical_error_happened;
  109.     }
  110.  
  111.     /**
  112.      * @return bool
  113.      */
  114.     protected function inspectBatchExceptions() {
  115.         if (! $this->_last_batch_exceptions)
  116.             return false;
  117.  
  118.         fprintf(STDERR, "### Batch ###\n");
  119.  
  120.         foreach ($this->_last_batch_exceptions as $e) {
  121.             fprintf(STDERR, "**%s**: %s\n", "Message", $e);
  122.         }
  123.  
  124.         fprintf(STDERR, "\n");
  125.  
  126.         return false;
  127.     }
  128.  
  129.     /**
  130.      * @param Mage_Dataflow_Model_Profile $profile
  131.      * @return Mage_Dataflow_Model_Batch
  132.      */
  133.     protected function doRunProfile(Mage_Dataflow_Model_Profile $profile) {
  134.         $this->_last_profile_exceptions = false;
  135.  
  136.         $user = Mage::getModel('admin/user');
  137.         $user->setUserId(0);
  138.  
  139.         Mage::getSingleton('admin/session')
  140.             ->setUser($user);
  141.  
  142.         $profile = Mage::getModel("dataflow/profile")
  143.                        ->load($profile->getId());
  144.  
  145.         Mage::register('current_convert_profile', $profile);
  146.         $profile->run();
  147.  
  148.         $this->_last_profile_exceptions = $this->convertProfileExceptionsArray($profile->getExceptions());
  149.  
  150.         return Mage::getSingleton('dataflow/batch');
  151.     }
  152.  
  153.     protected function doRunBatch(Mage_Dataflow_Model_Batch $batch) {
  154.         if (! $batch->getId()) {
  155.             throw new Exception("Uninitialized batch-model for import");
  156.         }
  157.  
  158.         $adapter = Mage::getModel($batch->getAdapter());
  159.         $adapter->setBatchParams($batch->getParams());
  160.  
  161.         $import_model = $batch->getBatchImportModel();
  162.         $import_ids = $import_model->getIdCollection();
  163.  
  164.         $this->_last_batch_exceptions = array();
  165.         $saved = 0;
  166.  
  167.         foreach ($import_ids as $id) {
  168.             $import_model->load($id);
  169.             if (! $import_model->getid()) {
  170.                 $this->_last_batch_exceptions[] = sprintf("Skipping undefined row");
  171.                 continue;
  172.             }
  173.  
  174.             try {
  175.                 $import_data = $import_model->getBatchData();
  176.                 $adapter->saveRow($import_data);
  177.             } catch (Exception $ex) {
  178.                 $this->_last_batch_exceptions[] = $ex->getMessage();
  179.                 continue;
  180.             }
  181.  
  182.             $saved++;
  183.         }
  184.  
  185.         if (method_exists($adapter, "'getEventPrefix'")) {
  186.             /**
  187.              * Event for process rules relations after products import
  188.              */
  189.             Mage::dispatchEvent($adapter->getEventPrefix() . '_finish_before', array(
  190.                 'adapter' => $adapter
  191.             ));
  192.  
  193.             /**
  194.              * Clear affected ids for adapter possible reuse
  195.              */
  196.             $adapter->clearAffectedEntityIds();
  197.         }
  198.  
  199.         return $saved;
  200.     }
  201.  
  202.     /**
  203.      * @param $id_or_name string
  204.      * @throws Exception
  205.      */
  206.     protected function doImport($id_or_name) {
  207.         $profile = $this->getDataFlowProfile($id_or_name);
  208.         if (! $profile)
  209.             throw new Exception(sprintf("Unable to find profile '%s'", $id_or_name));
  210.  
  211.         if ($profile->getEntityType() && ! $profile->getDirection() == "import")
  212.             throw new Exception(sprintf("Selected profile '%s' is not an import", $id_or_name));
  213.  
  214.         fprintf(STDERR, "\n");
  215.  
  216.         /** @var $batch Mage_Dataflow_Model_Batch_Import */
  217.         $batch = $this->doRunProfile($profile);
  218.  
  219.         $has_critical_error_happened = $this->inspectProfileExceptions();
  220.         if ($has_critical_error_happened)
  221.             return;
  222.  
  223.         $n_saved = $this->doRunBatch($batch);
  224.         $this->inspectBatchExceptions();
  225.     }
  226.  
  227.     /**
  228.      * @param $id_or_name string
  229.      * @throws Exception
  230.      */
  231.     protected function doExport($id_or_name) {
  232.         $profile = $this->getDataFlowProfile($id_or_name);
  233.         if (! $profile)
  234.             throw new Exception(sprintf("Unable to find profile '%s'", $id_or_name));
  235.  
  236.         if ($profile->getEntityType() && ! $profile->getDirection() == "export")
  237.             throw new Exception(sprintf("Selected profile '%s' is not an export", $id_or_name));
  238.  
  239.         /** @var $batch Mage_Dataflow_Model_Batch_Export */
  240.         $batch = $this->doRunProfile($profile);
  241.  
  242.         print_r($batch->getData());
  243.     }
  244.  
  245.     public function run()
  246.     {
  247.         try {
  248.             if ($this->getArg("list")){
  249.                 $this->doGetList();
  250.             }
  251.             else if ($this->getArg("import")) {
  252.                 $this->doImport($this->getArg("import"));
  253.             }
  254.             else if ($this->getArg("export")) {
  255.                 $this->doExport($this->getArg("export"));
  256.             }
  257.             else {
  258.                 echo $this->usageHelp();
  259.             }
  260.         } catch (Exception $ex) {
  261.             fprintf(STDERR, "\n**Error** During execution: \n");
  262.             fprintf(STDERR, "%s\n\n", $ex->__toString());
  263.             Mage::logException($ex);
  264.         }
  265.     }
  266.  
  267.    /**
  268.      * Retrieve Usage Help Message
  269.      *
  270.      */
  271.     public function usageHelp()
  272.     {
  273.         return <<<USAGE
  274.  
  275. Usage:  php -f dataflow.php -- [options]
  276.  
  277.   --import <profile>            Run DataFlow import profile
  278.   --export <profile>            Run DataFlow export profile
  279.   --list                        List available profiles
  280.  
  281.   <profile>     Id or Name of a DataFlow-profile
  282.  
  283.  
  284. USAGE;
  285.     }
  286. }
  287.  
  288. $shell = new Mage_Shell_DataFlow();
  289. $shell->run();