1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\MixPreload; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Support\HtmlString; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
|
9
|
|
|
class RenderPreloadLinks |
10
|
|
|
{ |
11
|
|
|
/** @var array */ |
12
|
|
|
protected $manifest; |
13
|
|
|
|
14
|
|
|
public static function create(string $manifestPath = null): RenderPreloadLinks |
15
|
|
|
{ |
16
|
|
|
if (! $manifestPath) { |
|
|
|
|
17
|
|
|
$manifestPath = public_path('mix-manifest.json'); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
$manifest = json_decode( |
21
|
|
|
file_get_contents($manifestPath), |
22
|
|
|
true |
23
|
|
|
); |
24
|
|
|
|
25
|
|
|
return new self($manifest); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function __construct(array $manifest) |
29
|
|
|
{ |
30
|
|
|
$this->manifest = $manifest; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function __invoke(): HtmlString |
34
|
|
|
{ |
35
|
|
|
return $this->getManifestEntries() |
36
|
|
|
->mapSpread(function (string $path, string $name) { |
37
|
|
|
$rel = $this->getRelAttribute($name); |
38
|
|
|
|
39
|
|
|
if (! $rel) { |
|
|
|
|
40
|
|
|
return null; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$as = $this->getAsAttribute($path); |
44
|
|
|
|
45
|
|
|
if (! $as) { |
|
|
|
|
46
|
|
|
return null; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return "<link rel=\"{$rel}\" href=\"{$path}\" as=\"{$as}\">"; |
50
|
|
|
}) |
51
|
|
|
->filter() |
52
|
|
|
->pipe(function (Collection $links) { |
53
|
|
|
return new HtmlString($links->implode("\n")); |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
protected function getManifestEntries(): Collection |
58
|
|
|
{ |
59
|
|
|
return collect($this->manifest) |
60
|
|
|
->map(function (string $path, string $name) { |
61
|
|
|
return [$path, $name]; |
62
|
|
|
}) |
63
|
|
|
->values(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function getRelAttribute(string $name): ?string |
67
|
|
|
{ |
68
|
|
|
if (Str::contains($name, 'preload')) { |
69
|
|
|
return 'preload'; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if (Str::contains($name, 'prefetch')) { |
73
|
|
|
return 'prefetch'; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return null; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
protected function getAsAttribute(string $path): ?string |
80
|
|
|
{ |
81
|
|
|
if (Str::contains($path, '.js')) { |
82
|
|
|
return 'script'; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
if (Str::contains($path, '.css')) { |
86
|
|
|
return 'style'; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
if (Str::contains($path, ['.woff', '.woff2', '.ttf', '.eot', '.svg', '.ttc'])) { |
90
|
|
|
return 'font'; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return null; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: