PluginProbe
Simple Analytics / 1.74
Simple Analytics v1.74
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 / ScriptManager.php

ScriptManager.php in Simple Analytics 1.74, at src/ScriptManager.php

83 lines 2.2 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 ScriptManager
13 {
14 private $scripts = [];
15 public function __construct($scripts = [])
16 {
17 /** @var Script[] */
18 $this->scripts = $scripts;
19 }
20
21 public function add(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 instanceof HideScriptId && $script->handle() === $handle) {
75 // Remove the id attribute from the script tag
76 return preg_replace('/ id=([\'"])[^\'"]*\\1/', '', $tag);
77 }
78 }
79
80 return $tag;
81 }
82 }
83