PluginProbe
Simple Analytics / 1.109
Simple Analytics v1.109
1.109 1.108 1.107 1.106 1.73 1.74 1.75 1.76 1.77 1.78 1.79 1.8 1.80 1.81 1.82 1.83 1.84 1.85 1.86 1.87 1.88 1.89 1.9 1.90 1.91 All 98 releases
simpleanalytics / src / ScriptRegistry.php

ScriptRegistry.php in Simple Analytics 1.109, at src/ScriptRegistry.php

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