1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the "andrey-helldar/support" project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
* |
8
|
|
|
* @author Andrey Helldar <[email protected]> |
9
|
|
|
* |
10
|
|
|
* @copyright 2021 Andrey Helldar |
11
|
|
|
* |
12
|
|
|
* @license MIT |
13
|
|
|
* |
14
|
|
|
* @see https://github.com/andrey-helldar/support |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
namespace Helldar\Support\Tools; |
18
|
|
|
|
19
|
|
|
use Helldar\Support\Exceptions\UnknownStubFileException; |
20
|
|
|
use Helldar\Support\Facades\Helpers\Str; |
21
|
|
|
|
22
|
|
|
class Stub |
23
|
|
|
{ |
24
|
|
|
public const PHP_ARRAY = 'php_array.stub'; |
25
|
|
|
|
26
|
|
|
public const JSON = 'json.stub'; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Replace the contents of the template file. |
30
|
|
|
* |
31
|
|
|
* @param string $stub_file |
32
|
|
|
* @param array $replace |
33
|
|
|
* |
34
|
|
|
* @throws \Helldar\Support\Exceptions\UnknownStubFileException |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
16 |
|
public function replace(string $stub_file, array $replace): string |
39
|
|
|
{ |
40
|
16 |
|
$content = $this->get($stub_file); |
41
|
|
|
|
42
|
16 |
|
return Str::replace($content, $replace); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Receive the contents of the template file. |
47
|
|
|
* |
48
|
|
|
* @param string $filename |
49
|
|
|
* |
50
|
|
|
* @throws \Helldar\Support\Exceptions\UnknownStubFileException |
51
|
|
|
* |
52
|
|
|
* @return string |
53
|
|
|
*/ |
54
|
24 |
|
public function get(string $filename): string |
55
|
|
|
{ |
56
|
24 |
|
if ($path = $this->path($filename)) { |
57
|
22 |
|
return file_get_contents($path); |
58
|
|
|
} |
59
|
|
|
|
60
|
2 |
|
throw new UnknownStubFileException($filename); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Receive the path to the template file. |
65
|
|
|
* |
66
|
|
|
* @param string $filename |
67
|
|
|
* |
68
|
|
|
* @return string|null |
69
|
|
|
*/ |
70
|
24 |
|
protected function path(string $filename): ?string |
71
|
|
|
{ |
72
|
24 |
|
$path = $this->isCustom($filename) ? $filename : __DIR__ . '/../../resources/stubs/' . $filename; |
73
|
|
|
|
74
|
24 |
|
return realpath($path); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Returns a link to the template file. |
79
|
|
|
* |
80
|
|
|
* If the file exists under the specified link, it will return it, |
81
|
|
|
* otherwise it will search in the default folder. |
82
|
|
|
* |
83
|
|
|
* @param string $path |
84
|
|
|
* |
85
|
|
|
* @return bool |
86
|
|
|
*/ |
87
|
24 |
|
protected function isCustom(string $path): bool |
88
|
|
|
{ |
89
|
24 |
|
return file_exists($path); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|