Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.68% covered (success)
98.68%
75 / 76
88.89% covered (warning)
88.89%
8 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard_Section
98.68% covered (success)
98.68%
75 / 76
88.89% covered (warning)
88.89%
8 / 9
36
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 derive_slug
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 is_available
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 get_default_layout
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_notice
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
4
 get_insertable_widget_types
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 to_array
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 set_props
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
17
 normalize_widget_type_names
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Dashboard Sections API: Dashboard_Section class.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics;
9
10/**
11 * Represents a dashboard section.
12 *
13 * The server-owned model behind a top-level dashboard tab.
14 */
15final class Dashboard_Section {
16
17    /**
18     * Date-filter surface offering the rolling date-range picker (today, last 7
19     * days, a custom range, …) plus the comparison control. The default.
20     *
21     * @since 0.2.0
22     * @var string
23     */
24    const DATE_FILTER_RANGE = 'range';
25
26    /**
27     * Date-filter surface offering all time plus one entry per calendar year,
28     * for sections whose data is read as whole history rather than as a
29     * rolling window.
30     *
31     * @since 0.2.0
32     * @var string
33     */
34    const DATE_FILTER_YEAR = 'year';
35
36    /**
37     * Date-filter surfaces a section may declare.
38     *
39     * @since 0.2.0
40     * @var string[]
41     */
42    const DATE_FILTERS = array( self::DATE_FILTER_RANGE, self::DATE_FILTER_YEAR );
43
44    /**
45     * Dashboard identifier.
46     *
47     * @var string
48     */
49    public $dashboard_name;
50
51    /**
52     * Section identifier.
53     *
54     * @var string
55     */
56    public $id;
57
58    /**
59     * URL-facing section slug, derived from the identifier.
60     *
61     * @var string
62     */
63    public $slug;
64
65    /**
66     * Display label, naming the section's tab.
67     *
68     * @var string
69     */
70    public $label;
71
72    /**
73     * Section heading, deliberately distinct from the tab label: the tab reads
74     * `Traffic` where the heading reads `Site traffic`. Null falls back to the label.
75     *
76     * @since 0.3.0
77     * @var string|null
78     */
79    public $title = null;
80
81    /**
82     * Sort order.
83     *
84     * @var int
85     */
86    public $order = 10;
87
88    /**
89     * Which shape the section's date filter takes, as one of self::DATE_FILTERS.
90     *
91     * Shape only. Where it renders and what it supports are
92     * self::$date_filter_options.
93     *
94     * @since 0.2.0
95     * @var string
96     */
97    public $date_filter = self::DATE_FILTER_RANGE;
98
99    /**
100     * What the section's date filter supports, and where it renders.
101     *
102     * - `with_date_comparison`: false drops the comparison param from every widget fetch in the
103     *   section, not just the chrome.
104     * - `with_header_date_control`: false hands the control to the section's widgets, which may
105     *   save the range onto the widget instance rather than the URL.
106     * - `with_header_interval_control`: false drops the chart interval control from the header, for
107     *   a section whose charts each save their own.
108     *
109     * @since 0.3.0
110     * @since 0.5.0 Added `with_header_date_control`.
111     * @since 0.12.0 Added `with_header_interval_control`.
112     * @var array
113     */
114    public $date_filter_options = array(
115        'with_date_comparison'         => true,
116        'with_header_date_control'     => true,
117        'with_header_interval_control' => true,
118    );
119
120    /**
121     * Whether the section's data only reaches WordPress.com through the analytics
122     * full sync, so its numbers are incomplete until that sync has finished once.
123     *
124     * @since 0.4.0
125     * @var bool
126     */
127    public $requires_sync = false;
128
129    /**
130     * Whether the section needs the site's Jetpack connection. On a disconnected site, a section that
131     * does not keeps working, and the others show a prompt to connect it.
132     *
133     * @since $$next-version$$
134     * @var bool
135     */
136    public $requires_connection = true;
137
138    /**
139     * Whether the plan's Stats date limits apply to the section's window.
140     *
141     * @since 0.14.0
142     * @var bool
143     */
144    public $follows_plan_date_limits = false;
145
146    /**
147     * Message, or a callback returning one, shown above the section's widgets; null when none.
148     *
149     * @since 0.13.0
150     * @var string|callable|null
151     */
152    private $notice = null;
153
154    /**
155     * Availability flag or callback; null when the registration declared none.
156     *
157     * @var bool|callable|null
158     */
159    private $is_available = null;
160
161    /**
162     * Default layout array or callback.
163     *
164     * @var array|callable
165     */
166    private $default_layout = array();
167
168    /**
169     * Widget type names the inserter offers on top of the default layout's.
170     *
171     * @since 0.13.0
172     * @var string[]
173     */
174    private $insertable_widget_types = array();
175
176    /**
177     * Constructor.
178     *
179     * @param string $dashboard_name Dashboard identifier.
180     * @param string $id             Section identifier.
181     * @param array  $args           Optional. Section arguments.
182     */
183    public function __construct( $dashboard_name, $id, $args = array() ) {
184        $this->dashboard_name = $dashboard_name;
185        $this->id             = $id;
186        $this->slug           = self::derive_slug( $id );
187        $this->label          = $id;
188
189        $this->set_props( $args );
190    }
191
192    /**
193     * Derives the URL-facing slug from a namespaced section identifier.
194     *
195     * @param string $id Section identifier, e.g. `analytics/traffic`.
196     * @return string The segment after the namespace, e.g. `traffic`.
197     */
198    private static function derive_slug( $id ) {
199        $separator = strpos( (string) $id, '/' );
200
201        return false === $separator ? (string) $id : substr( $id, $separator + 1 );
202    }
203
204    /**
205     * Returns whether this section should be exposed.
206     *
207     * @return bool
208     */
209    public function is_available() {
210        // Before sections decided who opens the dashboard, Stats access was the outer gate.
211        if ( null === $this->is_available ) {
212            return Capabilities::current_user_can_view_stats();
213        }
214
215        if ( is_callable( $this->is_available ) ) {
216            return (bool) call_user_func( $this->is_available, $this );
217        }
218
219        return (bool) $this->is_available;
220    }
221
222    /**
223     * Returns the section's default widget layout, run through the default-layout filter.
224     *
225     * @return array Array of widget instances.
226     */
227    public function get_default_layout() {
228        $layout = is_callable( $this->default_layout )
229            ? call_user_func( $this->default_layout, $this )
230            : $this->default_layout;
231        $layout = is_array( $layout ) ? array_values( $layout ) : array();
232
233        /**
234         * Filters a dashboard section's default widget layout.
235         *
236         * Each entry matches the dashboard's widget instance shape: `uuid`, `type`, optional
237         * `attributes`, optional `placement`. Runs for every section, so a callback adding an
238         * instance to one switches on `$section_id`.
239         *
240         * @since 0.8.0 Runs from the section, with its declared layout and its
241         *                         namespaced id; it received an empty array and any alias before.
242         *
243         * @param array             $layout     The section's declared default widget instances.
244         * @param string            $section_id Namespaced section identifier, e.g. `analytics/traffic`.
245         * @param Dashboard_Section $section    The section.
246         */
247        $layout = apply_filters( DASHBOARD_DEFAULT_LAYOUT_FILTER, $layout, $this->id, $this );
248
249        return is_array( $layout ) ? array_values( $layout ) : array();
250    }
251
252    /**
253     * Returns the message to show above the section's widgets, resolved for this request.
254     *
255     * @since 0.13.0
256     *
257     * @return string|null The message, or null when there is none.
258     */
259    public function get_notice() {
260        $notice = is_callable( $this->notice ) ? call_user_func( $this->notice, $this ) : $this->notice;
261
262        return is_string( $notice ) && '' !== $notice ? $notice : null;
263    }
264
265    /**
266     * Returns the widget types the section's inserter offers on top of its default layout, run
267     * through the insertable-types filter.
268     *
269     * @since 0.13.0
270     *
271     * @return string[] Widget type names.
272     */
273    public function get_insertable_widget_types() {
274        /**
275         * Filters the widget types a dashboard section's inserter offers on top of its default layout.
276         *
277         * Runs for every section, so a callback adding a type to one switches on `$section_id`. A
278         * type the widget type registry does not know is never offered.
279         *
280         * @since 0.13.0
281         *
282         * @param string[]          $types      The section's declared widget type names.
283         * @param string            $section_id Namespaced section identifier, e.g. `analytics/traffic`.
284         * @param Dashboard_Section $section    The section.
285         */
286        $types = apply_filters( DASHBOARD_INSERTABLE_WIDGET_TYPES_FILTER, $this->insertable_widget_types, $this->id, $this );
287
288        return self::normalize_widget_type_names( $types );
289    }
290
291    /**
292     * Returns the public REST representation.
293     *
294     * @return array
295     */
296    public function to_array() {
297        return array(
298            'id'                      => $this->id,
299            'slug'                    => $this->slug,
300            'label'                   => $this->label,
301            'title'                   => $this->title,
302            'order'                   => (int) $this->order,
303            'date_filter'             => $this->date_filter,
304            'date_filter_options'     => $this->date_filter_options,
305            'requires_sync'           => $this->requires_sync,
306            'notice'                  => $this->get_notice(),
307            'default_layout'          => $this->get_default_layout(),
308            'insertable_widget_types' => $this->get_insertable_widget_types(),
309        );
310    }
311
312    /**
313     * Hydrates section properties from the args array.
314     *
315     * @param array $args Section arguments.
316     * @return void
317     */
318    private function set_props( $args ) {
319        if ( ! is_array( $args ) ) {
320            return;
321        }
322
323        if ( isset( $args['label'] ) ) {
324            $this->label = (string) $args['label'];
325        }
326
327        // An empty string is a registrant saying "none", not a heading: kept as-is it
328        // would defeat the label fallback and render an `<h2>` with no accessible name.
329        if ( isset( $args['title'] ) ) {
330            $title       = (string) $args['title'];
331            $this->title = '' === $title ? null : $title;
332        }
333
334        if ( isset( $args['order'] ) ) {
335            $this->order = (int) $args['order'];
336        }
337
338        // An unrecognized surface keeps the default rather than reaching the
339        // dashboard, where the frontend has no filter to render for it.
340        if ( isset( $args['date_filter'] ) && in_array( $args['date_filter'], self::DATE_FILTERS, true ) ) {
341            $this->date_filter = (string) $args['date_filter'];
342        }
343
344        // Merged over the defaults so a partial array keeps the rest, and narrowed
345        // to the known options, which is all the dashboard renders.
346        if ( isset( $args['date_filter_options'] ) && is_array( $args['date_filter_options'] ) ) {
347            $options = array_merge( $this->date_filter_options, $args['date_filter_options'] );
348
349            $this->date_filter_options = array(
350                'with_date_comparison'         => (bool) $options['with_date_comparison'],
351                'with_header_date_control'     => (bool) $options['with_header_date_control'],
352                'with_header_interval_control' => (bool) $options['with_header_interval_control'],
353            );
354        }
355
356        if ( isset( $args['requires_sync'] ) ) {
357            $this->requires_sync = (bool) $args['requires_sync'];
358        }
359
360        if ( isset( $args['requires_connection'] ) ) {
361            $this->requires_connection = (bool) $args['requires_connection'];
362        }
363
364        if ( isset( $args['follows_plan_date_limits'] ) ) {
365            $this->follows_plan_date_limits = (bool) $args['follows_plan_date_limits'];
366        }
367
368        if ( array_key_exists( 'notice', $args ) ) {
369            $this->notice = $args['notice'];
370        }
371
372        if ( array_key_exists( 'is_available', $args ) ) {
373            $this->is_available = $args['is_available'];
374        }
375
376        if ( array_key_exists( 'default_layout', $args ) ) {
377            $this->default_layout = $args['default_layout'];
378        }
379
380        if ( isset( $args['insertable_widget_types'] ) ) {
381            $this->insertable_widget_types = self::normalize_widget_type_names( $args['insertable_widget_types'] );
382        }
383    }
384
385    /**
386     * Narrows a value to its distinct, non-empty widget type names, as a list.
387     *
388     * @param mixed $types Candidate widget type names.
389     * @return string[]
390     */
391    private static function normalize_widget_type_names( $types ) {
392        if ( ! is_array( $types ) ) {
393            return array();
394        }
395
396        $names = array_filter(
397            $types,
398            static function ( $type ) {
399                return is_string( $type ) && '' !== $type;
400            }
401        );
402
403        return array_values( array_unique( $names ) );
404    }
405}