array( 'required' => true, 'type' => 'object', ), ); $this->route( '/cohort/count', array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'count' ), 'args' => $spec_arg, ) ); $this->route( '/cohort/preview', array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'preview' ), 'args' => array_merge( $spec_arg, array( 'page' => $this->int_param( false, 1 ), 'per_page' => array( 'type' => 'integer', 'default' => 25, 'minimum' => 1, 'maximum' => 100, ), ) ), ) ); } /** * Parses the spec from a request or returns an error. * * @param \WP_REST_Request $request Request. * @return CohortSpec|\WP_Error */ public static function spec_from_request( \WP_REST_Request $request ) { $raw = $request['spec']; if ( ! is_array( $raw ) ) { return new \WP_Error( 'recast_invalid_spec', __( 'The selection must be an object.', 'recast-subscriptions' ), array( 'status' => 400 ) ); } try { return CohortSpec::from_array( $raw ); } catch ( InvalidSpecException $e ) { return new \WP_Error( 'recast_invalid_spec', $e->getMessage(), array( 'status' => 400 ) ); } } /** * Handles POST /cohort/count. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function count( \WP_REST_Request $request ) { $spec = self::spec_from_request( $request ); if ( is_wp_error( $spec ) ) { return $spec; } $result = ( new Counter() )->count( $spec ); $result['hash'] = $spec->hash(); $result['spec_summary'] = SpecSummary::describe( $spec ); return $this->respond( $result ); } /** * Handles POST /cohort/preview. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function preview( \WP_REST_Request $request ) { $spec = self::spec_from_request( $request ); if ( is_wp_error( $spec ) ) { return $spec; } $page = max( 1, (int) $request['page'] ); $per_page = (int) $request['per_page']; $slice = ( new CohortQuery( $spec ) )->slice( ( $page - 1 ) * $per_page, $per_page ); $rows = array_map( array( RowFormatter::class, 'format' ), $slice['subscriptions'] ); return $this->respond( array( 'rows' => $rows, 'page' => $page, 'per_page' => $per_page, 'has_more' => (bool) $slice['has_more'], 'hash' => $spec->hash(), 'spec_summary' => SpecSummary::describe( $spec ), ) ); } }