22
33namespace BayAreaWebPro \SimpleCsv ;
44
5- use Iterator ;
6- use SplFileObject ;
5+ use \Iterator ;
6+ use \SplFileObject ;
7+ use \Exception ;
78use Illuminate \Support \Collection ;
89use Illuminate \Support \LazyCollection ;
910use Symfony \Component \HttpFoundation \StreamedResponse ;
@@ -14,19 +15,8 @@ class SimpleCsvService
1415 const ENCLOSURE = '" ' ;
1516 const ESCAPE = '\\' ;
1617
17- /**
18- * @var string
19- */
2018 protected $ delimiter , $ enclosure , $ escape ;
21-
22- /**
23- * @var array|null
24- */
2519 protected $ headers ;
26-
27- /**
28- * @var SplFileObject|null
29- */
3020 protected $ file ;
3121
3222 public function __construct (
@@ -52,9 +42,16 @@ public function import(string $path): LazyCollection
5242 yield array_combine ($ this ->headers , $ line );
5343 }
5444 }
45+ $ this ->resetState ();
5546 });
5647 }
5748
49+ protected function resetState (): void
50+ {
51+ $ this ->headers = null ;
52+ $ this ->file = null ;
53+ }
54+
5855 protected function isInValidLine (array $ line ): bool
5956 {
6057 return count ($ line ) === 1 && is_null ($ line [0 ]);
@@ -65,7 +62,7 @@ public function export($collection, string $path): self
6562 if (!file_exists ($ path )) touch ($ path );
6663 $ this ->openFileObject ($ path , 'w ' );
6764 $ this ->writeLines ($ collection );
68- $ this ->closeFileObject ();
65+ $ this ->resetState ();
6966 return $ this ;
7067 }
7168
@@ -74,9 +71,9 @@ public function download($collection, string $filename, $headers = []): Streamed
7471 return response ()->streamDownload (function () use ($ collection ) {
7572 $ this ->openFileObject ('php://output ' , 'w ' );
7673 $ this ->writeLines ($ collection );
77- $ this ->closeFileObject ();
74+ $ this ->resetState ();
7875 }, $ filename , array_merge ([
79- 'Content-Type ' => 'text/csv ' ,
76+ 'Content-Type ' => 'text/csv ' ,
8077 ], $ headers ));
8178 }
8279
@@ -100,12 +97,6 @@ protected function openFileObject(string $path, string $mode = 'r'): void
10097 $ this ->file = new \SplFileObject ($ path , $ mode );
10198 }
10299
103- protected function closeFileObject (): void
104- {
105- $ this ->file = null ;
106- $ this ->headers = null ;
107- }
108-
109100 protected function writeLines ($ collection ): void
110101 {
111102 if (
@@ -114,15 +105,14 @@ protected function writeLines($collection): void
114105 !$ collection instanceof LazyCollection &&
115106 !is_array ($ collection )
116107 ) {
117- throw new \ Exception ("Non-Iterable Object cannot be iterated. " );
108+ throw new Exception ("Non-Iterable Object cannot be iterated. " );
118109 }
119110 foreach ($ collection as $ entry ) {
120111 if (!$ this ->headers ) {
121112 $ this ->headers = array_keys ($ this ->flattenRow ($ entry ));
122113 $ this ->writeLine ($ this ->headers );
123114 }
124115 $ this ->writeLine (array_values ($ this ->flattenRow ($ entry )));
125- unset($ entry );
126116 }
127117 }
128118}
0 commit comments