Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.76% covered (success)
96.76%
179 / 185
100.00% covered (success)
100.00%
13 / 13
CRAP
n/a
0 / 0
Automattic\Jetpack\PremiumAnalytics\register_dashboard_section
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_registered_dashboard_section
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_available_dashboard_sections
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_available_dashboard_section_slugs
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\get_plan_date_limited_section_slugs
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\PremiumAnalytics\configure_dashboard_sections_script_data
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\inject_dashboard_sections_script_data
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
Automattic\Jetpack\PremiumAnalytics\check_dashboard_sections_permission
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_available_dashboard_section_for_route
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\PremiumAnalytics\get_dashboard_section_schema
100.00% covered (success)
100.00%
86 / 86
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_dashboard_sections_response
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\get_dashboard_section_default_layout_response
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\register_dashboard_sections_rest_routes
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Dashboard Sections API: the registry helpers, the section script data, and the REST routes.
4 *
5 * The package's own sections register through this API from default-dashboard-sections.php,
6 * the same way a plugin extending the dashboard does.
7 *
8 * @package automattic/jetpack-premium-analytics
9 */
10
11namespace Automattic\Jetpack\PremiumAnalytics;
12
13require_once __DIR__ . '/dashboard-layout.php';
14require_once __DIR__ . '/dashboard-grammar.php';
15require_once __DIR__ . '/rest-namespace.php';
16require_once __DIR__ . '/class-dashboard-section.php';
17require_once __DIR__ . '/class-dashboard-section-registry.php';
18require_once __DIR__ . '/dashboard-first-visit.php';
19
20/**
21 * Registers a dashboard section.
22 *
23 * @param string $dashboard_name Dashboard identifier.
24 * @param string $id             Section identifier.
25 * @param array  $args           Optional. Section arguments.
26 * @return Dashboard_Section|false The registered section on success, or false on failure.
27 */
28function register_dashboard_section( $dashboard_name, $id, $args = array() ) {
29    return Dashboard_Section_Registry::get_instance()->register( $dashboard_name, $id, $args );
30}
31
32/**
33 * Retrieves a registered dashboard section.
34 *
35 * @param string $dashboard_name Dashboard identifier.
36 * @param string $id             Section identifier.
37 * @return Dashboard_Section|null The registered section, or null when absent.
38 */
39function get_registered_dashboard_section( $dashboard_name, $id ) {
40    return Dashboard_Section_Registry::get_instance()->get_registered( $dashboard_name, $id );
41}
42
43/**
44 * Retrieves available dashboard sections.
45 *
46 * @param string $dashboard_name Dashboard identifier.
47 * @return Dashboard_Section[] Ordered list of available sections.
48 */
49function get_available_dashboard_sections( $dashboard_name ) {
50    return Dashboard_Section_Registry::get_instance()->get_available_sections( $dashboard_name );
51}
52
53/**
54 * Slugs of the tabs the dashboard exposes, for the client's report routes.
55 *
56 * Reads the same sections the tab list does, so a report cannot outlive the tab it sits
57 * behind. Null, never `array()`, while nothing is registered: an empty array means no
58 * tab is available.
59 *
60 * @since 0.6.0
61 *
62 * @return string[]|null
63 */
64function get_available_dashboard_section_slugs() {
65    $registry = Dashboard_Section_Registry::get_instance();
66
67    if ( empty( $registry->get_all_registered( DASHBOARD_NAME ) ) ) {
68        return null;
69    }
70
71    return array_map(
72        static function ( Dashboard_Section $section ) {
73            return $section->slug;
74        },
75        $registry->get_available_sections( DASHBOARD_NAME )
76    );
77}
78
79/**
80 * Slugs of the available tabs whose window follows the plan's Stats date limits.
81 *
82 * @since 0.14.0
83 *
84 * @return string[]
85 */
86function get_plan_date_limited_section_slugs() {
87    $slugs = array();
88
89    foreach ( Dashboard_Section_Registry::get_instance()->get_available_sections( DASHBOARD_NAME ) as $section ) {
90        if ( $section->follows_plan_date_limits ) {
91            $slugs[] = $section->slug;
92        }
93    }
94
95    return $slugs;
96}
97
98/**
99 * Configures the section script data.
100 *
101 * @since 0.6.0
102 *
103 * @return void
104 */
105function configure_dashboard_sections_script_data() {
106    add_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\inject_dashboard_sections_script_data', 20 );
107}
108
109/**
110 * Injects the available section slugs, those the plan's date limits apply to, and whether the reader may see Stats, into JetpackScriptData.
111 *
112 * The same list travels over REST for the tab bar, but a report route reads no REST before
113 * choosing its redirect, so it reads the slugs from boot data instead.
114 *
115 * @since 0.6.0
116 *
117 * @param array $data The script data passed by the assets package.
118 * @return array
119 */
120function inject_dashboard_sections_script_data( array $data ): array {
121    if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
122        $data['premium_analytics'] = array();
123    }
124
125    // Surfaces outside any section, such as feedback, post to Stats endpoints.
126    $data['premium_analytics']['can_view_stats'] = Capabilities::current_user_can_view_stats();
127
128    // Switching the dashboard off sends the reader to classic Stats, so the client is told where that is.
129    $data['premium_analytics']['classic_stats_url'] = Classic_Stats::page_url();
130
131    // Once classic Stats is retired, Stats v2 stops asking for feedback.
132    $data['premium_analytics']['classic_stats_retired'] = Classic_Stats::is_retired();
133
134    $sections = get_available_dashboard_section_slugs();
135
136    if ( null !== $sections ) {
137        $data['premium_analytics']['sections']                   = $sections;
138        $data['premium_analytics']['plan_date_limited_sections'] = get_plan_date_limited_section_slugs();
139    }
140
141    return $data;
142}
143
144/**
145 * Whether the current user can access dashboard section routes.
146 *
147 * @return bool
148 */
149function check_dashboard_sections_permission() {
150    return Capabilities::current_user_can_view_analytics();
151}
152
153/**
154 * Resolves a route section, including availability checks.
155 *
156 * @param string $dashboard_name Dashboard identifier.
157 * @param string $section_id     Section identifier.
158 * @return Dashboard_Section|\WP_Error Registered available section, or error.
159 */
160function get_available_dashboard_section_for_route( $dashboard_name, $section_id ) {
161    $section = get_registered_dashboard_section( $dashboard_name, $section_id );
162
163    if ( ! $section ) {
164        return new \WP_Error(
165            'dashboard_section_not_found',
166            __( 'Dashboard section not found.', 'jetpack-premium-analytics-pkg' ),
167            array( 'status' => 404 )
168        );
169    }
170
171    if ( ! $section->is_available() ) {
172        return new \WP_Error(
173            'dashboard_section_unavailable',
174            __( 'Dashboard section is not available.', 'jetpack-premium-analytics-pkg' ),
175            array( 'status' => 404 )
176        );
177    }
178
179    return $section;
180}
181
182/**
183 * REST schema for one dashboard section, as returned by the sections route.
184 *
185 * Mirrored by the frontend's `sections.ts` and reused by WPCOM for Simple sites (see AGENTS.md).
186 *
187 * @since 0.2.0
188 *
189 * @return array The JSON schema for a dashboard section.
190 */
191function get_dashboard_section_schema() {
192    return array(
193        '$schema'    => 'http://json-schema.org/draft-04/schema#',
194        'title'      => 'jetpack-premium-analytics-dashboard-section',
195        'type'       => 'object',
196        'properties' => array(
197            'id'                      => array(
198                'description' => __( 'Namespaced section identifier.', 'jetpack-premium-analytics-pkg' ),
199                'type'        => 'string',
200                'readonly'    => true,
201            ),
202            'slug'                    => array(
203                'description' => __( 'URL-facing section slug, derived from the identifier.', 'jetpack-premium-analytics-pkg' ),
204                'type'        => 'string',
205                'readonly'    => true,
206            ),
207            'label'                   => array(
208                'description' => __( 'Translated display label, naming the section tab.', 'jetpack-premium-analytics-pkg' ),
209                'type'        => 'string',
210                'readonly'    => true,
211            ),
212            'title'                   => array(
213                'description' => __( 'Translated section heading, distinct from the tab label. Null falls back to the label.', 'jetpack-premium-analytics-pkg' ),
214                'type'        => array( 'string', 'null' ),
215                'readonly'    => true,
216            ),
217            'order'                   => array(
218                'description' => __( 'Sort order, ascending.', 'jetpack-premium-analytics-pkg' ),
219                'type'        => 'integer',
220                'readonly'    => true,
221            ),
222            'date_filter'             => array(
223                'description' => __( 'Which shape the section date filter takes: the rolling date range, or all time plus single years.', 'jetpack-premium-analytics-pkg' ),
224                'type'        => 'string',
225                'enum'        => Dashboard_Section::DATE_FILTERS,
226                'default'     => Dashboard_Section::DATE_FILTER_RANGE,
227                'readonly'    => true,
228            ),
229            'date_filter_options'     => array(
230                'description' => __( 'What the section date filter supports, and where it renders.', 'jetpack-premium-analytics-pkg' ),
231                'type'        => 'object',
232                'properties'  => array(
233                    'with_date_comparison'         => array(
234                        'description' => __( 'Whether the section supports period-over-period comparison at all. When false, no widget in the section receives comparison parameters.', 'jetpack-premium-analytics-pkg' ),
235                        'type'        => 'boolean',
236                        'default'     => true,
237                    ),
238                    'with_header_date_control'     => array(
239                        'description' => __( 'Whether the section header renders the date control. When false, the section widgets host their own.', 'jetpack-premium-analytics-pkg' ),
240                        'type'        => 'boolean',
241                        'default'     => true,
242                    ),
243                    'with_header_interval_control' => array(
244                        'description' => __( 'Whether the section header renders the chart interval control. When false, the section charts host their own.', 'jetpack-premium-analytics-pkg' ),
245                        'type'        => 'boolean',
246                        'default'     => true,
247                    ),
248                ),
249                'readonly'    => true,
250            ),
251            'requires_sync'           => array(
252                'description' => __( 'Whether the section\'s numbers stay incomplete until the analytics initial full sync has finished.', 'jetpack-premium-analytics-pkg' ),
253                'type'        => 'boolean',
254                'default'     => false,
255                'readonly'    => true,
256            ),
257            'notice'                  => array(
258                'description' => __( 'Message shown above the section widgets, or null when there is none.', 'jetpack-premium-analytics-pkg' ),
259                'type'        => array( 'string', 'null' ),
260                'default'     => null,
261                'readonly'    => true,
262            ),
263            'default_layout'          => array(
264                'description' => __( 'Bundled default widget layout.', 'jetpack-premium-analytics-pkg' ),
265                'type'        => 'array',
266                'items'       => array( 'type' => 'object' ),
267                'readonly'    => true,
268            ),
269            'insertable_widget_types' => array(
270                'description' => __( 'Widget types the section inserter offers on top of its default layout.', 'jetpack-premium-analytics-pkg' ),
271                'type'        => 'array',
272                'items'       => array( 'type' => 'string' ),
273                'default'     => array(),
274                'readonly'    => true,
275            ),
276        ),
277    );
278}
279
280/**
281 * REST callback returning available dashboard sections.
282 *
283 * @param \WP_REST_Request $request REST request carrying the dashboard name.
284 * @return \WP_REST_Response
285 */
286function get_dashboard_sections_response( $request ) {
287    // Only a rendering dashboard asks for its sections, so this also counts a visit through the admin shell.
288    if ( DASHBOARD_NAME === $request['name'] ) {
289        store_dashboard_first_visit();
290    }
291
292    $sections = array_map(
293        static function ( Dashboard_Section $section ) {
294            return $section->to_array();
295        },
296        get_available_dashboard_sections( $request['name'] )
297    );
298
299    return rest_ensure_response( $sections );
300}
301
302/**
303 * REST callback returning a section's default layout.
304 *
305 * @param \WP_REST_Request $request REST request carrying dashboard and section identifiers.
306 * @return \WP_REST_Response|\WP_Error
307 */
308function get_dashboard_section_default_layout_response( $request ) {
309    $section = get_available_dashboard_section_for_route( $request['name'], $request['section'] );
310
311    if ( is_wp_error( $section ) ) {
312        return $section;
313    }
314
315    return rest_ensure_response( $section->get_default_layout() );
316}
317
318/**
319 * Registers dashboard section REST routes.
320 *
321 * @return void
322 */
323function register_dashboard_sections_rest_routes() {
324    register_rest_route(
325        DASHBOARD_REST_NAMESPACE,
326        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections',
327        array(
328            array(
329                // @phan-suppress-next-line PhanPluginMixedKeyNoKey -- register_rest_route()'s own signature mixes a numerically keyed endpoint list with a route-level `schema` key.
330                'methods'             => \WP_REST_Server::READABLE,
331                'callback'            => __NAMESPACE__ . '\\get_dashboard_sections_response',
332                'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
333                'args'                => array(
334                    'name' => array(
335                        'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
336                        'type'        => 'string',
337                    ),
338                ),
339            ),
340            'schema' => __NAMESPACE__ . '\\get_dashboard_section_schema',
341        )
342    );
343
344    register_rest_route(
345        DASHBOARD_REST_NAMESPACE,
346        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections/(?P<section>' . get_dashboard_section_id_pattern() . ')/default-layout',
347        array(
348            'methods'             => \WP_REST_Server::READABLE,
349            'callback'            => __NAMESPACE__ . '\\get_dashboard_section_default_layout_response',
350            'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
351            'args'                => array(
352                'name'    => array(
353                    'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
354                    'type'        => 'string',
355                ),
356                'section' => array(
357                    'description' => __( 'Dashboard section identifier.', 'jetpack-premium-analytics-pkg' ),
358                    'type'        => 'string',
359                ),
360            ),
361        )
362    );
363}