public
Last active

Decorate Iterators - CSV Data Example

  • Download Gist
csv-keyed-spl.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
<?php
/**
* @link http://stackoverflow.com/q/10181054/367456
*/
 
 
/**
* Extending from a TraversableDecorator allows to decorate (change) the Iterator
* being Traversed without changing the object.
*/
abstract class TraversableDecorator implements Iterator
{
protected $subject;
 
 
public function __construct($subject) {
if (is_array($subject)) {
$subject = new ArrayIterator($subject);
} elseif (($subject instanceof Traversable) and !($subject instanceof iterator)) {
$subject = new IteratorIterator($subject);
}
$this->subject = $subject;
}
 
public function current() {
return $this->subject->current();
}
 
public function next() {
$this->subject->next();
}
 
public function key() {
return $this->subject->key();
}
 
public function valid() {
return $this->subject->valid();
}
 
public function rewind() {
$this->subject->rewind();
}
 
function __call($name, $arguments) {
return call_user_func_array([$this->subject, $name], $arguments);
}
 
function __get($name) {
return $this->subject->$name;
}
 
function __set($name, $value) {
$this->subject->$name = $value;
}
 
function __isset($name) {
return isset($this->subject->$name);
}
}
 
/**
* Decoration for the TraversableDecorator
*/
abstract class TraversableDecoration extends IteratorIterator
{
public function __construct() {
}
 
public function setIterator(Traversable $iterator) {
parent::__construct($iterator);
}
}
 
 
/**
* Decoration for skipping lines that are like the one given
*/
class SkipLines extends TraversableDecoration
{
private $like;
 
public function __construct(array $like) {
$this->like = $like;
}
 
public function next() {
parent::next();
while(parent::valid()) {
if (parent::current() !== $this->like) break;
parent::next();
}
}
}
 
/**
* Decoration for skipping empty lines
*/
class SkipEmptyLines extends SkipLines
{
public function __construct() {
parent::__construct([null]);
}
}
 
/**
* Decoration for setting field names
*/
class FieldNames extends TraversableDecoration
{
private $fieldNames;
 
public function __construct(array $fieldNames = null) {
$this->fieldNames = $fieldNames;
}
 
public function current() {
if ($this->fieldNames) {
return array_combine($this->fieldNames, parent::current());
}
return parent::current();
}
 
public function setFieldNames(array $fieldNames) {
$this->fieldNames = $fieldNames;
}
 
public function getFieldNames() {
return $this->fieldNames;
}
}
 
 
/**
* Decoration for having field names in the first row
*/
class FieldNamesInFirstRow extends FieldNames
{
public function rewind() {
parent::rewind();
$fieldNames = parent::current();
parent::setFieldNames($fieldNames);
parent::next();
}
}
 
 
/**
* CsvFile
*/
class CsvFile extends TraversableDecorator
{
/**
* @var Traversable
*/
private $file;
 
public function __construct($file = null) {
$this->file = $this->filterInput($file);
parent::__construct($this->file);
$this->decorateWith(new SkipEmptyLines());
}
 
public function getFile() {
return $this->file;
}
 
public function decorateWith(TraversableDecoration $iterator) {
$iterator->setIterator($this->subject);
$this->subject = $iterator;
}
 
public function removeDecoration() {
parent::__construct($this->file);
}
 
/**
* @param mixed $file
* @return Traversable
* @throws InvalidArgumentException
*/
private function filterInput($file) {
 
if (null === $file) {
$file = new SplTempFileObject();
}
 
if (is_string($file)) {
try {
$file = new SplFileObject($file);
} catch (InvalidArgumentException $e) {
throw $e;
}
}
 
if ($file instanceof SplFileObject) {
$file->setFlags(SplFileObject::READ_CSV);
}
 
return $file;
}
}
 
 
/**
* small helper function to display a csv file
* @param CsvFile $csv
*/
$echoCsvFile = function(CsvFile $csv) {
$counter = new IteratorIterator($csv);
printf("CSV File with %d Line(s):\n", iterator_count($counter));
foreach ($csv as $i => $line) {
echo "$i:|";
foreach($line as $key => $value) {
($value === NULL) && $value = 'NULL';
echo "$key: $value|";
}
echo "\n";
}
};
 
 
// Create a Temporary in-memory CSV file with two-line sample data
// and an empty line at the end
// Note: PHP eats non-standard \n for standard \r\n
$csv = new CsvFile();
/* @var $file SplTempFileObject */
$file = $csv->getFile();
$file->fwrite("A1,B1,C1\nA2,B2,C2\n\n");
 
$echoCsvFile($csv);
 
// as the example shows empty lines are dropped automatically as those
// are normally inside files in common scenarios, but this can be
// removed:
$csv->removeDecoration();
$echoCsvFile($csv);
 
// and added again:
$csv->decorateWith(new SkipEmptyLines());
$echoCsvFile($csv);
 
// for the moment take the CSV file as is and ignore empty lines
// this works because CsvFile can not only operate on an SplFileObject
// but anything that is Traversable
$csv = new CsvFile($csv);
 
// but tell that the first line contains the field names
$csv->decorateWith(new FieldNamesInFirstRow());
$echoCsvFile($csv);
 
// Let's change the field names, because in their current form it's not
// that nice
$csv->decorateWith(new FieldNames(['A', 'B', 'C']));
$echoCsvFile($csv);
 
// A full blown example
$csvData = <<<CSV
"Make","Model","Note"
"Chevy","1500","loaded"
"Chevy","2500",""
"Chevy","","loaded"
CSV;
 
$path = 'data://text/plain,' . $csvData;
 
$csv = new CsvFile($path);
 
$csv->decorateWith(new FieldNamesInFirstRow());
$echoCsvFile($csv);
 
// $csv->decorateWith(new SkipLines(["Chevy", "2500", ""]));
// $csv->decorateWith();
// $csv->decorateWith(new FieldNames(['make', 'model', 'note']));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.