Skip to content

Instantly share code, notes, and snippets.

@nimmneun
Created July 24, 2015 17:37
Show Gist options
  • Save nimmneun/50f2c291b8f06af468d9 to your computer and use it in GitHub Desktop.
Save nimmneun/50f2c291b8f06af468d9 to your computer and use it in GitHub Desktop.
<?php
/**
* @author nimmneun
* @since 02.07.2015 22:31
*/
class CsvReader
{
private $delimiter;
private $enclosure;
private $escape;
private $lines;
private $index;
public static function load($input, $delimiter = null, $enclosure = null, $escape = null)
{
$reader = new self;
$reader->delimiter = $delimiter;
$reader->enclosure = $enclosure;
$reader->escape = $escape;
$reader->readLines($input);
return $reader;
}
private function readLines($input)
{
if (strlen($input) < 512 && is_file($input)) {
$this->lines = file($input);
} else {
$this->lines = preg_split('/[\r\n]{1}[\n]{0,1}/', $input);
}
}
private function lineToRow($index)
{
return isset($this->lines[$index])
? array_map('trim', str_getcsv(trim($this->lines[$index]), $this->delimiter, $this->enclosure, $this->escape))
: false;
}
public function next()
{
return count($this->lines) > $this->index
? $this->lineToRow(++$this->index)
: $this->lineToRow($this->index);
}
public function prev()
{
return 0 < $this->index
? $this->lineToRow(--$this->index)
: false;
}
public function filter()
{
$this->lines = array_values(array_filter($this->lines));
return $this;
}
public function offset($offset)
{
$this->index += null === $this->index ? $offset-1 : $offset;
return $this;
}
public function rewind()
{
$this->index = null;
return $this;
}
public function getLineNo()
{
return null === $this->index ? 1 : $this->index+1;
}
public function getIndexNo()
{
return null === $this->index ? 0 : $this->index;
}
public function getLineCount()
{
return count($this->lines);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment