Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.24% covered (success)
97.24%
176 / 181
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%
9 / 9
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    $sections = get_available_dashboard_section_slugs();
131
132    if ( null !== $sections ) {
133        $data['premium_analytics']['sections']                   = $sections;
134        $data['premium_analytics']['plan_date_limited_sections'] = get_plan_date_limited_section_slugs();
135    }
136
137    return $data;
138}
139
140/**
141 * Whether the current user can access dashboard section routes.
142 *
143 * @return bool
144 */
145function check_dashboard_sections_permission() {
146    return Capabilities::current_user_can_view_analytics();
147}
148
149/**
150 * Resolves a route section, including availability checks.
151 *
152 * @param string $dashboard_name Dashboard identifier.
153 * @param string $section_id     Section identifier.
154 * @return Dashboard_Section|\WP_Error Registered available section, or error.
155 */
156function get_available_dashboard_section_for_route( $dashboard_name, $section_id ) {
157    $section = get_registered_dashboard_section( $dashboard_name, $section_id );
158
159    if ( ! $section ) {
160        return new \WP_Error(
161            'dashboard_section_not_found',
162            __( 'Dashboard section not found.', 'jetpack-premium-analytics-pkg' ),
163            array( 'status' => 404 )
164        );
165    }
166
167    if ( ! $section->is_available() ) {
168        return new \WP_Error(
169            'dashboard_section_unavailable',
170            __( 'Dashboard section is not available.', 'jetpack-premium-analytics-pkg' ),
171            array( 'status' => 404 )
172        );
173    }
174
175    return $section;
176}
177
178/**
179 * REST schema for one dashboard section, as returned by the sections route.
180 *
181 * Mirrored by the frontend's `sections.ts` and reused by WPCOM for Simple sites (see AGENTS.md).
182 *
183 * @since 0.2.0
184 *
185 * @return array The JSON schema for a dashboard section.
186 */
187function get_dashboard_section_schema() {
188    return array(
189        '$schema'    => 'http://json-schema.org/draft-04/schema#',
190        'title'      => 'jetpack-premium-analytics-dashboard-section',
191        'type'       => 'object',
192        'properties' => array(
193            'id'                      => array(
194                'description' => __( 'Namespaced section identifier.', 'jetpack-premium-analytics-pkg' ),
195                'type'        => 'string',
196                'readonly'    => true,
197            ),
198            'slug'                    => array(
199                'description' => __( 'URL-facing section slug, derived from the identifier.', 'jetpack-premium-analytics-pkg' ),
200                'type'        => 'string',
201                'readonly'    => true,
202            ),
203            'label'                   => array(
204                'description' => __( 'Translated display label, naming the section tab.', 'jetpack-premium-analytics-pkg' ),
205                'type'        => 'string',
206                'readonly'    => true,
207            ),
208            'title'                   => array(
209                'description' => __( 'Translated section heading, distinct from the tab label. Null falls back to the label.', 'jetpack-premium-analytics-pkg' ),
210                'type'        => array( 'string', 'null' ),
211                'readonly'    => true,
212            ),
213            'order'                   => array(
214                'description' => __( 'Sort order, ascending.', 'jetpack-premium-analytics-pkg' ),
215                'type'        => 'integer',
216                'readonly'    => true,
217            ),
218            'date_filter'             => array(
219                'description' => __( 'Which shape the section date filter takes: the rolling date range, or all time plus single years.', 'jetpack-premium-analytics-pkg' ),
220                'type'        => 'string',
221                'enum'        => Dashboard_Section::DATE_FILTERS,
222                'default'     => Dashboard_Section::DATE_FILTER_RANGE,
223                'readonly'    => true,
224            ),
225            'date_filter_options'     => array(
226                'description' => __( 'What the section date filter supports, and where it renders.', 'jetpack-premium-analytics-pkg' ),
227                'type'        => 'object',
228                'properties'  => array(
229                    'with_date_comparison'         => array(
230                        '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' ),
231                        'type'        => 'boolean',
232                        'default'     => true,
233                    ),
234                    'with_header_date_control'     => array(
235                        'description' => __( 'Whether the section header renders the date control. When false, the section widgets host their own.', 'jetpack-premium-analytics-pkg' ),
236                        'type'        => 'boolean',
237                        'default'     => true,
238                    ),
239                    'with_header_interval_control' => array(
240                        'description' => __( 'Whether the section header renders the chart interval control. When false, the section charts host their own.', 'jetpack-premium-analytics-pkg' ),
241                        'type'        => 'boolean',
242                        'default'     => true,
243                    ),
244                ),
245                'readonly'    => true,
246            ),
247            'requires_sync'           => array(
248                'description' => __( 'Whether the section\'s numbers stay incomplete until the analytics initial full sync has finished.', 'jetpack-premium-analytics-pkg' ),
249                'type'        => 'boolean',
250                'default'     => false,
251                'readonly'    => true,
252            ),
253            'notice'                  => array(
254                'description' => __( 'Message shown above the section widgets, or null when there is none.', 'jetpack-premium-analytics-pkg' ),
255                'type'        => array( 'string', 'null' ),
256                'default'     => null,
257                'readonly'    => true,
258            ),
259            'default_layout'          => array(
260                'description' => __( 'Bundled default widget layout.', 'jetpack-premium-analytics-pkg' ),
261                'type'        => 'array',
262                'items'       => array( 'type' => 'object' ),
263                'readonly'    => true,
264            ),
265            'insertable_widget_types' => array(
266                'description' => __( 'Widget types the section inserter offers on top of its default layout.', 'jetpack-premium-analytics-pkg' ),
267                'type'        => 'array',
268                'items'       => array( 'type' => 'string' ),
269                'default'     => array(),
270                'readonly'    => true,
271            ),
272        ),
273    );
274}
275
276/**
277 * REST callback returning available dashboard sections.
278 *
279 * @param \WP_REST_Request $request REST request carrying the dashboard name.
280 * @return \WP_REST_Response
281 */
282function get_dashboard_sections_response( $request ) {
283    $sections = array_map(
284        static function ( Dashboard_Section $section ) {
285            return $section->to_array();
286        },
287        get_available_dashboard_sections( $request['name'] )
288    );
289
290    return rest_ensure_response( $sections );
291}
292
293/**
294 * REST callback returning a section's default layout.
295 *
296 * @param \WP_REST_Request $request REST request carrying dashboard and section identifiers.
297 * @return \WP_REST_Response|\WP_Error
298 */
299function get_dashboard_section_default_layout_response( $request ) {
300    $section = get_available_dashboard_section_for_route( $request['name'], $request['section'] );
301
302    if ( is_wp_error( $section ) ) {
303        return $section;
304    }
305
306    return rest_ensure_response( $section->get_default_layout() );
307}
308
309/**
310 * Registers dashboard section REST routes.
311 *
312 * @return void
313 */
314function register_dashboard_sections_rest_routes() {
315    register_rest_route(
316        DASHBOARD_REST_NAMESPACE,
317        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections',
318        array(
319            array(
320                // @phan-suppress-next-line PhanPluginMixedKeyNoKey -- register_rest_route()'s own signature mixes a numerically keyed endpoint list with a route-level `schema` key.
321                'methods'             => \WP_REST_Server::READABLE,
322                'callback'            => __NAMESPACE__ . '\\get_dashboard_sections_response',
323                'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
324                'args'                => array(
325                    'name' => array(
326                        'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
327                        'type'        => 'string',
328                    ),
329                ),
330            ),
331            'schema' => __NAMESPACE__ . '\\get_dashboard_section_schema',
332        )
333    );
334
335    register_rest_route(
336        DASHBOARD_REST_NAMESPACE,
337        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections/(?P<section>' . get_dashboard_section_id_pattern() . ')/default-layout',
338        array(
339            'methods'             => \WP_REST_Server::READABLE,
340            'callback'            => __NAMESPACE__ . '\\get_dashboard_section_default_layout_response',
341            'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
342            'args'                => array(
343                'name'    => array(
344                    'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
345                    'type'        => 'string',
346                ),
347                'section' => array(
348                    'description' => __( 'Dashboard section identifier.', 'jetpack-premium-analytics-pkg' ),
349                    'type'        => 'string',
350                ),
351            ),
352        )
353    );
354}