FileGenerator::generate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 3
nop 0
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