Skip to content

Commit cfe76cf

Browse files
committed
Merge branch 'files-lines' into 8.x
2 parents 708d816 + b3bea36 commit cfe76cf

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;
@@ -132,6 +134,33 @@ public function requireOnce($path, array $data = [])
132134
throw new FileNotFoundException("File does not exist at path {$path}.");
133135
}
134136

137+
/**
138+
* Get the contents of a file one line at a time.
139+
*
140+
* @param string $path
141+
* @return \Illuminate\Support\LazyCollection
142+
*
143+
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
144+
*/
145+
public function lines($path)
146+
{
147+
if (! $this->isFile($path)) {
148+
throw new FileNotFoundException(
149+
"File does not exist at path {$path}."
150+
);
151+
}
152+
153+
return LazyCollection::make(function () use ($path) {
154+
$file = new SplFileObject($path);
155+
156+
$file->setFlags(SplFileObject::DROP_NEW_LINE);
157+
158+
while (! $file->eof()) {
159+
yield $file->fgets();
160+
}
161+
});
162+
}
163+
135164
/**
136165
* Get the MD5 hash of the file at the given path.
137166
*

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)