Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.56% covered (success)
97.56%
120 / 123
85.71% covered (warning)
85.71%
12 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Single_Report_Page
97.56% covered (success)
97.56%
120 / 123
85.71% covered (warning)
85.71%
12 / 14
73
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 derive_path
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 is_available
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 is_entity_in_rest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 get_default_layout
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
7
 get_sections
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 to_array
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
2
 set_props
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
15.26
 apply_post_type_defaults
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
 normalize_entity
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 is_entity_token
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 normalize_sections
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
9
 normalize_controls
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
9
 is_valid_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * A single-report page: the dashboard page about one entity, a post, an author, a video.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics;
9
10/**
11 * Describes one single-report page registered with the dashboard.
12 *
13 * The record is declarative. `entity` names the core-data record the page is about; the summary
14 * and header still come from a client-side adapter: the page's own, or the post one for a post type.
15 *
16 * @since 0.16.0
17 */
18class Single_Report_Page {
19
20    /**
21     * Field types a control may declare: the ones the client binds to the page state.
22     *
23     * @var string[]
24     */
25    const CONTROL_FIELD_TYPES = array( 'jpa/report-params' );
26
27    /**
28     * Dashboard the page belongs to.
29     *
30     * @var string
31     */
32    public $dashboard_name;
33
34    /**
35     * Namespaced identifier, e.g. `videopress/video`.
36     *
37     * @var string
38     */
39    public $id;
40
41    /**
42     * Core-data entity the page is about (`kind`, `name`, optional `key`), or null.
43     *
44     * @var array|null
45     */
46    public $entity = null;
47
48    /**
49     * URL segment, the public identity of the page: `/report/{path}/{id}`.
50     *
51     * @var string
52     */
53    public $path;
54
55    /**
56     * The entity kind, used as the breadcrumb and as the title fallback.
57     *
58     * @var string
59     */
60    public $label;
61
62    /**
63     * Slug of the dashboard section the page belongs to.
64     *
65     * @var string|null
66     */
67    public $dashboard_section = null;
68
69    /**
70     * Stats feature key a plan may lock; a locked feature sends the reader to the locked reports page.
71     *
72     * @var string|null
73     */
74    public $feature = null;
75
76    /**
77     * Report param that carries the entity id to the widgets.
78     *
79     * @var string
80     */
81    public $scope_param = 'post_id';
82
83    /**
84     * Regex the entity id must match, without delimiters.
85     *
86     * @var string
87     */
88    public $id_pattern = '^[1-9]\d*$';
89
90    /**
91     * Registered icon name (`collection/icon-name`), resolved on the client as widget icons are.
92     *
93     * @var string|null
94     */
95    public $icon = null;
96
97    /**
98     * Header controls: DataViews field declarations, empty for none, null for the default date control.
99     *
100     * @var array[]|null
101     */
102    public $controls = null;
103
104    /**
105     * Reports page of the same entities, for the "Back to …" link of the not-found notice.
106     *
107     * @var string|null
108     */
109    public $reports_page = null;
110
111    /**
112     * Preferences scope the client persists the arrangement under.
113     *
114     * @var string
115     */
116    public $preferences_scope;
117
118    /**
119     * Availability rule: a callable, a bool, or null for the default.
120     *
121     * @var callable|bool|null
122     */
123    private $is_available = null;
124
125    /**
126     * Default layout of a page with one section: widget instances, or a callable returning them.
127     *
128     * @var array|callable
129     */
130    private $default_layout = array();
131
132    /**
133     * Inner sections of a page with inner navigation: `slug`, `label`, `default_layout` and `controls` each.
134     *
135     * @var array[]
136     */
137    private $sections = array();
138
139    /**
140     * Constructor.
141     *
142     * @param string $dashboard_name Dashboard identifier.
143     * @param string $id             Page identifier.
144     * @param array  $args           Page arguments.
145     */
146    public function __construct( $dashboard_name, $id, $args = array() ) {
147        $this->dashboard_name = $dashboard_name;
148        $this->id             = $id;
149        $this->path           = self::derive_path( $id );
150        $this->label          = $id;
151        $this->apply_post_type_defaults( is_array( $args ) ? $args : array() );
152        $this->set_props( $args );
153
154        if ( empty( $this->preferences_scope ) ) {
155            $this->preferences_scope = 'jetpack-premium-analytics/' . $this->path . '-detail';
156        }
157    }
158
159    /**
160     * Default path: the name part of the id.
161     *
162     * @param string $id Page identifier.
163     * @return string
164     */
165    private static function derive_path( $id ) {
166        $separator = strpos( (string) $id, '/' );
167
168        return false === $separator ? (string) $id : substr( $id, $separator + 1 );
169    }
170
171    /**
172     * Whether the page is available to the current reader.
173     *
174     * By default: Stats access, and a post type's page only where the type is registered in REST.
175     *
176     * @return bool
177     */
178    public function is_available() {
179        if ( null === $this->is_available ) {
180            return Capabilities::current_user_can_view_stats() && $this->is_entity_in_rest();
181        }
182
183        if ( is_callable( $this->is_available ) ) {
184            return (bool) call_user_func( $this->is_available, $this );
185        }
186
187        return (bool) $this->is_available;
188    }
189
190    /**
191     * Whether core-data can load the page's entity: a post type's has to be registered in REST.
192     *
193     * @return bool
194     */
195    private function is_entity_in_rest() {
196        if ( null === $this->entity || 'postType' !== $this->entity['kind'] ) {
197            return true;
198        }
199
200        $post_type = get_post_type_object( $this->entity['name'] );
201
202        return $post_type instanceof \WP_Post_Type && (bool) $post_type->show_in_rest;
203    }
204
205    /**
206     * The page's default layout, or one inner section's, run through the default-layout filter.
207     *
208     * @param string|null $section_slug Inner section, or null for a page with one section.
209     * @return array
210     */
211    public function get_default_layout( $section_slug = null ) {
212        $layout = $this->default_layout;
213
214        if ( null !== $section_slug ) {
215            $layout = array();
216            foreach ( $this->sections as $section ) {
217                if ( $section['slug'] === $section_slug ) {
218                    $layout = $section['default_layout'];
219                    break;
220                }
221            }
222        }
223
224        $layout = is_callable( $layout ) ? call_user_func( $layout, $this, $section_slug ) : $layout;
225        $layout = is_array( $layout ) ? array_values( $layout ) : array();
226
227        /**
228         * Filters the default layout of a single-report page, or of one of its inner sections.
229         *
230         * @since 0.16.0
231         *
232         * @param array              $layout       Widget instances.
233         * @param string             $page_id      Page identifier.
234         * @param string|null        $section_slug Inner section, or null for a page with one section.
235         * @param Single_Report_Page $page         The page.
236         */
237        $layout = apply_filters( SINGLE_REPORT_PAGE_DEFAULT_LAYOUT_FILTER, $layout, $this->id, $section_slug, $this );
238
239        return is_array( $layout ) ? array_values( $layout ) : array();
240    }
241
242    /**
243     * The inner sections with their filtered layouts, empty for a page with one section.
244     *
245     * @return array[]
246     */
247    public function get_sections() {
248        $sections = array();
249
250        foreach ( $this->sections as $section ) {
251            $sections[] = array(
252                'slug'           => $section['slug'],
253                'label'          => $section['label'],
254                'default_layout' => $this->get_default_layout( $section['slug'] ),
255                'controls'       => $section['controls'],
256            );
257        }
258
259        return $sections;
260    }
261
262    /**
263     * The record the client reads.
264     *
265     * @return array
266     */
267    public function to_array() {
268        return array(
269            'id'                => $this->id,
270            'entity'            => $this->entity,
271            'path'              => $this->path,
272            'label'             => $this->label,
273            'dashboard_section' => $this->dashboard_section,
274            'feature'           => $this->feature,
275            'scope_param'       => $this->scope_param,
276            'id_pattern'        => $this->id_pattern,
277            'icon'              => $this->icon,
278            'controls'          => $this->controls,
279            'reports_page'      => $this->reports_page,
280            'preferences_scope' => $this->preferences_scope,
281            'default_layout'    => empty( $this->sections ) ? $this->get_default_layout() : array(),
282            'sections'          => $this->get_sections(),
283        );
284    }
285
286    /**
287     * Copies the recognized arguments onto the record.
288     *
289     * @param array $args Page arguments.
290     */
291    private function set_props( $args ) {
292        if ( ! is_array( $args ) ) {
293            return;
294        }
295
296        if ( isset( $args['path'] ) && self::is_valid_slug( $args['path'] ) ) {
297            $this->path = $args['path'];
298        }
299
300        foreach ( array( 'label', 'dashboard_section', 'feature', 'scope_param', 'id_pattern', 'reports_page', 'preferences_scope' ) as $key ) {
301            if ( isset( $args[ $key ] ) && is_string( $args[ $key ] ) && '' !== $args[ $key ] ) {
302                $this->$key = $args[ $key ];
303            }
304        }
305
306        if ( isset( $args['icon'] ) ) {
307            $this->icon = sanitize_widget_icon( $args['icon'] );
308        }
309
310        if ( array_key_exists( 'controls', $args ) ) {
311            $this->controls = self::normalize_controls( $args['controls'] );
312        }
313
314        if ( array_key_exists( 'is_available', $args ) ) {
315            $this->is_available = $args['is_available'];
316        }
317
318        if ( array_key_exists( 'default_layout', $args ) ) {
319            $this->default_layout = $args['default_layout'];
320        }
321
322        if ( isset( $args['sections'] ) && is_array( $args['sections'] ) ) {
323            $this->sections = self::normalize_sections( $args['sections'] );
324        }
325
326        if ( array_key_exists( 'entity', $args ) ) {
327            $this->entity = self::normalize_entity( $args['entity'] );
328        }
329    }
330
331    /**
332     * Default path, label and reports page for a `postType` entity, before explicit arguments.
333     *
334     * A post type name with an underscore is not a valid path, so that page keeps the id's name.
335     *
336     * @param array $args Page arguments.
337     */
338    private function apply_post_type_defaults( array $args ) {
339        $entity = self::normalize_entity( $args['entity'] ?? null );
340        if ( null === $entity || 'postType' !== $entity['kind'] ) {
341            return;
342        }
343
344        $post_type = get_post_type_object( $entity['name'] );
345        if ( ! $post_type instanceof \WP_Post_Type ) {
346            return;
347        }
348
349        if ( self::is_valid_slug( $post_type->name ) ) {
350            $this->path = $post_type->name;
351        }
352
353        $singular = $post_type->labels->singular_name ?? '';
354        if ( is_string( $singular ) && '' !== $singular ) {
355            $this->label = $singular;
356        }
357
358        $this->scope_param  = 'post_id';
359        $this->reports_page = 'posts';
360    }
361
362    /**
363     * The entity block when it names a kind and a name, or null.
364     *
365     * @param mixed $entity Declared entity.
366     * @return array|null
367     */
368    private static function normalize_entity( $entity ) {
369        if ( ! is_array( $entity ) ) {
370            return null;
371        }
372
373        $kind = $entity['kind'] ?? null;
374        $name = $entity['name'] ?? null;
375        if ( ! self::is_entity_token( $kind ) || ! self::is_entity_token( $name ) ) {
376            return null;
377        }
378
379        $normalized = array(
380            'kind' => $kind,
381            'name' => $name,
382        );
383
384        if ( self::is_entity_token( $entity['key'] ?? null ) ) {
385            $normalized['key'] = $entity['key'];
386        }
387
388        return $normalized;
389    }
390
391    /**
392     * Whether a value can be a core-data kind, name or key.
393     *
394     * @param mixed $value Candidate.
395     * @return bool
396     */
397    private static function is_entity_token( $value ) {
398        return is_string( $value ) && 1 === preg_match( '/^[A-Za-z0-9_-]+$/', $value );
399    }
400
401    /**
402     * Keeps the inner sections that carry a valid slug, deduplicated by slug.
403     *
404     * @param array $sections Section declarations.
405     * @return array[]
406     */
407    private static function normalize_sections( $sections ) {
408        $normalized = array();
409
410        foreach ( $sections as $section ) {
411            if ( ! is_array( $section ) || ! isset( $section['slug'] ) || ! self::is_valid_slug( $section['slug'] ) || isset( $normalized[ $section['slug'] ] ) ) {
412                continue;
413            }
414
415            $normalized[ $section['slug'] ] = array(
416                'slug'           => $section['slug'],
417                'label'          => isset( $section['label'] ) && is_string( $section['label'] ) && '' !== $section['label'] ? $section['label'] : $section['slug'],
418                'default_layout' => $section['default_layout'] ?? array(),
419                'controls'       => self::normalize_controls( $section['controls'] ?? null ),
420            );
421        }
422
423        return array_values( $normalized );
424    }
425
426    /**
427     * The controls a page or a section declares: the fields of a type the client binds, one per
428     * type; false or an empty list for none; null, the default, for anything else.
429     *
430     * @param mixed $controls Declared controls.
431     * @return array[]|null
432     */
433    private static function normalize_controls( $controls ) {
434        if ( false === $controls || array() === $controls ) {
435            return array();
436        }
437
438        // A control is a DataViews field, as a widget attribute is: the same vocabulary, the same sanitizer.
439        $fields = sanitize_widget_attributes( $controls );
440        if ( null === $fields ) {
441            return null;
442        }
443
444        $by_type = array();
445        foreach ( $fields as $field ) {
446            if ( isset( $field['type'] ) && in_array( $field['type'], self::CONTROL_FIELD_TYPES, true ) && ! isset( $by_type[ $field['type'] ] ) ) {
447                $by_type[ $field['type'] ] = $field;
448            }
449        }
450
451        return $by_type ? array_values( $by_type ) : null;
452    }
453
454    /**
455     * Whether a value is a lowercase slug of letters, numbers and hyphens.
456     *
457     * @param mixed $value Candidate.
458     * @return bool
459     */
460    private static function is_valid_slug( $value ) {
461        return is_string( $value ) && 1 === preg_match( '/^[a-z0-9-]+$/', $value );
462    }
463}