Skip to content

Commit 154fef3

Browse files
committed
Add Files::lines($path)
1 parent 9141ccd commit 154fef3

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/Illuminate/Filesystem/Filesystem.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
use ErrorException;
66
use FilesystemIterator;
77
use Illuminate\Contracts\Filesystem\FileNotFoundException;
8+
use Illuminate\Support\LazyCollection;
89
use Illuminate\Support\Traits\Macroable;
910
use RuntimeException;
11+
use SplFileObject;
1012
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
1113
use Symfony\Component\Finder\Finder;
1214
use Symfony\Component\Mime\MimeTypes;
@@ -84,6 +86,33 @@ public function sharedGet($path)
8486
return $contents;
8587
}
8688

89+
/**
90+
* Get the contents of a file, one line at a time.
91+
*
92+
* @param string $path
93+
* @return \Illuminate\Support\LazyCollection
94+
*
95+
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
96+
*/
97+
public function lines($path)
98+
{
99+
if (! $this->isFile($path)) {
100+
throw new FileNotFoundException(
101+
"File does not exist at path {$path}."
102+
);
103+
}
104+
105+
return LazyCollection::make(function () use ($path) {
106+
$file = new SplFileObject($path);
107+
108+
$file->setFlags(SplFileObject::DROP_NEW_LINE);
109+
110+
while (! $file->eof()) {
111+
yield $file->fgets();
112+
}
113+
});
114+
}
115+
87116
/**
88117
* Get the returned value of a file.
89118
*

tests/Filesystem/FilesystemTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Filesystem\Filesystem;
77
use Illuminate\Filesystem\FilesystemManager;
88
use Illuminate\Foundation\Application;
9+
use Illuminate\Support\LazyCollection;
910
use Illuminate\Testing\Assert;
1011
use Mockery as m;
1112
use PHPUnit\Framework\TestCase;
@@ -56,6 +57,27 @@ public function testPutStoresFiles()
5657
$this->assertStringEqualsFile(self::$tempDir.'/file.txt', 'Hello World');
5758
}
5859

60+
public function testLines()
61+
{
62+
$path = self::$tempDir.'/file.txt';
63+
64+
$contents = LazyCollection::times(3)
65+
->map(function ($number) {
66+
return "line-{$number}";
67+
})
68+
->join("\n");
69+
70+
file_put_contents($path, $contents);
71+
72+
$files = new Filesystem;
73+
$this->assertInstanceOf(LazyCollection::class, $files->lines($path));
74+
75+
$this->assertSame(
76+
['line-1', 'line-2', 'line-3'],
77+
$files->lines($path)->all()
78+
);
79+
}
80+
5981
public function testReplaceCreatesFile()
6082
{
6183
$tempFile = self::$tempDir.'/file.txt';

0 commit comments

Comments
 (0)