profit = $profit; $this->reconcile = $reconcile; } /** * {@inheritDoc} */ public function register_routes(): void { $range_args = array( 'range' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_key', ), 'from' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'to' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ); register_rest_route( $this->namespace, '/profit', array( array( 'methods' => 'GET', 'callback' => array( $this, 'summary' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => $range_args, ), ) ); register_rest_route( $this->namespace, '/profit/products', array( array( 'methods' => 'GET', 'callback' => array( $this, 'by_product' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => $range_args, ), ) ); register_rest_route( $this->namespace, '/profit/backfill', array( array( 'methods' => 'GET', 'callback' => array( $this, 'backfill_state' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'backfill_start' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'cutoff' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ), ), array( 'methods' => 'DELETE', 'callback' => array( $this, 'backfill_cancel' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); } /** * GET /profit * * @param WP_REST_Request $request Request. */ public function summary( WP_REST_Request $request ): WP_REST_Response { return new WP_REST_Response( $this->profit->summary( $this->range_args( $request ) ), 200 ); } /** * GET /profit/products * * @param WP_REST_Request $request Request. */ public function by_product( WP_REST_Request $request ): WP_REST_Response { return new WP_REST_Response( $this->profit->by_product( $this->range_args( $request ) ), 200 ); } /** * GET /profit/backfill */ public function backfill_state(): WP_REST_Response { return new WP_REST_Response( $this->reconcile->state(), 200 ); } /** * POST /profit/backfill * * @param WP_REST_Request $request Request. * @return WP_REST_Response|\WP_Error */ public function backfill_start( WP_REST_Request $request ) { $result = $this->reconcile->start( (string) $request->get_param( 'cutoff' ) ); if ( is_wp_error( $result ) ) { return $result; } return new WP_REST_Response( $result, 202 ); } /** * DELETE /profit/backfill */ public function backfill_cancel(): WP_REST_Response { return new WP_REST_Response( $this->reconcile->cancel(), 200 ); } /** * Extract range args from the request. * * @param WP_REST_Request $request Request. * @return array */ private function range_args( WP_REST_Request $request ): array { return array( 'range' => (string) $request->get_param( 'range' ), 'from' => (string) $request->get_param( 'from' ), 'to' => (string) $request->get_param( 'to' ), ); } }