1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Stitcher\Renderer\Extension; |
4
|
|
|
|
5
|
|
|
use Stitcher\File; |
6
|
|
|
use Stitcher\Renderer\Extension; |
7
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
8
|
|
|
|
9
|
|
|
class Js implements Extension |
10
|
|
|
{ |
11
|
|
|
protected $sourceDirectory; |
12
|
|
|
protected $publicDirectory; |
13
|
|
|
|
14
|
|
|
protected $defer = false; |
15
|
|
|
protected $async = false; |
16
|
|
|
|
17
|
5 |
|
public function __construct( |
18
|
|
|
string $sourceDirectory, |
19
|
|
|
string $publicDirectory |
20
|
|
|
) { |
21
|
5 |
|
$this->sourceDirectory = $sourceDirectory; |
22
|
5 |
|
$this->publicDirectory = $publicDirectory; |
23
|
5 |
|
} |
24
|
|
|
|
25
|
|
|
public function name(): string |
26
|
|
|
{ |
27
|
|
|
return 'js'; |
28
|
|
|
} |
29
|
|
|
|
30
|
3 |
|
public function link(string $src): string |
31
|
|
|
{ |
32
|
3 |
|
[$url, $content] = $this->parseSource($src); |
|
|
|
|
33
|
|
|
|
34
|
3 |
|
$script = "<script src=\"{$url}\""; |
35
|
|
|
|
36
|
3 |
|
if ($this->defer) { |
37
|
1 |
|
$script .= ' defer'; |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
if ($this->async) { |
41
|
1 |
|
$script .= ' async'; |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
$script .= "></script>"; |
45
|
|
|
|
46
|
3 |
|
return $script; |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
public function inline(string $src): string |
50
|
|
|
{ |
51
|
1 |
|
[$url, $content] = $this->parseSource($src); |
|
|
|
|
52
|
|
|
|
53
|
1 |
|
return '<script>' . $content . '</script>'; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
public function defer(): Js |
57
|
|
|
{ |
58
|
1 |
|
$this->defer = true; |
59
|
|
|
|
60
|
1 |
|
return $this; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
public function async(): Js |
64
|
|
|
{ |
65
|
1 |
|
$this->async = true; |
66
|
|
|
|
67
|
1 |
|
return $this; |
68
|
|
|
} |
69
|
|
|
|
70
|
5 |
|
public function parseSource(string $src): array |
71
|
|
|
{ |
72
|
5 |
|
$src = ltrim($src, '/'); |
73
|
|
|
|
74
|
5 |
|
['dirname' => $dirname, 'filename' => $filename, 'extension' => $extension] = pathinfo($src); |
|
|
|
|
75
|
|
|
|
76
|
5 |
|
$content = File::read("{$this->sourceDirectory}/{$src}"); |
77
|
|
|
|
78
|
5 |
|
$path = "{$dirname}/{$filename}.{$extension}"; |
79
|
|
|
|
80
|
5 |
|
$this->saveFile($path, $content); |
81
|
|
|
|
82
|
5 |
|
return ["/{$path}", $content]; |
83
|
|
|
} |
84
|
|
|
|
85
|
5 |
|
protected function saveFile(string $path, string $content): void |
86
|
|
|
{ |
87
|
5 |
|
$fs = new Filesystem(); |
88
|
|
|
|
89
|
5 |
|
$fs->dumpFile( |
90
|
5 |
|
File::path("{$this->publicDirectory}/{$path}"), |
91
|
5 |
|
$content |
92
|
|
|
); |
93
|
5 |
|
} |
94
|
|
|
} |
95
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.