Skip to content

Instantly share code, notes, and snippets.

@Modelizer
Created September 19, 2019 14:02
Show Gist options
  • Save Modelizer/7d34ccd0abba07cd929f722a2816ffa9 to your computer and use it in GitHub Desktop.
Save Modelizer/7d34ccd0abba07cd929f722a2816ffa9 to your computer and use it in GitHub Desktop.
CSV File Loader in PHP. The headers will be map as keys in collected CSV data.
<?php
use Exception;
use Illuminate\Support\Collection;
use SplFileObject;
/**
* CSV loader is a helper class to load data into Laravel Collection
*
* ----------------------------------------------------------------------------------------------------------------
* $csvLoader = CsvFileLoader::loadFromUserImportStorage('file.csv');
*
* // Fetch data from CSV
* $rows = $csvLoader->get();
*
* // It might be possible we have some invalid rows in CSV file
* if ($csvLoader->hasInvalidRow()) {
* $invalidRows = $csvLoader->getInvalidRows();
* }
* ----------------------------------------------------------------------------------------------------------------
*
* @author Mohammed Mudassir Shaikh <hello@mudasir.me>
* @license MIT
*/
class CsvFileLoader
{
/** @var SplFileObject */
protected $file;
/** @var Collection */
protected $rows;
/** @var Collection */
protected $invalidRows;
/**
* @param string $filePath
*/
public function __construct(string $filePath)
{
$this->file = new SplFileObject($filePath);
$this->rows = new Collection;
$this->invalidRows = new Collection;
$this->processFile();
}
/**
* @param string $filePath
* @return CsvFileLoader
*/
public static function loadFromUserImportStorage(string $filePath)
{
return new self(storage_path("user-imports/$filePath"));
}
/**
* @return Collection
*/
public function get()
{
return $this->rows;
}
/**
* @return Collection
*/
public function getInvalidRows()
{
return $this->invalidRows;
}
/**
* @return bool
*/
public function hasInvalidRow()
{
return $this->invalidRows->isNotEmpty();
}
/**
* @param array $row
* @return bool
*/
public function isRowEmpty(array $row)
{
return count($row) < 2 || empty($row[0]);
}
/**
* Process the CSV file
* @return void
*/
protected function processFile()
{
$header = $this->file->fgetcsv();
while (! $this->file->eof()) {
if ($this->isRowEmpty($row = $this->file->fgetcsv())) {
continue;
}
try {
$this->rows[] = array_combine($header, $row);
} catch (Exception $exception) {
$this->invalidRows[] = $row;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment