Skip to content

Instantly share code, notes, and snippets.

@jonatanrdsantos
Last active October 17, 2016 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonatanrdsantos/584cf2fa7adb9a9e3e343e9308304b20 to your computer and use it in GitHub Desktop.
Save jonatanrdsantos/584cf2fa7adb9a9e3e343e9308304b20 to your computer and use it in GitHub Desktop.
Class To convert CSV data to Varien_Object

##Code

<?php
class Package_Module_Model_System_Config_Backend_ProcessCsv extends Varien_Object
{
    private $_csvFilePath;
    private $_headerIsValid;
    private $_validCsvHeader;
    private $_csvFileAsVarienFileCsv;
    private $_csvFileAsVarienObject;
    private $_csvFileWithoutHeader;

    /**
     * @param array $arguments
     */
    public function __construct($arguments = NULL)
    {
        $this->_csvFilePath = $arguments[0];
        $this->_validCsvHeader = $arguments[1];
        $this->_headerIsValid = true;
        $this->_csvFileAsVarienFileCsv = $this->_getCsvDataToVarienFileCsv();
    }

    /**
     * Retrieve the csv as varien Object
     */
    public function getCsvProcessedAsVarienObject()
    {
        $this->_validateIfCsvAreEmpty();
        $this->_validateCsvHeader();

        if($this->_headerIsValid) {
            $this->_createVarienObjectWithCsvData();
        }
        return $this->_csvFileAsVarienObject;
    }

    /**
     * @return string
     */
    private function _getCsvDataToVarienFileCsv()
    {
        $varienFileCsv = new Varien_File_Csv();
        $varienFileCsv->setDelimiter(',');
        return $varienFileCsv->getData($this->_csvFilePath);
    }

    /**
     * Validate the headers of the csv
     */
    private function _validateCsvHeader()
    {
        $this->_validateIfAllHeadersAreOnCsv();
    }

    /**
     * Validate if all headers are present on the csv
     */
    private function _validateIfAllHeadersAreOnCsv()
    {
        foreach ($this->_csvFileAsVarienFileCsv[0] as $indexKey => $csvHeaderName) {
            if ($this->_getFormattedCsvColumnName($csvHeaderName) != $this->_getFormattedCsvColumnName($this->_validCsvHeader[$indexKey])) {
                $this->_headerIsValid = false;
            }
        }
    }

    /**
     * Validate if csv are empty
     */
    private function _validateIfCsvAreEmpty()
    {
        if (!isset($this->_csvFileAsVarienFileCsv[0])) {
            Mage::throwException('The csv are empty');
            $this->_headerIsValid = false;
        }
    }

    private function _createVarienObjectWithCsvData()
    {
        $this->_prepareCsvToCreateVarienObject();

        foreach ($this->_csvFileWithoutHeader as $csvLine) {
            $this->_csvFileAsVarienObject[] = $this->_getFormattedCsvLineToVarienObject($csvLine);
        }
    }

    private function _getFormattedCsvLineToVarienObject($csvLine)
    {
        $formattedCsvLine = array();
        
        foreach ($csvLine as $csvColumnKey => $csvValue) {
            $formattedCsvLine[$this->_getFormattedCsvColumnName($this->_validCsvHeader[$csvColumnKey])] =  $csvValue;
        }

        return $this->_createVarienObjectBasedOnCsvLine($formattedCsvLine);
    }

    /**
     * @param array $csvLine
     * @return Varien_Object
     */
    private function _createVarienObjectBasedOnCsvLine($csvLine)
    {
        $varienObject = new Varien_Object();
        return $varienObject->setData($csvLine);
    }

    /**
     * @param string $columnName
     * @return string
     */
    private function _getFormattedCsvColumnName($columnName)
    {
        return trim(strtolower(str_replace(array('-','/'), '_', $columnName)));
    }

    /**
     * Prepare the csv to convert to varien object
     */
    private function _prepareCsvToCreateVarienObject()
    {
        $varienFileCsv = $this->_csvFileAsVarienFileCsv;
        unset($varienFileCsv[0]);// remove the header of csv
        $this->_csvFileWithoutHeader = $varienFileCsv;
    }
}
?>

Usage:

<?php

$csvFilePath = dirname(__FILE__) . '/file.csv';
$processCsvFile = Mage::getModel('package_module/system_config_backend_processCsv',array($csvFilePath,
    array('header01','header02', 'header03', 'header04', 'header05')));

$csvAsVarienObject = $processCsvFile->getCsvProcessedAsVarienObject();
?>

Result:

array (size=309)
  0 => 
    object(Varien_Object)[72]
      protected '_data' => 
        array (size=5)
          'header01' => string 'value 01' (length=8)
          'header02' => string 'value 02' (length=8)
          'header03' => string 'value 03' (length=8)
          'header04' => string 'value 04' (length=8)
          'header05' => string 'value 05' (length=8)
      protected '_hasDataChanges' => boolean true
      protected '_origData' => null
      protected '_idFieldName' => null
      protected '_isDeleted' => boolean false
      protected '_oldFieldsMap' => 
        array (size=0)
          empty
      protected '_syncFieldsMap' => 
        array (size=0)
          empty
  1 => 
    object(Varien_Object)[147]
      protected '_data' => 
        array (size=5)
          'header01' => string 'value 01' (length=8)
          'header02' => string 'value 02' (length=8)
          'header03' => string 'value 03' (length=8)
          'header04' => string 'value 04' (length=8)
          'header05' => string 'value 05' (length=8)
      protected '_hasDataChanges' => boolean true
      protected '_origData' => null
      protected '_idFieldName' => null
      protected '_isDeleted' => boolean false
      protected '_oldFieldsMap' => 
        array (size=0)
          empty
      protected '_syncFieldsMap' => 
        array (size=0)
          empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment