1 | <?php |
||
2 | |||
3 | namespace Rawilk\LaravelModules\Support; |
||
4 | |||
5 | class Stub |
||
6 | { |
||
7 | /** @var null|string */ |
||
8 | protected static $basePath; |
||
9 | |||
10 | /** @var string */ |
||
11 | protected $path; |
||
12 | |||
13 | /** @var array */ |
||
14 | protected $replaces = []; |
||
15 | |||
16 | /** |
||
17 | * @param string $path |
||
18 | * @param array $replaces |
||
19 | */ |
||
20 | public function __construct(string $path, array $replaces = []) |
||
21 | { |
||
22 | $this->path = $path; |
||
23 | $this->replaces = $replaces; |
||
24 | } |
||
25 | |||
26 | public static function create(string $path, array $replaces = []): self |
||
27 | { |
||
28 | return new static($path, $replaces); |
||
29 | } |
||
30 | |||
31 | public static function getBasePath(): ?string |
||
32 | { |
||
33 | return static::$basePath; |
||
34 | } |
||
35 | |||
36 | public static function setBasePath(string $path): void |
||
37 | { |
||
38 | static::$basePath = $path; |
||
39 | } |
||
40 | |||
41 | public function getContents(): string |
||
42 | { |
||
43 | $contents = file_get_contents($this->getPath()); |
||
44 | |||
45 | foreach ($this->replaces as $key => $value) { |
||
46 | $contents = str_replace('$' . strtoupper($key) . '$', $value, $contents); |
||
47 | } |
||
48 | |||
49 | return $contents; |
||
50 | } |
||
51 | |||
52 | public function getReplaces(): array |
||
53 | { |
||
54 | return $this->replaces; |
||
55 | } |
||
56 | |||
57 | public function getPath(): string |
||
58 | { |
||
59 | $path = static::getBasePath() . $this->path; |
||
60 | |||
61 | return file_exists($path) ? $path : __DIR__ . '/../Commands/stubs' . $this->path; |
||
62 | } |
||
63 | |||
64 | public function render(): string |
||
65 | { |
||
66 | return $this->getContents(); |
||
67 | } |
||
68 | |||
69 | public function replace(array $replaces = []): self |
||
70 | { |
||
71 | $this->replaces = $replaces; |
||
72 | |||
73 | return $this; |
||
74 | } |
||
75 | |||
76 | public function saveTo(string $path, string $filename): bool |
||
77 | { |
||
78 | return file_put_contents($path . '/' . $filename, $this->getContents()); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
79 | } |
||
80 | |||
81 | public function setPath(string $path): self |
||
82 | { |
||
83 | $this->path = $path; |
||
84 | |||
85 | return $this; |
||
86 | } |
||
87 | |||
88 | public function __toString() |
||
89 | { |
||
90 | return $this->render(); |
||
91 | } |
||
92 | } |
||
93 |