plugin = $plugin; } /** * Registers this controller's routes. Called on rest_api_init. */ abstract public function register_routes(): void; /** * Permission callback: site administrators (settings, connect, health). */ public function can_manage(): bool { return current_user_can( 'manage_options' ); } /** * Permission callback: users allowed to view reports. */ public function can_view(): bool { return current_user_can( Capabilities::VIEW ); } /** * Converts an ApiError to its REST error (user message, status, slug). * * @param ApiError $e The failure. */ protected static function error( ApiError $e ): \WP_Error { return $e->to_wp_error(); } /** * A validated, sanitized arg definition from a JSON schema. * * The schema's type is enforced by rest_validate_request_arg, so arrays * or objects sent where a scalar is expected are rejected with a 400 * instead of reaching code that would cast them. * * @param array $schema JSON schema for the arg. * @return array */ protected static function arg( array $schema ): array { return array_merge( $schema, array( 'validate_callback' => 'rest_validate_request_arg', 'sanitize_callback' => 'rest_sanitize_request_arg', ) ); } /** * The shared date-range query args for report routes. * * @param bool $compare Whether the route accepts the compare flag. * @return array> */ protected static function range_args( bool $compare = true ): array { $date = array( 'type' => 'string', 'pattern' => '^\d{4}-\d{2}-\d{2}$', ); $args = array( 'range' => self::arg( array( 'type' => 'string', 'enum' => array( 'today', 'yesterday', '7d', '28d', '90d', '12m', 'custom' ), 'default' => '28d', ) ), 'start' => self::arg( $date ), 'end' => self::arg( $date ), 'compare' => self::arg( array( 'type' => 'boolean', 'default' => false, ) ), ); if ( ! $compare ) { unset( $args['compare'] ); } return $args; } /** * The DateRange for a request's range, start, end and compare params. * * @param \WP_REST_Request $request Request (params already validated). * @param bool $compare Whether to honor the compare flag. */ protected static function range_from( \WP_REST_Request $request, bool $compare = true ): DateRange { $start = $request->get_param( 'start' ); $end = $request->get_param( 'end' ); return DateRange::from_request( (string) $request->get_param( 'range' ), is_string( $start ) ? $start : null, is_string( $end ) ? $end : null, $compare && true === $request->get_param( 'compare' ) ); } }