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 55use ErrorException ;
66use FilesystemIterator ;
77use Illuminate \Contracts \Filesystem \FileNotFoundException ;
8+ use Illuminate \Support \LazyCollection ;
89use Illuminate \Support \Traits \Macroable ;
910use RuntimeException ;
11+ use SplFileObject ;
1012use Symfony \Component \Filesystem \Filesystem as SymfonyFilesystem ;
1113use Symfony \Component \Finder \Finder ;
1214use 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 *
Original file line number Diff line number Diff line change 66use Illuminate \Filesystem \Filesystem ;
77use Illuminate \Filesystem \FilesystemManager ;
88use Illuminate \Foundation \Application ;
9+ use Illuminate \Support \LazyCollection ;
910use Illuminate \Testing \Assert ;
1011use Mockery as m ;
1112use 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 )->map ('trim ' )->all ()
78+ );
79+ }
80+
5981 public function testReplaceCreatesFile ()
6082 {
6183 $ tempFile = self ::$ tempDir .'/file.txt ' ;
You can’t perform that action at this time.
0 commit comments