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