Skip to content

Instantly share code, notes, and snippets.

@abdoulmouctard
Last active September 20, 2023 19:03
Show Gist options
  • Save abdoulmouctard/90e91b74a6b420111c2308492fcff33c to your computer and use it in GitHub Desktop.
Save abdoulmouctard/90e91b74a6b420111c2308492fcff33c to your computer and use it in GitHub Desktop.
Laravel Lazy Collection From CSV
<?php
LazyCollection::macro("fromCsv", function (string $path, int $chunk = 0, string $separator = ";"): LazyCollection {
/** @var LazyCollection $collection */
$collection = static::make(function () use (&$separator, &$path, &$chunk) {
$handle = fopen($path, 'r');
while ($line = fgetcsv(stream: $handle, separator: $separator)) {
yield array_map(fn ($item) => trim($item), $line);
}
});
return $chunk > 0 ? $collection->chunk($chunk) : $collection;
});
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment