From 154fef3031ac33d1c47160e99af3a0526d9721d5 Mon Sep 17 00:00:00 2001 From: Joseph Silber Date: Mon, 7 Sep 2020 11:44:57 -0400 Subject: [PATCH] Add Files::lines($path) --- src/Illuminate/Filesystem/Filesystem.php | 29 ++++++++++++++++++++++++ tests/Filesystem/FilesystemTest.php | 22 ++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/Illuminate/Filesystem/Filesystem.php b/src/Illuminate/Filesystem/Filesystem.php index be9bb4b5b96c..9dbe8ebae1b8 100644 --- a/src/Illuminate/Filesystem/Filesystem.php +++ b/src/Illuminate/Filesystem/Filesystem.php @@ -5,8 +5,10 @@ use ErrorException; use FilesystemIterator; use Illuminate\Contracts\Filesystem\FileNotFoundException; +use Illuminate\Support\LazyCollection; use Illuminate\Support\Traits\Macroable; use RuntimeException; +use SplFileObject; use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Mime\MimeTypes; @@ -84,6 +86,33 @@ public function sharedGet($path) return $contents; } + /** + * Get the contents of a file, one line at a time. + * + * @param string $path + * @return \Illuminate\Support\LazyCollection + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + public function lines($path) + { + if (! $this->isFile($path)) { + throw new FileNotFoundException( + "File does not exist at path {$path}." + ); + } + + return LazyCollection::make(function () use ($path) { + $file = new SplFileObject($path); + + $file->setFlags(SplFileObject::DROP_NEW_LINE); + + while (! $file->eof()) { + yield $file->fgets(); + } + }); + } + /** * Get the returned value of a file. * diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index 3b2fa7b77123..d1ff89f680ce 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -6,6 +6,7 @@ use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\FilesystemManager; use Illuminate\Foundation\Application; +use Illuminate\Support\LazyCollection; use Illuminate\Testing\Assert; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -56,6 +57,27 @@ public function testPutStoresFiles() $this->assertStringEqualsFile(self::$tempDir.'/file.txt', 'Hello World'); } + public function testLines() + { + $path = self::$tempDir.'/file.txt'; + + $contents = LazyCollection::times(3) + ->map(function ($number) { + return "line-{$number}"; + }) + ->join("\n"); + + file_put_contents($path, $contents); + + $files = new Filesystem; + $this->assertInstanceOf(LazyCollection::class, $files->lines($path)); + + $this->assertSame( + ['line-1', 'line-2', 'line-3'], + $files->lines($path)->all() + ); + } + public function testReplaceCreatesFile() { $tempFile = self::$tempDir.'/file.txt';