@@ -32,18 +32,43 @@ final class OD_Tag_Visitor_Registry implements Countable, IteratorAggregate {
32
32
*/
33
33
private $ visitors = array ();
34
34
35
+ /**
36
+ * Whether finalized.
37
+ *
38
+ * @since n.e.x.t
39
+ * @var bool
40
+ */
41
+ private $ is_finalized = false ;
42
+
43
+ /**
44
+ * Finalizes the registry to prevent further modifications.
45
+ *
46
+ * @since n.e.x.t
47
+ * @access private
48
+ */
49
+ public function finalize (): void {
50
+ $ this ->is_finalized = true ;
51
+ }
52
+
35
53
/**
36
54
* Registers a tag visitor.
37
55
*
38
56
* @since 0.3.0
57
+ * @since n.e.x.t Returns boolean for whether registration is successful. Returns false if registry is finalized.
39
58
*
40
59
* @phpstan-param TagVisitorCallback $tag_visitor_callback
41
60
*
42
61
* @param non-empty-string $id Identifier for the tag visitor.
43
62
* @param callable $tag_visitor_callback Tag visitor callback.
63
+ * @return bool Whether a tag visitor was registered.
44
64
*/
45
- public function register ( string $ id , callable $ tag_visitor_callback ): void {
65
+ public function register ( string $ id , callable $ tag_visitor_callback ): bool {
66
+ if ( $ this ->is_finalized ) {
67
+ _doing_it_wrong ( __METHOD__ , esc_html ( $ this ->get_finalized_message () ), 'optimization-detective 1.0.0 ' );
68
+ return false ;
69
+ }
46
70
$ this ->visitors [ $ id ] = $ tag_visitor_callback ;
71
+ return true ;
47
72
}
48
73
49
74
/**
@@ -77,11 +102,16 @@ public function get_registered( string $id ): ?callable {
77
102
* Unregisters a tag visitor.
78
103
*
79
104
* @since 0.3.0
105
+ * @since n.e.x.t Returns false if the registry is finalized.
80
106
*
81
107
* @param non-empty-string $id Identifier for the tag visitor.
82
108
* @return bool Whether a tag visitor was unregistered.
83
109
*/
84
110
public function unregister ( string $ id ): bool {
111
+ if ( $ this ->is_finalized ) {
112
+ _doing_it_wrong ( __METHOD__ , esc_html ( $ this ->get_finalized_message () ), 'optimization-detective 1.0.0 ' );
113
+ return false ;
114
+ }
85
115
if ( ! $ this ->is_registered ( $ id ) ) {
86
116
return false ;
87
117
}
@@ -110,4 +140,19 @@ public function getIterator(): ArrayIterator {
110
140
public function count (): int {
111
141
return count ( $ this ->visitors );
112
142
}
143
+
144
+ /**
145
+ * Gets the finalized message when attempting to mutate the registry after the od_register_tag_visitors action.
146
+ *
147
+ * @since n.e.x.t
148
+ *
149
+ * @return string Message.
150
+ */
151
+ private function get_finalized_message (): string {
152
+ return sprintf (
153
+ /* translators: %s is the od_register_tag_visitors action */
154
+ __ ( 'The tag visitor registry has already been finalized. This method must be called during the %s action. ' , 'optimization-detective ' ),
155
+ 'od_register_tag_visitors '
156
+ );
157
+ }
113
158
}
0 commit comments