$params Query parameters. * @return array{data: mixed, total: int|null} * @throws RuntimeException When Analytics returns an error. */ public static function get( string $route, array $params = array() ): array { $request = new WP_REST_Request( 'GET', '/wc-analytics' . $route ); $request->set_query_params( $params ); $response = rest_do_request( $request ); $server = rest_get_server(); $data = $server->response_to_data( $response, false ); if ( $response->is_error() ) { $message = is_array( $data ) && isset( $data['message'] ) ? (string) $data['message'] : 'WooCommerce Analytics returned an error.'; throw new RuntimeException( $message ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Returned as JSON, never printed as HTML. } $headers = $response->get_headers(); $total = isset( $headers['X-WP-Total'] ) ? (int) $headers['X-WP-Total'] : null; // Some Analytics controllers return stdClass objects inside the data; normalise to arrays. $data = json_decode( (string) wp_json_encode( $data ), true ); return array( 'data' => $data, 'total' => $total, ); } /** * Order statuses Analytics leaves out of reports, without the "wc-" prefix. * Mirrors Automattic\WooCommerce\Admin\API\Reports\DataStore::get_excluded_report_order_statuses(). * * @return list */ public static function excluded_statuses(): array { $default = array( 'pending', 'cancelled', 'failed' ); $saved = get_option( 'woocommerce_excluded_report_order_statuses', $default ); $saved = is_array( $saved ) ? array_values( array_filter( array_map( 'strval', $saved ) ) ) : $default; $all = array_merge( array( 'auto-draft', 'trash' ), $saved ); /** This filter is documented in WooCommerce's Reports DataStore. */ $filtered = apply_filters( 'woocommerce_analytics_excluded_order_statuses', $all ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own filter, applied the same way. $filtered = is_array( $filtered ) ? $filtered : $all; return array_values( array_unique( array_map( 'sanitize_key', $filtered ) ) ); } /** * The wc_order_stats date column Analytics filters on (Analytics › Settings › Date type). */ public static function date_column(): string { $column = get_option( 'woocommerce_date_type', 'date_paid' ); return in_array( $column, array( 'date_created', 'date_paid', 'date_completed' ), true ) ? $column : 'date_paid'; } /** * Rounds money for tool results. * * @param mixed $value Number. */ public static function money( $value ): float { return round( (float) $value, wc_get_price_decimals() ); } }