Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
91.61% |
131 / 143 |
|
76.92% |
10 / 13 |
CRAP | |
0.00% |
0 / 1 |
| Core_Report_Handler | |
91.61% |
131 / 143 |
|
76.92% |
10 / 13 |
50.42 | |
0.00% |
0 / 1 |
| get_capability | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
| supports | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| check_ready | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| run | |
95.56% |
43 / 45 |
|
0.00% |
0 / 1 |
6 | |||
| to_core_query | |
100.00% |
28 / 28 |
|
100.00% |
1 / 1 |
7 | |||
| get_store_date_type | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| to_bound | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
7 | |||
| to_site_iso | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| map_fields | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
6.07 | |||
| count_intervals | |
43.75% |
7 / 16 |
|
0.00% |
0 / 1 |
19.39 | |||
| too_many_intervals | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| to_array | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| core_request | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * A report served by a core `wc-analytics` stats route, in WordPress.com's shape. |
| 4 | * |
| 5 | * @package automattic/jetpack-woocommerce-stats |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack\WooCommerceStats\Report_Execution; |
| 9 | |
| 10 | use DateTimeImmutable; |
| 11 | use DateTimeZone; |
| 12 | use WP_Error; |
| 13 | use WP_REST_Request; |
| 14 | use WP_REST_Response; |
| 15 | |
| 16 | /** |
| 17 | * Runs a core stats route in-process as the current user, so core's own capability check applies, |
| 18 | * and maps its totals and intervals into `summary` and `data` rows. A subclass names the route, |
| 19 | * the controller and the field map. |
| 20 | * |
| 21 | * @internal |
| 22 | * |
| 23 | * @since $$next-version$$ |
| 24 | */ |
| 25 | abstract class Core_Report_Handler implements Report_Handler, Report_Capability, Report_Support, Report_Readiness { |
| 26 | |
| 27 | /** |
| 28 | * Date types the `date_type` param accepts, as core names them. |
| 29 | */ |
| 30 | private const DATE_TYPES = array( |
| 31 | 'created' => 'date_created', |
| 32 | 'paid' => 'date_paid', |
| 33 | 'completed' => 'date_completed', |
| 34 | ); |
| 35 | |
| 36 | /** |
| 37 | * Intervals core can bucket by. |
| 38 | */ |
| 39 | private const INTERVALS = array( 'hour', 'day', 'week', 'month', 'quarter', 'year' ); |
| 40 | |
| 41 | /** |
| 42 | * Core's page size cap for intervals. |
| 43 | */ |
| 44 | private const PER_PAGE = 100; |
| 45 | |
| 46 | /** |
| 47 | * Most intervals one request may ask for: every core page reruns the totals queries. |
| 48 | */ |
| 49 | private const MAX_INTERVALS = 500; |
| 50 | |
| 51 | /** |
| 52 | * Core REST route, such as `/wc-analytics/reports/revenue/stats`. |
| 53 | * |
| 54 | * @var string |
| 55 | */ |
| 56 | protected $core_route; |
| 57 | |
| 58 | /** |
| 59 | * Core controller class, present only on a WooCommerce that serves the route. |
| 60 | * |
| 61 | * @var string |
| 62 | */ |
| 63 | protected $core_controller; |
| 64 | |
| 65 | /** |
| 66 | * Contract field => core field, or [ core field, count field ] for an average that is null over no items. |
| 67 | * |
| 68 | * @var array<string, string|string[]> |
| 69 | */ |
| 70 | protected $fields = array(); |
| 71 | |
| 72 | /** |
| 73 | * {@inheritDoc} |
| 74 | */ |
| 75 | public function get_capability() { |
| 76 | return array( |
| 77 | 'fields' => array_keys( $this->fields ), |
| 78 | 'params' => array( 'from', 'to', 'interval', 'date_type' ), |
| 79 | ); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * {@inheritDoc} |
| 84 | * |
| 85 | * @param Report_Request $request The request. |
| 86 | */ |
| 87 | public function supports( Report_Request $request ) { |
| 88 | $query = self::to_core_query( $request ); |
| 89 | if ( is_wp_error( $query ) ) { |
| 90 | return $query; |
| 91 | } |
| 92 | |
| 93 | $count = self::count_intervals( $query['after'], $query['before'], $query['interval'] ); |
| 94 | |
| 95 | return $count > self::MAX_INTERVALS ? self::too_many_intervals() : true; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * {@inheritDoc} |
| 100 | */ |
| 101 | public function check_ready() { |
| 102 | if ( class_exists( $this->core_controller ) ) { |
| 103 | return true; |
| 104 | } |
| 105 | |
| 106 | return new WP_Error( |
| 107 | 'local_unavailable', |
| 108 | __( 'This version of WooCommerce does not provide this report.', 'jetpack-woocommerce-stats-pkg' ), |
| 109 | array( 'status' => 503 ) |
| 110 | ); |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * {@inheritDoc} |
| 115 | * |
| 116 | * @param Report_Request $request The request. |
| 117 | */ |
| 118 | public function run( Report_Request $request ) { |
| 119 | $query = self::to_core_query( $request ); |
| 120 | if ( is_wp_error( $query ) ) { |
| 121 | return $query; |
| 122 | } |
| 123 | |
| 124 | $bounds = $query; |
| 125 | $query = array( |
| 126 | 'after' => $bounds['after']->format( 'c' ), |
| 127 | 'before' => $bounds['before']->format( 'c' ), |
| 128 | ) + $query + array( |
| 129 | 'orderby' => 'date', |
| 130 | 'order' => 'asc', |
| 131 | 'per_page' => self::PER_PAGE, |
| 132 | ); |
| 133 | if ( $request->force_refresh ) { |
| 134 | $query['force_cache_refresh'] = true; |
| 135 | } |
| 136 | |
| 137 | $totals = null; |
| 138 | $intervals = array(); |
| 139 | $page = 1; |
| 140 | do { |
| 141 | $response = $this->core_request( $query + array( 'page' => $page ) ); |
| 142 | if ( is_wp_error( $response ) ) { |
| 143 | return $response; |
| 144 | } |
| 145 | |
| 146 | $body = self::to_array( $response->get_data() ); |
| 147 | $totals ??= $body['totals'] ?? array(); |
| 148 | $intervals = array_merge( $intervals, $body['intervals'] ?? array() ); |
| 149 | $pages = (int) ( $response->get_headers()['X-WP-TotalPages'] ?? 1 ); |
| 150 | // supports() estimates; core counts its own buckets, so refuse rather than return part of a series. |
| 151 | if ( $pages * self::PER_PAGE > self::MAX_INTERVALS ) { |
| 152 | return self::too_many_intervals(); |
| 153 | } |
| 154 | } while ( ++$page <= $pages ); |
| 155 | |
| 156 | $data = array(); |
| 157 | foreach ( $intervals as $interval ) { |
| 158 | $data[] = array( |
| 159 | 'time_interval' => $interval['interval'], |
| 160 | 'date_start' => self::to_site_iso( $interval['date_start'] ), |
| 161 | 'date_end' => self::to_site_iso( $interval['date_end'] ), |
| 162 | ) + $this->map_fields( $interval['subtotals'] ?? array() ); |
| 163 | } |
| 164 | |
| 165 | return array( |
| 166 | 'data' => array( |
| 167 | 'summary' => $this->map_fields( $totals ) + array( |
| 168 | 'date_start' => $query['after'], |
| 169 | 'date_end' => $query['before'], |
| 170 | ), |
| 171 | 'data' => $data, |
| 172 | ), |
| 173 | 'status' => 200, |
| 174 | 'headers' => array(), |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | /** |
| 179 | * The request's range, interval and date type as core's params, the bounds as instants in the store's zone. |
| 180 | * |
| 181 | * @param Report_Request $request The request. |
| 182 | * @return array|WP_Error `after`, `before`, `interval` and `date_type`, or a 400. |
| 183 | */ |
| 184 | private static function to_core_query( Report_Request $request ) { |
| 185 | $params = $request->params; |
| 186 | foreach ( array( 'from', 'to', 'interval' ) as $name ) { |
| 187 | if ( ! isset( $params[ $name ] ) ) { |
| 188 | return new WP_Error( |
| 189 | 'missing_parameter', |
| 190 | /* translators: %s: query param name. */ |
| 191 | sprintf( __( 'The report needs %s.', 'jetpack-woocommerce-stats-pkg' ), $name ), |
| 192 | array( 'status' => 400 ) |
| 193 | ); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | $date_type = $params['date_type'] ?? null; |
| 198 | $values = array( |
| 199 | 'from' => self::to_bound( $params['from'], '00:00:00' ), |
| 200 | 'to' => self::to_bound( $params['to'], '23:59:59' ), |
| 201 | 'interval' => in_array( $params['interval'], self::INTERVALS, true ) ? $params['interval'] : null, |
| 202 | 'date_type' => null === $date_type ? self::get_store_date_type() : ( is_string( $date_type ) ? self::DATE_TYPES[ $date_type ] ?? null : null ), |
| 203 | ); |
| 204 | $invalid = array_search( null, $values, true ); |
| 205 | if ( false !== $invalid ) { |
| 206 | return new WP_Error( |
| 207 | 'invalid_parameter', |
| 208 | /* translators: %s: query param name. */ |
| 209 | sprintf( __( 'The report cannot apply this value of %s.', 'jetpack-woocommerce-stats-pkg' ), $invalid ), |
| 210 | array( 'status' => 400 ) |
| 211 | ); |
| 212 | } |
| 213 | |
| 214 | return array( |
| 215 | 'after' => $values['from'], |
| 216 | 'before' => $values['to'], |
| 217 | 'interval' => $values['interval'], |
| 218 | 'date_type' => $values['date_type'], |
| 219 | ); |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * The store's `woocommerce_date_type`, read live as the WordPress.com forward does. |
| 224 | * |
| 225 | * @return string Core's name for it, `date_paid` when unset or unknown. |
| 226 | */ |
| 227 | private static function get_store_date_type() { |
| 228 | $option = get_option( 'woocommerce_date_type' ); |
| 229 | |
| 230 | return in_array( $option, self::DATE_TYPES, true ) ? $option : self::DATE_TYPES['paid']; |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * A report date as an instant in the store's zone, as WordPress.com reads it: a date without an |
| 235 | * offset is store wall time, one with an offset is converted, and a bare date spans its day. |
| 236 | * |
| 237 | * @param mixed $date `Y-m-d`, `Y-m-d H:i:s`, or ISO 8601 such as `2026-10-01T00:00:00.000Z`. |
| 238 | * @param string $time Time to give a bare date. |
| 239 | * @return DateTimeImmutable|null Null when the date does not parse. |
| 240 | */ |
| 241 | private static function to_bound( $date, $time ) { |
| 242 | if ( ! is_string( $date ) || ! preg_match( '/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}:\d{2})(?:\.\d+)?)?(Z|[+-](?:0\d|1[0-4]):?[0-5]\d)?$/D', $date, $parts ) ) { |
| 243 | return null; |
| 244 | } |
| 245 | |
| 246 | // Checked in UTC so that only a calendar rollover, such as February 30th, fails the round trip. |
| 247 | $wall = $parts[1] . 'T' . ( empty( $parts[2] ) ? $time : $parts[2] ); |
| 248 | $utc = DateTimeImmutable::createFromFormat( '!Y-m-d\TH:i:s', $wall, new DateTimeZone( 'UTC' ) ); |
| 249 | if ( ! $utc || $utc->format( 'Y-m-d\TH:i:s' ) !== $wall ) { |
| 250 | return null; |
| 251 | } |
| 252 | |
| 253 | $zone = empty( $parts[3] ) ? wp_timezone() : new DateTimeZone( $parts[3] ); |
| 254 | |
| 255 | return ( new DateTimeImmutable( $wall, $zone ) )->setTimezone( wp_timezone() ); |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * A core interval date, store wall time, as ISO 8601 with its offset, as WordPress.com writes dates. |
| 260 | * |
| 261 | * @param string $wall_time `Y-m-d H:i:s`. |
| 262 | * @return string |
| 263 | */ |
| 264 | private static function to_site_iso( $wall_time ) { |
| 265 | return ( new DateTimeImmutable( $wall_time, wp_timezone() ) )->format( 'c' ); |
| 266 | } |
| 267 | |
| 268 | /** |
| 269 | * A core row in contract fields, as the strings WordPress.com sends. A field core lacks stays absent. |
| 270 | * |
| 271 | * @param array $row Core totals or interval subtotals. |
| 272 | * @return array |
| 273 | */ |
| 274 | private function map_fields( array $row ) { |
| 275 | $mapped = array(); |
| 276 | foreach ( $this->fields as $field => $source ) { |
| 277 | list( $core_field, $count_field ) = (array) $source + array( 1 => null ); |
| 278 | if ( ! array_key_exists( $core_field, $row ) ) { |
| 279 | continue; |
| 280 | } |
| 281 | |
| 282 | // Core casts an average over no orders to 0; WordPress.com sends null. |
| 283 | $empty = null === $row[ $core_field ] || ( null !== $count_field && empty( $row[ $count_field ] ) ); |
| 284 | $mapped[ $field ] = $empty ? null : (string) wp_json_encode( $row[ $core_field ], JSON_UNESCAPED_SLASHES ); |
| 285 | } |
| 286 | |
| 287 | return $mapped; |
| 288 | } |
| 289 | |
| 290 | /** |
| 291 | * How many buckets core returns for the range: partial first and last buckets count, and weeks |
| 292 | * start on the site's `start_of_week`, as in core's TimeInterval. |
| 293 | * |
| 294 | * @param DateTimeImmutable $start Start bound, in the store's zone. |
| 295 | * @param DateTimeImmutable $end End bound, in the store's zone. |
| 296 | * @param string $interval One of `INTERVALS`. |
| 297 | * @return int |
| 298 | */ |
| 299 | private static function count_intervals( DateTimeImmutable $start, DateTimeImmutable $end, $interval ) { |
| 300 | if ( $end < $start ) { |
| 301 | return 0; |
| 302 | } |
| 303 | |
| 304 | $days = (int) $start->setTime( 0, 0 )->diff( $end->setTime( 0, 0 ) )->days; |
| 305 | $year = (int) $end->format( 'Y' ) - (int) $start->format( 'Y' ); |
| 306 | |
| 307 | switch ( $interval ) { |
| 308 | case 'hour': |
| 309 | return intdiv( $end->getTimestamp() - $start->getTimestamp(), HOUR_IN_SECONDS ) + 1; |
| 310 | case 'day': |
| 311 | return $days + 1; |
| 312 | case 'week': |
| 313 | $offset = ( (int) $start->format( 'w' ) - absint( get_option( 'start_of_week' ) ) + 7 ) % 7; |
| 314 | return intdiv( $days + $offset, 7 ) + 1; |
| 315 | case 'month': |
| 316 | return $year * 12 + (int) $end->format( 'n' ) - (int) $start->format( 'n' ) + 1; |
| 317 | case 'quarter': |
| 318 | return $year * 4 + intdiv( (int) $end->format( 'n' ) - 1, 3 ) - intdiv( (int) $start->format( 'n' ) - 1, 3 ) + 1; |
| 319 | default: |
| 320 | return $year + 1; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * The error for a range with more buckets than one request may fetch. |
| 326 | * |
| 327 | * @return WP_Error |
| 328 | */ |
| 329 | private static function too_many_intervals() { |
| 330 | return new WP_Error( |
| 331 | 'too_many_intervals', |
| 332 | /* translators: %d: the most intervals allowed. */ |
| 333 | sprintf( __( 'This range needs more than %d intervals. Pick a shorter range or a larger interval.', 'jetpack-woocommerce-stats-pkg' ), self::MAX_INTERVALS ), |
| 334 | array( 'status' => 422 ) |
| 335 | ); |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * Core's response data as the JSON a client would read: in-process it may still hold objects. |
| 340 | * |
| 341 | * @param mixed $data Response data. |
| 342 | * @return array |
| 343 | */ |
| 344 | private static function to_array( $data ) { |
| 345 | return (array) json_decode( (string) wp_json_encode( $data, JSON_UNESCAPED_SLASHES ), true ); |
| 346 | } |
| 347 | |
| 348 | /** |
| 349 | * Run the core route in-process as the current user. |
| 350 | * |
| 351 | * @param array $query Query params. |
| 352 | * @return WP_REST_Response|WP_Error Core's response, or its error with core's status. |
| 353 | */ |
| 354 | private function core_request( array $query ) { |
| 355 | $request = new WP_REST_Request( 'GET', $this->core_route ); |
| 356 | $request->set_query_params( $query ); |
| 357 | $response = rest_do_request( $request ); |
| 358 | |
| 359 | if ( ! $response->is_error() ) { |
| 360 | return $response; |
| 361 | } |
| 362 | |
| 363 | $error = $response->as_error(); |
| 364 | if ( 404 === $response->get_status() && 'rest_no_route' === $error->get_error_code() ) { |
| 365 | return new WP_Error( |
| 366 | 'local_unavailable', |
| 367 | __( 'WooCommerce does not serve this report on this site.', 'jetpack-woocommerce-stats-pkg' ), |
| 368 | array( 'status' => 503 ) |
| 369 | ); |
| 370 | } |
| 371 | |
| 372 | return $error; |
| 373 | } |
| 374 | } |