Skip to content

Instantly share code, notes, and snippets.

@mysiar
Created April 2, 2019 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mysiar/8c7976807ee61be0179c0f28f491e0cf to your computer and use it in GitHub Desktop.
Save mysiar/8c7976807ee61be0179c0f28f491e0cf to your computer and use it in GitHub Desktop.
CsvIterator
<?php
declare(strict_types=1);
namespace mysiar;
use Exception;
use Iterator;
class CsvIterator implements Iterator
{
private const ROW_SIZE = 4096;
/** @var resource */
private $file = null;
/** @var string */
private $delimiter = null;
/** @var mixed[] */
private $currentRecord = null;
/** @var int */
private $recordCounter = null;
/**
* CsvIterator constructor.
* @param string $file
* @param string $delimiter
* @throws Exception
*/
public function __construct(string $file, string $delimiter = ",")
{
try {
$this->file = fopen($file, 'rb');
$this->delimiter = $delimiter;
} catch (Exception $e) {
throw new Exception('Can\'t open file: ' . $file);
}
}
/**
* @return array|false|mixed|mixed[]|null
*/
public function current()
{
$this->currentRecord = fgetcsv($this->file, self::ROW_SIZE, $this->delimiter);
$this->recordCounter++;
return $this->currentRecord;
}
public function next(): bool
{
return !feof($this->file);
}
public function key(): ?int
{
return $this->recordCounter;
}
public function valid(): bool
{
if (!$this->next()) {
return false;
}
return true;
}
public function rewind(): void
{
$this->recordCounter = 0;
rewind($this->file);
}
public function __destruct()
{
fclose($this->file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment