Skip to content

Commit e2f60bc

Browse files
committed
fix: creating of file when directory does not exists
1 parent aa171e3 commit e2f60bc

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/CsvFile.php

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
namespace Yajra\SQLLoader;
66

7+
use Illuminate\Support\Facades\File;
8+
79
final class CsvFile
810
{
911
/**
@@ -15,34 +17,35 @@ private function __construct(public string $file, public $stream)
1517

1618
public static function make(string $filename, string $mode): CsvFile
1719
{
18-
if (! file_exists($filename)) {
19-
$filename = self::create($filename);
20-
}
20+
$csv = self::create($filename);
2121

22-
$stream = fopen($filename, $mode);
22+
$stream = fopen($csv, $mode);
2323

2424
if ($stream === false) {
25-
throw new \RuntimeException("Failed to open file [{$filename}].");
25+
throw new \RuntimeException("Failed to open file [{$csv}].");
2626
}
2727

28-
return new self($filename, $stream);
28+
return new self($csv, $stream);
2929
}
3030

3131
public static function create(string $file): string
3232
{
33-
$stream = fopen($file, 'w');
34-
if ($stream === false) {
35-
throw new \RuntimeException('Could not open file for writing: '.$file);
33+
$directory = File::dirname($file);
34+
if (! File::isDirectory($directory)) {
35+
File::makeDirectory($directory, 0755, true, true);
36+
}
37+
38+
if (! File::exists($file)) {
39+
File::append($file, '');
3640
}
37-
fclose($stream);
3841

3942
return $file;
4043
}
4144

4245
public static function blank(string $file): string
4346
{
44-
if (file_exists($file)) {
45-
unlink($file);
47+
if (File::exists($file)) {
48+
File::delete($file);
4649
}
4750

4851
return self::create($file);

0 commit comments

Comments
 (0)