1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Rawilk\LaravelModules\Generators; |
4
|
|
|
|
5
|
|
|
use Illuminate\Filesystem\Filesystem; |
6
|
|
|
use Rawilk\LaravelModules\Exceptions\FileAlreadyExists; |
7
|
|
|
|
8
|
|
|
class FileGenerator extends Generator |
9
|
|
|
{ |
10
|
|
|
/** @var string */ |
11
|
|
|
protected $contents; |
12
|
|
|
|
13
|
|
|
/** @var \Illuminate\Filesystem\Filesystem */ |
14
|
|
|
protected $filesystem; |
15
|
|
|
|
16
|
|
|
/** @var bool */ |
17
|
|
|
private $overwriteFile; |
18
|
|
|
|
19
|
|
|
/** @var string */ |
20
|
|
|
protected $path; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string $path |
24
|
|
|
* @param string $contents |
25
|
|
|
* @param null|\Illuminate\Filesystem\Filesystem $filesystem |
26
|
|
|
*/ |
27
|
|
|
public function __construct(string $path, string $contents, ?Filesystem $filesystem = null) |
28
|
|
|
{ |
29
|
|
|
$this->path = $path; |
30
|
|
|
$this->contents = $contents; |
31
|
|
|
$this->filesystem = $filesystem ?: new Filesystem; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function generate() |
35
|
|
|
{ |
36
|
|
|
$path = $this->getPath(); |
37
|
|
|
|
38
|
|
|
if (! $this->filesystem->exists($path)) { |
39
|
|
|
return $this->filesystem->put($path, $this->getContents()); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if ($this->overwriteFile) { |
43
|
|
|
return $this->filesystem->put($path, $this->getContents()); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
throw new FileAlreadyExists('File already exists!'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getContents(): string |
50
|
|
|
{ |
51
|
|
|
return $this->contents; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getFilesystem(): Filesystem |
55
|
|
|
{ |
56
|
|
|
return $this->filesystem; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getPath(): string |
60
|
|
|
{ |
61
|
|
|
return $this->path; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function setContents(string $contents): self |
65
|
|
|
{ |
66
|
|
|
$this->contents = $contents; |
67
|
|
|
|
68
|
|
|
return $this; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function setFilesystem(Filesystem $filesystem): self |
72
|
|
|
{ |
73
|
|
|
$this->filesystem = $filesystem; |
74
|
|
|
|
75
|
|
|
return $this; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function setPath(string $path): self |
79
|
|
|
{ |
80
|
|
|
$this->path = $path; |
81
|
|
|
|
82
|
|
|
return $this; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
public function withFileOverwrite(bool $overwrite = true): self |
86
|
|
|
{ |
87
|
|
|
$this->overwriteFile = $overwrite; |
88
|
|
|
|
89
|
|
|
return $this; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|