forked from simpleanalytics/wordpress-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptRegistry.php
More file actions
92 lines (76 loc) · 2.5 KB
/
Copy pathScriptRegistry.php
File metadata and controls
92 lines (76 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace SimpleAnalytics;
use SimpleAnalytics\Scripts\Contracts\HasAttributes;
use SimpleAnalytics\Scripts\Contracts\HideScriptId;
use SimpleAnalytics\Scripts\Contracts\Script;
/**
* Register scripts with WordPress.
*/
final class ScriptRegistry
{
/** @var Script[] */
private $scripts = [];
public function __construct()
{
}
public function push(Script $script): void
{
$this->scripts[] = $script;
}
/**
* Register the scripts with WordPress.
*/
public function register(): void
{
$this->enqueueScripts();
$this->addAttributes();
$this->removeIds();
}
protected function enqueueScripts(): void
{
foreach ($this->scripts as $script) {
wp_enqueue_script($script->handle(), $script->path(), [], null, true);
}
}
/**
* As WordPress does not provide a way of directly assigning attributes to scripts, we need to use a filter.
* @see https://developer.wordpress.org/reference/hooks/wp_script_attributes
*/
protected function addAttributes(): void
{
add_filter('wp_script_attributes', \Closure::fromCallable([$this, 'addAttributesFilter']), 10, 2);
}
protected function addAttributesFilter($attributes)
{
foreach ($this->scripts as $script) {
if (
$script instanceof HasAttributes &&
$script->handle() . '-js' === $attributes['id']
) {
return array_merge(is_array($attributes) ? $attributes : iterator_to_array($attributes), $script->attributes());
}
}
return $attributes;
}
protected function removeIds(): void
{
add_filter('script_loader_tag', \Closure::fromCallable([$this, 'removeIdsFilter']), 10, 2);
}
protected function removeIdsFilter($tag, $handle): string
{
foreach ($this->scripts as $script) {
if ($script->handle() === $handle) {
$updatedTag = $tag;
if ($script instanceof HideScriptId) {
// Remove the id attribute from the script tag
$updatedTag = preg_replace('/ id=([\'"])[^\'"]*\\1/', '', $updatedTag);
}
if ($handle === 'simpleanalytics') {
return "<!-- Simple Analytics - 100% privacy-first analytics (official WordPress plugin) -->\n" . $updatedTag;
}
return $updatedTag;
}
}
return $tag;
}
}