2
2
3
3
namespace BayAreaWebPro \SimpleCsv ;
4
4
5
- use Iterator ;
6
- use SplFileObject ;
5
+ use \Iterator ;
6
+ use \SplFileObject ;
7
+ use \Exception ;
7
8
use Illuminate \Support \Collection ;
8
9
use Illuminate \Support \LazyCollection ;
9
10
use Symfony \Component \HttpFoundation \StreamedResponse ;
@@ -14,19 +15,8 @@ class SimpleCsvService
14
15
const ENCLOSURE = '" ' ;
15
16
const ESCAPE = '\\' ;
16
17
17
- /**
18
- * @var string
19
- */
20
18
protected $ delimiter , $ enclosure , $ escape ;
21
-
22
- /**
23
- * @var array|null
24
- */
25
19
protected $ headers ;
26
-
27
- /**
28
- * @var SplFileObject|null
29
- */
30
20
protected $ file ;
31
21
32
22
public function __construct (
@@ -52,9 +42,16 @@ public function import(string $path): LazyCollection
52
42
yield array_combine ($ this ->headers , $ line );
53
43
}
54
44
}
45
+ $ this ->resetState ();
55
46
});
56
47
}
57
48
49
+ protected function resetState (): void
50
+ {
51
+ $ this ->headers = null ;
52
+ $ this ->file = null ;
53
+ }
54
+
58
55
protected function isInValidLine (array $ line ): bool
59
56
{
60
57
return count ($ line ) === 1 && is_null ($ line [0 ]);
@@ -65,7 +62,7 @@ public function export($collection, string $path): self
65
62
if (!file_exists ($ path )) touch ($ path );
66
63
$ this ->openFileObject ($ path , 'w ' );
67
64
$ this ->writeLines ($ collection );
68
- $ this ->closeFileObject ();
65
+ $ this ->resetState ();
69
66
return $ this ;
70
67
}
71
68
@@ -74,9 +71,9 @@ public function download($collection, string $filename, $headers = []): Streamed
74
71
return response ()->streamDownload (function () use ($ collection ) {
75
72
$ this ->openFileObject ('php://output ' , 'w ' );
76
73
$ this ->writeLines ($ collection );
77
- $ this ->closeFileObject ();
74
+ $ this ->resetState ();
78
75
}, $ filename , array_merge ([
79
- 'Content-Type ' => 'text/csv ' ,
76
+ 'Content-Type ' => 'text/csv ' ,
80
77
], $ headers ));
81
78
}
82
79
@@ -97,12 +94,7 @@ protected function flattenRow($entry): array
97
94
98
95
protected function openFileObject (string $ path , string $ mode = 'r ' ): void
99
96
{
100
- $ this ->file = new \SplFileObject ($ path , $ mode );
101
- }
102
-
103
- protected function closeFileObject (): void
104
- {
105
- $ this ->file = null ;
97
+ $ this ->file = new SplFileObject ($ path , $ mode );
106
98
}
107
99
108
100
protected function writeLines ($ collection ): void
@@ -113,7 +105,7 @@ protected function writeLines($collection): void
113
105
!$ collection instanceof LazyCollection &&
114
106
!is_array ($ collection )
115
107
) {
116
- throw new \ Exception ("Non-Iterable Object cannot be iterated. " );
108
+ throw new Exception ("Non-Iterable Object cannot be iterated. " );
117
109
}
118
110
foreach ($ collection as $ entry ) {
119
111
if (!$ this ->headers ) {
0 commit comments