fields = $fields; $this->sanitizer = $sanitizer; } /** * Registers hooks. * * @return void */ public function register(): void { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Registers REST routes. * * @return void */ public function register_routes(): void { register_rest_route( SettingsController::ROUTE_NAMESPACE, '/rule-fields', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'render' ), 'permission_callback' => array( $this, 'can_edit' ), 'args' => array( 'name' => array( 'type' => 'string', 'required' => true, 'pattern' => trim( self::NAME_PATTERN, '/' ), ), 'rule' => array( 'type' => 'object', 'required' => true, ), ), ), ) ); } /** * Classic menus and widgets both need `edit_theme_options`. * * @return bool */ public function can_edit(): bool { return current_user_can( 'edit_theme_options' ); } /** * Renders the pasted rule's condition groups. Copied rules have no IDs, * so the sanitizer gives every group and condition a new one. * * @param WP_REST_Request $request Request. * @phpstan-param WP_REST_Request> $request * @return WP_REST_Response */ public function render( WP_REST_Request $request ): WP_REST_Response { $rule = $this->sanitizer->sanitize( $request->get_param( 'rule' ) ); ob_start(); $this->fields->render_groups( (string) $request->get_param( 'name' ), $rule['groups'] ); return new WP_REST_Response( array( 'action' => $rule['action'], 'groups' => count( $rule['groups'] ), 'html' => (string) ob_get_clean(), ) ); } }