Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
46.58% covered (danger)
46.58%
34 / 73
57.14% covered (warning)
57.14%
4 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
Widget_Type_Registry
46.58% covered (danger)
46.58%
34 / 73
57.14% covered (warning)
57.14%
4 / 7
74.05
0.00% covered (danger)
0.00%
0 / 1
 register
42.50% covered (danger)
42.50%
17 / 40
0.00% covered (danger)
0.00%
0 / 1
16.32
 unregister
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 get_registered
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 get_all_registered
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 is_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 ensure_hydrated
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 get_instance
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Widget Types API: Widget_Type_Registry class.
4 *
5 * PA-namespaced copy of the dashboard widget-type registry (the core/Gutenberg
6 * version is gated behind an experimental flag). Stays fully isolated from any
7 * core registry so the two never share state.
8 *
9 * @package automattic/jetpack-premium-analytics
10 */
11
12namespace Automattic\Jetpack\PremiumAnalytics;
13
14/**
15 * Stores Widget_Type instances keyed by their namespaced name.
16 *
17 * Hydrates on its first read: the registration action fires once, and every registrant, the
18 * manifest hydration in widget-types.php included, registers its widget types from there. Reads
19 * happen after `init`, while the page boot dependencies are built and from REST, so hooking the
20 * action is the one moment that covers both paths.
21 */
22#[\AllowDynamicProperties]
23final class Widget_Type_Registry {
24
25    /**
26     * Action through which widget types are registered, fired once on the first read.
27     *
28     * @since $$next-version$$
29     * @var string
30     */
31    const REGISTER_ACTION = 'jetpack_premium_analytics_register_widget_types';
32
33    /**
34     * Registered widget types, as `$name => $instance` pairs.
35     *
36     * @var Widget_Type[]
37     */
38    private $registered_widget_types = array();
39
40    /**
41     * Whether the registration action has fired.
42     *
43     * @var bool
44     */
45    private $hydrated = false;
46
47    /**
48     * Container for the main instance of the class.
49     *
50     * @var Widget_Type_Registry|null
51     */
52    private static $instance = null;
53
54    /**
55     * Registers a widget type.
56     *
57     * @param string|Widget_Type $name Widget type name including namespace, or
58     *                                 a complete Widget_Type instance. When an
59     *                                 instance is provided the `$args` parameter
60     *                                 is ignored.
61     * @param array              $args Optional. Array of widget type arguments.
62     *                                 Accepts any public property of
63     *                                 Widget_Type. Default empty array.
64     * @return Widget_Type|false The registered widget type on success, or false
65     *                           on failure.
66     */
67    public function register( $name, $args = array() ) {
68        $widget_type = null;
69        if ( $name instanceof Widget_Type ) {
70            $widget_type = $name;
71            $name        = $widget_type->name;
72        }
73
74        if ( ! is_string( $name ) ) {
75            _doing_it_wrong(
76                __METHOD__,
77                esc_html__( 'Widget type names must be strings.', 'jetpack-premium-analytics-pkg' ),
78                '0.1.0'
79            );
80            return false;
81        }
82
83        if ( preg_match( '/[A-Z]+/', $name ) ) {
84            _doing_it_wrong(
85                __METHOD__,
86                esc_html__( 'Widget type names must not contain uppercase characters.', 'jetpack-premium-analytics-pkg' ),
87                '0.1.0'
88            );
89            return false;
90        }
91
92        $name_matcher = '/^[a-z0-9-]+\/[a-z0-9-]+$/';
93        if ( ! preg_match( $name_matcher, $name ) ) {
94            _doing_it_wrong(
95                __METHOD__,
96                esc_html__( 'Widget type names must contain a namespace prefix. Example: my-plugin/my-custom-widget-type', 'jetpack-premium-analytics-pkg' ),
97                '0.1.0'
98            );
99            return false;
100        }
101
102        if ( $this->is_registered( $name ) ) {
103            _doing_it_wrong(
104                __METHOD__,
105                sprintf(
106                    /* translators: %s: Widget type name. */
107                    esc_html__( 'Widget type "%s" is already registered.', 'jetpack-premium-analytics-pkg' ),
108                    esc_html( $name )
109                ),
110                '0.1.0'
111            );
112            return false;
113        }
114
115        if ( ! $widget_type ) {
116            $widget_type = new Widget_Type( $name, $args );
117        }
118
119        $this->registered_widget_types[ $name ] = $widget_type;
120
121        return $widget_type;
122    }
123
124    /**
125     * Unregisters a widget type.
126     *
127     * @param string|Widget_Type $name Widget type name including namespace, or
128     *                                 a complete Widget_Type instance.
129     * @return Widget_Type|false The unregistered widget type on success, or
130     *                           false on failure.
131     */
132    public function unregister( $name ) {
133        if ( $name instanceof Widget_Type ) {
134            $name = $name->name;
135        }
136
137        if ( ! $this->is_registered( $name ) ) {
138            _doing_it_wrong(
139                __METHOD__,
140                sprintf(
141                    /* translators: %s: Widget type name. */
142                    esc_html__( 'Widget type "%s" is not registered.', 'jetpack-premium-analytics-pkg' ),
143                    esc_html( $name )
144                ),
145                '0.1.0'
146            );
147            return false;
148        }
149
150        $unregistered_widget_type = $this->registered_widget_types[ $name ];
151        unset( $this->registered_widget_types[ $name ] );
152
153        return $unregistered_widget_type;
154    }
155
156    /**
157     * Retrieves a registered widget type.
158     *
159     * @param string $name Widget type name including namespace.
160     * @return Widget_Type|null The registered widget type, or null if it is not
161     *                          registered.
162     */
163    public function get_registered( $name ) {
164        $this->ensure_hydrated();
165
166        if ( ! $this->is_registered( $name ) ) {
167            return null;
168        }
169
170        return $this->registered_widget_types[ $name ];
171    }
172
173    /**
174     * Retrieves all registered widget types.
175     *
176     * @return Widget_Type[] Associative array of `$name => $widget_type` pairs.
177     */
178    public function get_all_registered() {
179        $this->ensure_hydrated();
180
181        return $this->registered_widget_types;
182    }
183
184    /**
185     * Checks if a widget type is registered. Does not hydrate: register() relies on it, and a
186     * registrant may run before the action fires.
187     *
188     * @param string $name Widget type name including namespace.
189     * @return bool True if the widget type is registered, false otherwise.
190     */
191    public function is_registered( $name ) {
192        return isset( $this->registered_widget_types[ $name ] );
193    }
194
195    /**
196     * Fires the registration action once, on the first read after `init`.
197     *
198     * @return void
199     */
200    private function ensure_hydrated() {
201        if ( $this->hydrated ) {
202            return;
203        }
204
205        // Latching this early would drop every registrant hooked later, so the read skips the action.
206        if ( ! did_action( 'init' ) ) {
207            $message = __( 'Widget types are read after init. A read before it does not hydrate the registry and answers only what was registered directly.', 'jetpack-premium-analytics-pkg' );
208            // One line: tools/replace-next-version-tag.sh only rewrites the token in a single-line call.
209            _doing_it_wrong( __METHOD__, esc_html( $message ), 'jetpack-premium-analytics-$$next-version$$' );
210            return;
211        }
212
213        // Latched before the action so a registrant that reads the registry cannot re-enter.
214        $this->hydrated = true;
215
216        /**
217         * Fires when the widget type registry hydrates, on its first read after `init`.
218         *
219         * Register widget types here rather than on `init`: the registry is read while the page
220         * boot dependencies are built and from REST, and each path loads it at a different
221         * moment. A registrant that may run twice guards with `is_registered()`.
222         *
223         * @since $$next-version$$
224         *
225         * @param Widget_Type_Registry $registry The registry being hydrated.
226         */
227        do_action( self::REGISTER_ACTION, $this );
228    }
229
230    /**
231     * Utility method to retrieve the main instance of the class.
232     *
233     * The instance will be created if it does not exist yet.
234     *
235     * @return Widget_Type_Registry The main instance.
236     */
237    public static function get_instance() {
238        if ( null === self::$instance ) {
239            self::$instance = new self();
240        }
241
242        return self::$instance;
243    }
244}