Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.48% covered (success)
97.48%
116 / 119
84.62% covered (warning)
84.62%
11 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Single_Report_Page
97.48% covered (success)
97.48%
116 / 119
84.62% covered (warning)
84.62%
11 / 13
68
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
3.07
 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     * @return bool
175     */
176    public function is_available() {
177        if ( null === $this->is_available ) {
178            return Capabilities::current_user_can_view_stats();
179        }
180
181        if ( is_callable( $this->is_available ) ) {
182            return (bool) call_user_func( $this->is_available, $this );
183        }
184
185        return (bool) $this->is_available;
186    }
187
188    /**
189     * The page's default layout, or one inner section's, run through the default-layout filter.
190     *
191     * @param string|null $section_slug Inner section, or null for a page with one section.
192     * @return array
193     */
194    public function get_default_layout( $section_slug = null ) {
195        $layout = $this->default_layout;
196
197        if ( null !== $section_slug ) {
198            $layout = array();
199            foreach ( $this->sections as $section ) {
200                if ( $section['slug'] === $section_slug ) {
201                    $layout = $section['default_layout'];
202                    break;
203                }
204            }
205        }
206
207        $layout = is_callable( $layout ) ? call_user_func( $layout, $this, $section_slug ) : $layout;
208        $layout = is_array( $layout ) ? array_values( $layout ) : array();
209
210        /**
211         * Filters the default layout of a single-report page, or of one of its inner sections.
212         *
213         * @since 0.16.0
214         *
215         * @param array              $layout       Widget instances.
216         * @param string             $page_id      Page identifier.
217         * @param string|null        $section_slug Inner section, or null for a page with one section.
218         * @param Single_Report_Page $page         The page.
219         */
220        $layout = apply_filters( SINGLE_REPORT_PAGE_DEFAULT_LAYOUT_FILTER, $layout, $this->id, $section_slug, $this );
221
222        return is_array( $layout ) ? array_values( $layout ) : array();
223    }
224
225    /**
226     * The inner sections with their filtered layouts, empty for a page with one section.
227     *
228     * @return array[]
229     */
230    public function get_sections() {
231        $sections = array();
232
233        foreach ( $this->sections as $section ) {
234            $sections[] = array(
235                'slug'           => $section['slug'],
236                'label'          => $section['label'],
237                'default_layout' => $this->get_default_layout( $section['slug'] ),
238                'controls'       => $section['controls'],
239            );
240        }
241
242        return $sections;
243    }
244
245    /**
246     * The record the client reads.
247     *
248     * @return array
249     */
250    public function to_array() {
251        return array(
252            'id'                => $this->id,
253            'entity'            => $this->entity,
254            'path'              => $this->path,
255            'label'             => $this->label,
256            'dashboard_section' => $this->dashboard_section,
257            'feature'           => $this->feature,
258            'scope_param'       => $this->scope_param,
259            'id_pattern'        => $this->id_pattern,
260            'icon'              => $this->icon,
261            'controls'          => $this->controls,
262            'reports_page'      => $this->reports_page,
263            'preferences_scope' => $this->preferences_scope,
264            'default_layout'    => empty( $this->sections ) ? $this->get_default_layout() : array(),
265            'sections'          => $this->get_sections(),
266        );
267    }
268
269    /**
270     * Copies the recognized arguments onto the record.
271     *
272     * @param array $args Page arguments.
273     */
274    private function set_props( $args ) {
275        if ( ! is_array( $args ) ) {
276            return;
277        }
278
279        if ( isset( $args['path'] ) && self::is_valid_slug( $args['path'] ) ) {
280            $this->path = $args['path'];
281        }
282
283        foreach ( array( 'label', 'dashboard_section', 'feature', 'scope_param', 'id_pattern', 'reports_page', 'preferences_scope' ) as $key ) {
284            if ( isset( $args[ $key ] ) && is_string( $args[ $key ] ) && '' !== $args[ $key ] ) {
285                $this->$key = $args[ $key ];
286            }
287        }
288
289        if ( isset( $args['icon'] ) ) {
290            $this->icon = sanitize_widget_icon( $args['icon'] );
291        }
292
293        if ( array_key_exists( 'controls', $args ) ) {
294            $this->controls = self::normalize_controls( $args['controls'] );
295        }
296
297        if ( array_key_exists( 'is_available', $args ) ) {
298            $this->is_available = $args['is_available'];
299        }
300
301        if ( array_key_exists( 'default_layout', $args ) ) {
302            $this->default_layout = $args['default_layout'];
303        }
304
305        if ( isset( $args['sections'] ) && is_array( $args['sections'] ) ) {
306            $this->sections = self::normalize_sections( $args['sections'] );
307        }
308
309        if ( array_key_exists( 'entity', $args ) ) {
310            $this->entity = self::normalize_entity( $args['entity'] );
311        }
312    }
313
314    /**
315     * Default path, label and reports page for a `postType` entity, before explicit arguments.
316     *
317     * A post type name with an underscore is not a valid path, so that page keeps the id's name.
318     *
319     * @param array $args Page arguments.
320     */
321    private function apply_post_type_defaults( array $args ) {
322        $entity = self::normalize_entity( $args['entity'] ?? null );
323        if ( null === $entity || 'postType' !== $entity['kind'] ) {
324            return;
325        }
326
327        $post_type = get_post_type_object( $entity['name'] );
328        if ( ! $post_type instanceof \WP_Post_Type ) {
329            return;
330        }
331
332        if ( self::is_valid_slug( $post_type->name ) ) {
333            $this->path = $post_type->name;
334        }
335
336        $singular = $post_type->labels->singular_name ?? '';
337        if ( is_string( $singular ) && '' !== $singular ) {
338            $this->label = $singular;
339        }
340
341        $this->scope_param  = 'post_id';
342        $this->reports_page = 'posts';
343    }
344
345    /**
346     * The entity block when it names a kind and a name, or null.
347     *
348     * @param mixed $entity Declared entity.
349     * @return array|null
350     */
351    private static function normalize_entity( $entity ) {
352        if ( ! is_array( $entity ) ) {
353            return null;
354        }
355
356        $kind = $entity['kind'] ?? null;
357        $name = $entity['name'] ?? null;
358        if ( ! self::is_entity_token( $kind ) || ! self::is_entity_token( $name ) ) {
359            return null;
360        }
361
362        $normalized = array(
363            'kind' => $kind,
364            'name' => $name,
365        );
366
367        if ( self::is_entity_token( $entity['key'] ?? null ) ) {
368            $normalized['key'] = $entity['key'];
369        }
370
371        return $normalized;
372    }
373
374    /**
375     * Whether a value can be a core-data kind, name or key.
376     *
377     * @param mixed $value Candidate.
378     * @return bool
379     */
380    private static function is_entity_token( $value ) {
381        return is_string( $value ) && 1 === preg_match( '/^[A-Za-z0-9_-]+$/', $value );
382    }
383
384    /**
385     * Keeps the inner sections that carry a valid slug, deduplicated by slug.
386     *
387     * @param array $sections Section declarations.
388     * @return array[]
389     */
390    private static function normalize_sections( $sections ) {
391        $normalized = array();
392
393        foreach ( $sections as $section ) {
394            if ( ! is_array( $section ) || ! isset( $section['slug'] ) || ! self::is_valid_slug( $section['slug'] ) || isset( $normalized[ $section['slug'] ] ) ) {
395                continue;
396            }
397
398            $normalized[ $section['slug'] ] = array(
399                'slug'           => $section['slug'],
400                'label'          => isset( $section['label'] ) && is_string( $section['label'] ) && '' !== $section['label'] ? $section['label'] : $section['slug'],
401                'default_layout' => $section['default_layout'] ?? array(),
402                'controls'       => self::normalize_controls( $section['controls'] ?? null ),
403            );
404        }
405
406        return array_values( $normalized );
407    }
408
409    /**
410     * The controls a page or a section declares: the fields of a type the client binds, one per
411     * type; false or an empty list for none; null, the default, for anything else.
412     *
413     * @param mixed $controls Declared controls.
414     * @return array[]|null
415     */
416    private static function normalize_controls( $controls ) {
417        if ( false === $controls || array() === $controls ) {
418            return array();
419        }
420
421        // A control is a DataViews field, as a widget attribute is: the same vocabulary, the same sanitizer.
422        $fields = sanitize_widget_attributes( $controls );
423        if ( null === $fields ) {
424            return null;
425        }
426
427        $by_type = array();
428        foreach ( $fields as $field ) {
429            if ( isset( $field['type'] ) && in_array( $field['type'], self::CONTROL_FIELD_TYPES, true ) && ! isset( $by_type[ $field['type'] ] ) ) {
430                $by_type[ $field['type'] ] = $field;
431            }
432        }
433
434        return $by_type ? array_values( $by_type ) : null;
435    }
436
437    /**
438     * Whether a value is a lowercase slug of letters, numbers and hyphens.
439     *
440     * @param mixed $value Candidate.
441     * @return bool
442     */
443    private static function is_valid_slug( $value ) {
444        return is_string( $value ) && 1 === preg_match( '/^[a-z0-9-]+$/', $value );
445    }
446}