option_name = $option_name; } public static function instance( string $option_name ) : Enforcer { if ( null === self::$instance ) { self::$instance = new self( $option_name ); } return self::$instance; } public function init() : void { add_action( 'admin_menu', array( $this, 'apply_menu_control' ), 999 ); add_action( 'wp_dashboard_setup', array( $this, 'apply_dashboard_widget_control' ), 999 ); add_filter( 'admin_footer_text', array( $this, 'admin_footer_text' ), 20 ); add_filter( 'show_admin_bar', array( $this, 'maybe_hide_admin_bar' ), 20 ); } private function options() : array { $opt = get_option( $this->option_name, array() ); return is_array( $opt ) ? $opt : array(); } private function user_roles( $user_id = 0 ) : array { $user = $user_id ? get_user_by( 'id', $user_id ) : wp_get_current_user(); if ( ! $user || empty( $user->roles ) || ! is_array( $user->roles ) ) { return array(); } return array_values( array_unique( array_map( 'sanitize_key', $user->roles ) ) ); } private function roles_setting_union( array $role_map ) : array { $out = array(); $user_roles = $this->user_roles(); foreach ( $user_roles as $role ) { if ( isset( $role_map[ $role ] ) && is_array( $role_map[ $role ] ) ) { $out = array_merge( $out, $role_map[ $role ] ); } } return array_values( array_unique( array_filter( $out ) ) ); } public function apply_menu_control() : void { if ( ! is_admin() || ! is_user_logged_in() ) { return; } $opt = $this->options(); $role_map = isset( $opt['menu_hidden'] ) && is_array( $opt['menu_hidden'] ) ? $opt['menu_hidden'] : array(); $slugs = $this->roles_setting_union( $role_map ); foreach ( $slugs as $slug ) { remove_menu_page( $slug ); } } public function apply_dashboard_widget_control() : void { if ( ! is_admin() || ! is_user_logged_in() ) { return; } $opt = $this->options(); $role_map = isset( $opt['dashboard_widgets_hidden'] ) && is_array( $opt['dashboard_widgets_hidden'] ) ? $opt['dashboard_widgets_hidden'] : array(); $ids = $this->roles_setting_union( $role_map ); foreach ( $ids as $id ) { remove_meta_box( $id, 'dashboard', 'normal' ); remove_meta_box( $id, 'dashboard', 'side' ); remove_meta_box( $id, 'dashboard', 'column3' ); remove_meta_box( $id, 'dashboard', 'column4' ); } } public function admin_footer_text( $text ) { $opt = $this->options(); $ui = isset( $opt['ui'] ) && is_array( $opt['ui'] ) ? $opt['ui'] : array(); $custom = isset( $ui['custom_footer_text'] ) ? trim( (string) $ui['custom_footer_text'] ) : ''; if ( '' === $custom ) { return $text; } return $custom; } public function maybe_hide_admin_bar( $show ) { if ( is_admin() || ! is_user_logged_in() ) { return $show; } $opt = $this->options(); $ui = isset( $opt['ui'] ) && is_array( $opt['ui'] ) ? $opt['ui'] : array(); $role_map = isset( $ui['hide_admin_bar'] ) && is_array( $ui['hide_admin_bar'] ) ? $ui['hide_admin_bar'] : array(); foreach ( $this->user_roles() as $role ) { if ( ! empty( $role_map[ $role ] ) ) { return false; } } return $show; } }