Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.54% covered (success)
92.54%
62 / 67
55.56% covered (warning)
55.56%
5 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Analytics_Dashboard
92.54% covered (success)
92.54%
62 / 67
55.56% covered (warning)
55.56%
5 / 9
27.30
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 register_single_report_pages
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
4
 register_widget_types
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 add_default_layout_instance
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
7.07
 is_top_videos_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 widget_contract_is_supported
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_widget_manifest
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 load_build
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 build_dir
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * VideoPress widgets of the Premium Analytics dashboard.
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use Automattic\Jetpack\Status\Host;
11use function Automattic\Jetpack\PremiumAnalytics\get_dashboard_default_widget_instance;
12use function Automattic\Jetpack\PremiumAnalytics\register_widget_types_from_manifest;
13use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_NAME;
14use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_TILE_LIST;
15
16/**
17 * Registers the package's widget types on the Premium Analytics dashboard, seeds Top videos
18 * into the Traffic section's default layout, and registers the video single-report page.
19 *
20 * The package decides nothing about who gets the widgets: `Initializer` calls `init()` where
21 * VideoPress is active outside the WordPress.com platform, jetpack-mu-wpcom calls the registrants
22 * on Simple and Atomic where the plan includes VideoPress. Everything registers when the
23 * dashboard's widget registry hydrates, so a call on a site without the dashboard is inert.
24 *
25 * @since 0.55.0
26 */
27class Analytics_Dashboard {
28
29    /**
30     * Widget type name the package builds, from `widgets/top-videos/widget.json`.
31     */
32    const TOP_VIDEOS_TYPE = 'videopress/top-videos';
33
34    /**
35     * Widget type name the package builds, from `widgets/video-player/widget.json`.
36     */
37    const VIDEO_PLAYER_TYPE = 'videopress/video-player';
38
39    /**
40     * Names the widget type registered under before it moved here. A persisted layout that still
41     * carries one resolves to TOP_VIDEOS_TYPE.
42     */
43    const TOP_VIDEOS_FORMER_NAMES = array( 'jpa/videopress' );
44
45    /**
46     * The dashboard section whose default layout seeds the widget, and the seeded instance.
47     */
48    const TRAFFIC_SECTION_ID       = 'analytics/traffic';
49    const TOP_VIDEOS_INSTANCE_UUID = 'default-videopress-widget-instance';
50
51    /**
52     * The video single-report page, served by the dashboard at `/report/video/{id}`.
53     */
54    const VIDEO_PAGE_ID   = 'videopress/video';
55    const VIDEO_PAGE_PATH = 'video';
56
57    /**
58     * Registry actions and default-layout filter of the dashboard package.
59     */
60    const REGISTER_WIDGET_TYPES_ACTION        = 'jetpack_premium_analytics_register_widget_types';
61    const REGISTER_SINGLE_REPORT_PAGES_ACTION = 'jetpack_premium_analytics_register_single_report_pages';
62    const DEFAULT_LAYOUT_FILTER               = 'jetpack_premium_analytics_dashboard_default_layout';
63
64    /**
65     * Text domain of the widget metadata and of the built widget bundle.
66     */
67    const TEXTDOMAIN = 'jetpack-videopress-pkg';
68
69    /**
70     * Lowest widget contract the build works against: Top videos renders the `@wordpress/ui`
71     * primitives the SDK shares, which the dashboard ships from 2.1.0.
72     */
73    const MIN_WIDGET_API_VERSION = '2.1.0';
74
75    /**
76     * Lowest widget contract with the single-report page API and the generic route that serves it.
77     */
78    const MIN_SINGLE_REPORT_API_VERSION = '2.2.0';
79
80    /**
81     * Hook the registrant on the dashboard's registry action and the seed on its layout filter.
82     *
83     * Priority 20 for the registrant, after the dashboard package's own; priority 10 for the seed,
84     * before the dashboard drops the instances of unregistered types at 100.
85     *
86     * @return void
87     */
88    public static function init() {
89        // Simple and Atomic decide by plan feature, from jetpack-mu-wpcom.
90        if ( ( new Host() )->is_wpcom_platform() ) {
91            return;
92        }
93
94        add_action( self::REGISTER_WIDGET_TYPES_ACTION, array( __CLASS__, 'register_widget_types' ), 20 );
95        add_action( self::REGISTER_SINGLE_REPORT_PAGES_ACTION, array( __CLASS__, 'register_single_report_pages' ), 20 );
96        add_filter( self::DEFAULT_LAYOUT_FILTER, array( __CLASS__, 'add_default_layout_instance' ), 10, 2 );
97    }
98
99    /**
100     * Register the video single-report page: the dashboard renders it from this record at
101     * `/report/video/{id}`, with the arrangements readers saved on the page it served before.
102     *
103     * The layout names the package's player and the dashboard's own video detail widget types,
104     * until those move here too.
105     *
106     * @since 0.63.0
107     *
108     * @param object $registry The single-report page registry being hydrated.
109     * @return void
110     */
111    public static function register_single_report_pages( $registry ) {
112        if ( ! self::widget_contract_is_supported( self::MIN_SINGLE_REPORT_API_VERSION ) || ! method_exists( $registry, 'register' ) ) {
113            return;
114        }
115
116        // An older dashboard still registers the video page itself, on this path.
117        if ( $registry->get_registered_by_path( DASHBOARD_NAME, self::VIDEO_PAGE_PATH ) ) {
118            return;
119        }
120
121        $registry->register(
122            DASHBOARD_NAME,
123            self::VIDEO_PAGE_ID,
124            array(
125                'path'              => self::VIDEO_PAGE_PATH,
126                'label'             => __( 'Video', 'jetpack-videopress-pkg' ),
127                'dashboard_section' => 'traffic',
128                'feature'           => 'videos',
129                'scope_param'       => 'post_id',
130                'icon'              => 'jpa/video',
131                'reports_page'      => 'videos',
132                'default_layout'    => array(
133                    get_dashboard_default_widget_instance( 'video-detail-views-performance', 'jpa/video-detail-views-performance', 10, 'full', 2, array( 'chartType' => 'bar' ) ),
134                    get_dashboard_default_widget_instance( 'videopress-video-player', self::VIDEO_PLAYER_TYPE, 20, 1, 2 ),
135                    get_dashboard_default_widget_instance( 'video-detail-embeds', 'jpa/video-detail-embeds', 30, 'fill', 2 ),
136                ),
137                'preferences_scope' => 'jetpack-premium-analytics/video-detail',
138            )
139        );
140    }
141
142    /**
143     * Register the widget types from the package's build manifest.
144     *
145     * Loads the generated build first: after `init` it registers the widget script modules on the
146     * spot, so they reach the page import map the same request.
147     *
148     * @param object $registry The widget type registry being hydrated.
149     * @return void
150     */
151    public static function register_widget_types( $registry ) {
152        if ( ! self::widget_contract_is_supported() ) {
153            return;
154        }
155
156        register_widget_types_from_manifest(
157            self::get_widget_manifest(),
158            array(
159                'textdomain'    => self::TEXTDOMAIN,
160                'i18n_manifest' => add_query_arg( 'ver', Package_Version::PACKAGE_VERSION, plugins_url( 'i18n-manifest.json', self::build_dir() . '/build.php' ) ),
161                'former_names'  => array( self::TOP_VIDEOS_TYPE => self::TOP_VIDEOS_FORMER_NAMES ),
162                'plan_features' => array(
163                    self::TOP_VIDEOS_TYPE   => 'videos',
164                    self::VIDEO_PLAYER_TYPE => 'videos',
165                ),
166            ),
167            $registry
168        );
169    }
170
171    /**
172     * Seed the Top videos instance into the Traffic section's default layout.
173     *
174     * Order 8 keeps the place the dashboard seeded it in before the widget moved here. A layout
175     * that already holds the instance, under this name or a former one, is left alone; and one
176     * seeded on a site where the type never registers loses it to the dashboard's own policy.
177     *
178     * @param mixed  $layout     The section's default widget instances; anything but an array passes through.
179     * @param string $section_id Namespaced section identifier.
180     * @return mixed The layout, with the instance appended when it is an array.
181     */
182    public static function add_default_layout_instance( $layout, $section_id ) {
183        if ( self::TRAFFIC_SECTION_ID !== $section_id || ! is_array( $layout ) ) {
184            return $layout;
185        }
186
187        foreach ( $layout as $item ) {
188            if ( ! is_array( $item ) ) {
189                continue;
190            }
191            if ( self::TOP_VIDEOS_INSTANCE_UUID === ( $item['uuid'] ?? null ) || self::is_top_videos_type( $item['type'] ?? null ) ) {
192                return $layout;
193            }
194        }
195
196        $layout[] = get_dashboard_default_widget_instance( self::TOP_VIDEOS_INSTANCE_UUID, self::TOP_VIDEOS_TYPE, 8, 1, DASHBOARD_TILE_LIST );
197
198        return $layout;
199    }
200
201    /**
202     * Whether a widget type name is the Top videos type, current or former.
203     *
204     * @param mixed $type A widget type name.
205     * @return bool
206     */
207    private static function is_top_videos_type( $type ) {
208        return is_string( $type ) && ( self::TOP_VIDEOS_TYPE === $type || in_array( $type, self::TOP_VIDEOS_FORMER_NAMES, true ) );
209    }
210
211    /**
212     * Whether the dashboard's widget contract is one this build works against.
213     *
214     * Undefined is a request that never loaded the dashboard's widget types, such as the sections
215     * REST route: the widgets wait for one that does.
216     *
217     * @param string $minimum The lowest contract the caller needs.
218     * @return bool
219     */
220    private static function widget_contract_is_supported( $minimum = self::MIN_WIDGET_API_VERSION ) {
221        if ( ! defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ) {
222            return false;
223        }
224
225        $version = \Automattic\Jetpack\PremiumAnalytics\WIDGET_API_VERSION;
226
227        return version_compare( $version, $minimum, '>=' ) && version_compare( $version, '3', '<' );
228    }
229
230    /**
231     * The widget manifest the package registers from: what its build generated, none without a build.
232     *
233     * @return array[] Manifest entries, as `jetpack_videopress_get_registered_widget_modules()` returns them.
234     */
235    private static function get_widget_manifest() {
236        self::load_build();
237        if ( ! function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) {
238            return array();
239        }
240
241        return (array) jetpack_videopress_get_registered_widget_modules();
242    }
243
244    /**
245     * Load the generated build once. Guarded by symbol, not by path: on WordPress.com two copies of
246     * the package can share a request.
247     *
248     * @return void
249     */
250    private static function load_build() {
251        if ( function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) {
252            return;
253        }
254        $loader = self::build_dir() . '/build.php';
255        if ( file_exists( $loader ) ) {
256            require_once $loader;
257        }
258    }
259
260    /**
261     * Directory of the wp-build output.
262     *
263     * @return string
264     */
265    private static function build_dir() {
266        return dirname( __DIR__ ) . '/build';
267    }
268}