PageRenderTime 89ms CodeModel.GetById 38ms app.highlight 34ms RepoModel.GetById 14ms app.codeStats 0ms

/application/datamapper/csv.php

https://bitbucket.org/alexdeoliveira/ignitercms
PHP | 225 lines | 139 code | 24 blank | 62 comment | 25 complexity | 291f4cdd6a72a0c249f59190fd8d9160 MD5 | raw file
  1<?php
  2
  3/**
  4 * CSV Extension for DataMapper classes.
  5 *
  6 * Quickly import and export a set of DataMapper models to-and-from CSV files.
  7 *
  8 * @license 	MIT License
  9 * @package		DMZ-Included-Extensions
 10 * @category	DMZ
 11 * @author  	Phil DeJarnett
 12 * @link    	http://www.overzealous.com/dmz/pages/extensions/csv.html
 13 * @version 	1.0
 14 */
 15
 16// --------------------------------------------------------------------------
 17
 18/**
 19 * DMZ_CSV Class
 20 *
 21 * @package		DMZ-Included-Extensions
 22 */
 23class DMZ_CSV {
 24	
 25	/**
 26	 * Convert a DataMapper model into an associative array.
 27	 * 
 28	 * @param	DataMapper $object The DataMapper Object to export
 29	 * @param	mixed filename The filename to export to, or a file pointer. If this is a file pointer, it will not be closed.
 30	 * @param	array $fields Array of fields to include.  If empty, includes all database columns.
 31	 * @param	bool $include_header If FALSE the header is not exported with the CSV. Not recommended if planning to import this data.
 32	 * @return	bool TRUE on success, or FALSE on failure.
 33	 */
 34	function csv_export($object, $filename, $fields = '', $include_header = TRUE)
 35	{
 36		// determine the correct field set.
 37		if(empty($fields))
 38		{
 39			$fields = $object->fields;
 40		}
 41		
 42		$success = TRUE;
 43		
 44		// determine if we need to open the file or not.
 45		if(is_string($filename))
 46		{
 47			// open the file, if possible.
 48			$fp = fopen($filename, 'w');
 49			if($fp === FALSE)
 50			{
 51				log_message('error', 'CSV Extension: Unable to open file ' . $filename);
 52				return FALSE;
 53			}
 54		}
 55		else
 56		{
 57			// assume file pointer.
 58			$fp = $filename;
 59		}
 60		
 61		if($include_header)
 62		{
 63			// Print out header line
 64			$success = fputcsv($fp, $fields);
 65		}
 66		
 67		if($success)
 68		{
 69			foreach($object as $o)
 70			{
 71				// convert each object into an array
 72				$result = array();
 73				foreach($fields as $f)
 74				{
 75					$result[] = $o->{$f};
 76				}
 77				// output CSV-formatted line
 78				$success = fputcsv($fp, $result);
 79				if(!$success)
 80				{
 81					// stop on first failure.
 82					break;
 83				}
 84			}
 85		}
 86		
 87		if(is_string($filename))
 88		{
 89			fclose($fp);
 90		}
 91		
 92		return $success;
 93	}
 94	
 95	/**
 96	 * Import objects from a CSV file.
 97	 * 
 98	 * Completely empty rows are automatically skipped, as are rows that
 99	 * start with a # sign (assumed to be comments).
100	 * 
101	 * @param	DataMapper $object The type of DataMapper Object to import
102	 * @param	mixed $filename Name of CSV file, or a file pointer.
103	 * @param	array $fields If empty, the database fields are used.  Otherwise used to limit what fields are saved.
104	 * @param	boolean $header_row If true, the first line is assumed to be a header row.  Defaults to true.
105	 * @param	mixed $callback A callback method for each row.  Can return FALSE on failure to save, or 'stop' to stop the import.
106	 * @return	array Array of imported objects, or FALSE if unable to import.
107	 */
108	function csv_import($object, $filename, $fields = '', $header_row = TRUE, $callback = NULL)
109	{
110		$class = get_class($object);
111		
112		if(empty($fields))
113		{
114			$fields = $object->fields;
115		}
116		
117		// determine if we need to open the file or not.
118		if(is_string($filename))
119		{
120			// open the file, if possible.
121			$fp = fopen($filename, 'r');
122			if($fp === FALSE)
123			{
124				log_message('error', 'CSV Extension: Unable to open file ' . $filename);
125				return FALSE;
126			}
127		}
128		else
129		{
130			// assume file pointer.
131			$fp = $filename;
132		}
133		
134		if(empty($callback))
135		{
136			$result = array();			
137		}
138		else
139		{
140			$result = 0;
141		}
142		$columns = NULL;
143		
144		while(($data = fgetcsv($fp)) !== FALSE)
145		{
146			// get column names
147			if(is_null($columns))
148			{
149				if($header_row)
150				{
151					// store header row for column names
152					$columns = $data;
153					// only include columns in $fields
154					foreach($columns as $index => $name)
155					{
156						if( ! in_array($name, $fields))
157						{
158							// mark column as false to skip
159							$columns[$index] = FALSE;
160						}
161					}
162					continue;
163				}
164				else
165				{
166					$columns = $fields;
167				}
168			}
169			
170			// skip on comments and empty rows
171			if(empty($data) || $data[0][0] == '#' || implode('', $data) == '')
172			{
173				continue;
174			}
175			
176			// create the object to save
177			$o = new $class();
178			foreach($columns as $index => $key)
179			{
180				if(count($data) <= $index)
181				{
182					// more header columns than data columns
183					break;
184				}
185				
186				// skip columns that were determined to not be needed above.
187				if($key === FALSE)
188				{
189					continue;
190				}
191				
192				// finally, it's OK to save the data column.
193				$o->{$key} = $data[$index];
194			}
195			
196			if( empty($callback))
197			{
198				$result[] = $o;
199			}
200			else
201			{
202				$test = call_user_func($callback, $o);
203				if($test === 'stop')
204				{
205					break;
206				}
207				if($test !== FALSE)
208				{
209					$result++;
210				}
211			}
212		}
213		
214		if(is_string($filename))
215		{
216			fclose($fp);
217		}
218		
219		return $result;
220	}
221	
222}
223
224/* End of file csv.php */
225/* Location: ./application/datamapper/csv.php */