Created
February 2, 2014 10:55
-
-
Save intco/8766469 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* CsvRow class | |
* | |
* @copyright Angelo Galleja | |
* @license public domain | |
* | |
* | |
* TODO: make exception messages more clear :-O | |
*/ | |
abstract class CsvRow { | |
abstract protected function getColumns(); | |
public function parse($arrData) { | |
$arrColumns = $this->getColumns(); | |
$row = array(); | |
foreach ($arrColumns as $field => $arrCallback) { | |
if (!isset($arrData[$field])) { | |
throw new \Exception($field.' not found in data array'); | |
} | |
$strValue = $arrData[$field]; | |
foreach ($arrCallback as $callback) { | |
if (is_string($callback) && function_exists($callback)) { | |
$strValue = $callback($strValue); | |
continue; | |
} | |
if (is_array($callback) && count($callback) == 2) { | |
list($obj, $method) = $callback; | |
if (!is_object($obj)) { | |
throw new \Exception('invalid object defined for '.$field); | |
} | |
if (!is_string($method)) { | |
throw new \Exception('invalid method defined for '.$field); | |
} | |
if (!method_exists($obj, $method)) { | |
throw new \Exception('method '.$method.' does not exists for '.$field); | |
} | |
$strValue = $obj->$method($strValue); | |
continue; | |
} | |
throw new \Exception('invalid callback defined for '.$field); | |
} | |
$row[] = $strValue; | |
} | |
return $row; | |
} | |
} | |
/* | |
* sample implementation | |
*/ | |
class MyCsvRow extends CsvRow { | |
public function __construct() { | |
$this->utils = new MyUtilsClass(); | |
} | |
protected function getColumns() { | |
$arrColumns = array(); | |
$arrColumns['field1'] = array( | |
'trim', | |
'intval', | |
array($this, 'my_method'), | |
); | |
$arrColumns['field2'] = array( | |
array($this->utils, 'pad_10') | |
); | |
return $arrColumns; | |
} | |
protected function my_method($strValue) { | |
return $strValue.'xxxxx'; | |
} | |
} | |
class MyUtilsClass { | |
public function pad_10($strValue) { | |
return sprintf("%-10s", $strValue); | |
} | |
} | |
/*** | |
* sample code | |
*/ | |
$source = array( | |
array('field1' => ' 3 ', 'field2' => ' 3 '), | |
array('field1' => ' 42 ', 'field2' => 'adsdas'), | |
); | |
$destination = array(); | |
foreach ($source as $row) { | |
$objCsvRow = new MyCsvRow(); | |
$singleRow = $objCsvRow->parse($row); | |
/** | |
* you can now pass singleRow to fputcsv function | |
*/ | |
/** | |
* only for demonstration purpose | |
*/ | |
$destination[] = $singleRow; | |
} | |
var_dump($destination); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment