File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
src/Illuminate/Filesystem Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 5
5
use ErrorException ;
6
6
use FilesystemIterator ;
7
7
use Illuminate \Contracts \Filesystem \FileNotFoundException ;
8
+ use Illuminate \Support \LazyCollection ;
8
9
use Illuminate \Support \Traits \Macroable ;
9
10
use RuntimeException ;
11
+ use SplFileObject ;
10
12
use Symfony \Component \Filesystem \Filesystem as SymfonyFilesystem ;
11
13
use Symfony \Component \Finder \Finder ;
12
14
use Symfony \Component \Mime \MimeTypes ;
@@ -132,6 +134,33 @@ public function requireOnce($path, array $data = [])
132
134
throw new FileNotFoundException ("File does not exist at path {$ path }. " );
133
135
}
134
136
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
+
135
164
/**
136
165
* Get the MD5 hash of the file at the given path.
137
166
*
Original file line number Diff line number Diff line change 6
6
use Illuminate \Filesystem \Filesystem ;
7
7
use Illuminate \Filesystem \FilesystemManager ;
8
8
use Illuminate \Foundation \Application ;
9
+ use Illuminate \Support \LazyCollection ;
9
10
use Illuminate \Testing \Assert ;
10
11
use Mockery as m ;
11
12
use PHPUnit \Framework \TestCase ;
@@ -56,6 +57,27 @@ public function testPutStoresFiles()
56
57
$ this ->assertStringEqualsFile (self ::$ tempDir .'/file.txt ' , 'Hello World ' );
57
58
}
58
59
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
+
59
81
public function testReplaceCreatesFile ()
60
82
{
61
83
$ tempFile = self ::$ tempDir .'/file.txt ' ;
You can’t perform that action at this time.
0 commit comments