Location: PHPKode > projects > Porte > porte-0.2.2/src/plugins/Csv.php
<?php

/**
 * Copyright (c) 2008, SARL Adaltas. All rights reserved.
 * Code licensed under the BSD License:
 * http://porte.adaltas.com/en/developer/license.html
 */

/**
 * PorteJson
 *
 * Add CSV import and export support to records or list of records by registering two new method "fromJson"
 * and "toJson" to each record.
 * 
 * @package    Porte
 * @subpackage plugin
 * @author     David Worms info(at)adaltas.com
 * @copyright  2008 Adaltas
 */
class PorteCsv{
	
	public static function _tableCallBefore($table,$method,$args){
		switch ($method){
			case 'toCsv':
				return self::toCsv($table,$args);
			case 'fromCsv':
				return self::fromCsv($table,$args);
			case 'fromCsvFile':
				return self::fromCsvFile($table,array_shift($args),count($args)?array_shift($args):array());
		}
	}
	
	public static function toCsv($table,$options){
		
	}
	
	public static function fromCsv($table,$options){
		
	}
	
	/**
	 * Available options include:
	 *  - length
	 *  - delimiter
	 *  - enclosure
	 *  - properties
	 *  - callbacks
	 *  - preg_replace
	 * @return 
	 * @param $table Object
	 * @param $file Object
	 * @param $options Object[optional]
	 */
	public static function fromCsvFile($table,$file,$options=array()){
		$options = array_merge(
			array('length'=>0,'delimiter'=>',','enclosure'=>'"','escape'=>'\\','callbacks'=>array(),'preg_replace'=>array()),
			$options);
		if(!is_readable($file)) throw new PorteException('File does not exist or is not readable: '.$file);
		$handle = fopen($file, 'r');
		$properties = isset($options['properties'])?$options['properties']:array();
		$records = array();
		while(($data=fgetcsv($handle,$options['length'],$options['delimiter'],$options['enclosure']))!==false){//,$options['escape']
			if(empty($properties)){
				$properties = $data;
				continue;
			}
			$record = array();
			$count = count($data);
			for ($i=0; $i < $count; $i++) {
				$property = $properties[$i];
				if(empty($property)) continue;
				if(!empty($options['callbacks'][$property])){
					$callback = $options['callbacks'][$property];
					$record[$property] = call_user_func_array($callback,$data[$i]);
				}else if(!empty($options['preg_replace'][$property])){
					$replace = $options['preg_replace'][$property];
					$record[$property] = preg_replace($replace[0],$replace[1],$data[$i]);
				}else{
					$record[$property] = $data[$i];
				}
			}
			$records[] = $table->load()->fromArray($record);
		}
		fclose($handle);
		return new PorteIterator($table,$records);
	}
	
}

PorteEvents::connect('table_call_before',array('PorteCsv','_tableCallBefore'));

?>
Return current item: Porte