Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
36.59% covered (danger)
36.59%
30 / 82
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats
36.59% covered (danger)
36.59%
30 / 82
25.00% covered (danger)
25.00%
1 / 4
100.63
0.00% covered (danger)
0.00%
0 / 1
 fetch_video_plays
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
5
 get_today_plays
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 get_featured_stats
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
3.94
 prepare_featured_stats
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * Provides data stats about videos inside VideoPress
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use Automattic\Jetpack\Connection\Client;
11use WP_Error;
12
13/**
14 * Provides data stats about videos inside VideoPress
15 */
16class Stats {
17    /**
18     * Hit WPCOM video-plays stats endpoint.
19     *
20     * @param array $args Request args.
21     * @return array|WP_Error WP HTTP response on success
22     */
23    public static function fetch_video_plays( $args = array() ) {
24        $blog_id = VideoPressToken::blog_id();
25
26        $endpoint = sprintf(
27            'sites/%d/stats/video-plays?check_stats_module=false',
28            $blog_id
29        );
30
31        if ( is_array( $args ) && ! empty( $args ) ) {
32            $endpoint .= '&' . http_build_query( $args, '', '&' );
33        }
34
35        $result = Client::wpcom_json_api_request_as_blog( $endpoint );
36
37        if ( is_wp_error( $result ) ) {
38            return $result;
39        }
40
41        $response_code = (int) wp_remote_retrieve_response_code( $result );
42        $response_body = json_decode( wp_remote_retrieve_body( $result ), true );
43
44        if ( 200 !== $response_code ) {
45            return new WP_Error(
46                'videopress_stats_error',
47                $response_body
48            );
49        }
50
51        return array(
52            'code' => $response_code,
53            'data' => $response_body,
54        );
55    }
56
57    /**
58     * Returns the counter of today's plays for all videos.
59     *
60     * @return int|WP_Error the total of plays for today, or WP_Error on failure.
61     */
62    public static function get_today_plays() {
63        $response = self::fetch_video_plays();
64
65        if ( is_wp_error( $response ) ) {
66            return $response;
67        }
68
69        $data = $response['data'];
70
71        if ( ! $data || ! isset( $data['days'] ) || ! is_countable( $data['days'] ) || count( $data['days'] ) === 0 ) {
72            return new WP_Error(
73                'videopress_stats_error',
74                __( 'Could not find any stats from the service', 'jetpack-videopress-pkg' )
75            );
76        }
77
78        /*
79         * The only result here is today's stats
80         */
81        $today_stats = array_pop( $data['days'] );
82
83        return $today_stats['total_plays'];
84    }
85
86    /**
87     * Returns the featured stats for VideoPress.
88     *
89     * @param int    $period_count (optional) The number of days to consider.
90     * @param string $period (optional) The period to consider.
91     *
92     * @return array|WP_Error a list of stats, or WP_Error on failure.
93     */
94    public static function get_featured_stats( $period_count = 14, $period = 'day' ) {
95        $response = self::fetch_video_plays(
96            array(
97                'period'         => $period,
98                'num'            => $period_count,
99                'complete_stats' => true,
100            )
101        );
102
103        if ( is_wp_error( $response ) ) {
104            return $response;
105        }
106
107        $data = $response['data'];
108
109        if ( ! $data ) {
110            return new WP_Error(
111                'videopress_stats_error',
112                __( 'Could not find any stats from the service', 'jetpack-videopress-pkg' )
113            );
114        }
115
116        // Get only the list of dates
117        $dates = $data['days'];
118
119        // Organize the data into the planned stats
120        return self::prepare_featured_stats( $dates, $period_count, $period );
121    }
122
123    /**
124     * Prepares the featured stats for VideoPress.
125     *
126     * @param array  $dates The list of dates returned by the API.
127     * @param int    $period_count The total number of days to consider.
128     * @param string $period The period to consider.
129     * @return array a list of stats.
130     */
131    public static function prepare_featured_stats( $dates, $period_count, $period = 'day' ) {
132        /**
133         * Ensure the sorting of the dates, recent ones first.
134         * This way, the first 7 positions are from the last 7 days,
135         * and the next 7 positions are from the 7 days before it.
136         */
137        krsort( $dates );
138        $period_of_data = floor( $period_count / 2 );
139        $period         = $period === 'day' ? __( 'day', 'jetpack-videopress-pkg' ) : __( 'year', 'jetpack-videopress-pkg' );
140
141        // template for the response
142        $featured_stats = array(
143            // translators: %1$d is the number of units of time, %2$s is the period in which the units of time are measured ex. 'day' or 'year'.
144            'label'  => sprintf( _n( 'last %1$d %2$s', 'last %1$d %2$ss', (int) $period_of_data, 'jetpack-videopress-pkg' ), $period_of_data, $period ),
145            'period' => $period,
146            'data'   => array(
147                'views'       => array(
148                    'current'  => 0,
149                    'previous' => 0,
150                ),
151                'impressions' => array(
152                    'current'  => 0,
153                    'previous' => 0,
154                ),
155                'watch_time'  => array(
156                    'current'  => 0,
157                    'previous' => 0,
158                ),
159            ),
160        );
161
162        // Go through the dates to compute the stats
163        $counter = 0;
164        foreach ( $dates as $date_info ) {
165            $date_totals = $date_info['total'];
166
167            if ( $counter < floor( $period_count / 2 ) ) {
168
169                // the first 7 elements are for the current period
170                $featured_stats['data']['views']['current']       += $date_totals['views'];
171                $featured_stats['data']['impressions']['current'] += $date_totals['impressions'];
172                $featured_stats['data']['watch_time']['current']  += $date_totals['watch_time'];
173
174            } else {
175
176                // the next 7 elements are for the previous period
177                $featured_stats['data']['views']['previous']       += $date_totals['views'];
178                $featured_stats['data']['impressions']['previous'] += $date_totals['impressions'];
179                $featured_stats['data']['watch_time']['previous']  += $date_totals['watch_time'];
180
181            }
182
183            ++$counter;
184        }
185
186        return $featured_stats;
187    }
188}