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 $publicDirectory; |
12
|
|
|
|
13
|
|
|
protected $defer = false; |
14
|
|
|
protected $async = false; |
15
|
|
|
|
16
|
7 |
|
public function __construct( |
17
|
|
|
string $publicDirectory |
18
|
|
|
) { |
19
|
7 |
|
$this->publicDirectory = $publicDirectory; |
20
|
7 |
|
} |
21
|
|
|
|
22
|
2 |
|
public function name(): string |
23
|
|
|
{ |
24
|
2 |
|
return 'js'; |
25
|
|
|
} |
26
|
|
|
|
27
|
4 |
|
public function link(string $src): string |
28
|
|
|
{ |
29
|
4 |
|
[$url, $content] = $this->parseSource($src); |
|
|
|
|
30
|
|
|
|
31
|
4 |
|
$script = "<script src=\"{$url}\""; |
32
|
|
|
|
33
|
4 |
|
if ($this->defer) { |
34
|
2 |
|
$script .= ' defer'; |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
if ($this->async) { |
38
|
1 |
|
$script .= ' async'; |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
$script .= "></script>"; |
42
|
|
|
|
43
|
4 |
|
return $script; |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
public function inline(string $src): string |
47
|
|
|
{ |
48
|
1 |
|
[$url, $content] = $this->parseSource($src); |
|
|
|
|
49
|
|
|
|
50
|
1 |
|
return '<script>' . $content . '</script>'; |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
public function defer(): Js |
54
|
|
|
{ |
55
|
2 |
|
$this->defer = true; |
56
|
|
|
|
57
|
2 |
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
public function async(): Js |
61
|
|
|
{ |
62
|
1 |
|
$this->async = true; |
63
|
|
|
|
64
|
1 |
|
return $this; |
65
|
|
|
} |
66
|
|
|
|
67
|
6 |
|
public function parseSource(string $src): array |
68
|
|
|
{ |
69
|
6 |
|
$src = ltrim($src, '/'); |
70
|
|
|
|
71
|
6 |
|
['dirname' => $dirname, 'filename' => $filename, 'extension' => $extension] = pathinfo($src); |
|
|
|
|
72
|
|
|
|
73
|
6 |
|
$content = File::read($src); |
74
|
|
|
|
75
|
6 |
|
$path = "{$dirname}/{$filename}.{$extension}"; |
76
|
|
|
|
77
|
6 |
|
$this->saveFile($path, $content); |
78
|
|
|
|
79
|
6 |
|
return ["/{$path}", $content]; |
80
|
|
|
} |
81
|
|
|
|
82
|
6 |
|
protected function saveFile(string $path, string $content): void |
83
|
|
|
{ |
84
|
6 |
|
$fs = new Filesystem(); |
85
|
|
|
|
86
|
6 |
|
$fs->dumpFile( |
87
|
6 |
|
File::path("{$this->publicDirectory}/{$path}"), |
88
|
6 |
|
$content |
89
|
|
|
); |
90
|
6 |
|
} |
91
|
|
|
} |
92
|
|
|
|
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.