| 1 |
<?php |
| 2 |
namespace StoreEngine\API; |
| 3 |
|
| 4 |
if ( ! defined( 'ABSPATH' ) ) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
use WP_REST_Controller; |
| 9 |
use WP_REST_Server; |
| 10 |
|
| 11 |
/** |
| 12 |
* Read-only listing of every role registered on the site — including roles |
| 13 |
* contributed by StoreEngine add-ons and any other active plugin — so store |
| 14 |
* admins can see the full access surface in one place. |
| 15 |
*/ |
| 16 |
class Roles extends WP_REST_Controller { |
| 17 |
|
| 18 |
/** |
| 19 |
* Core WordPress roles. Everything else is contributed by a plugin/theme. |
| 20 |
*/ |
| 21 |
const CORE_ROLES = [ 'administrator', 'editor', 'author', 'contributor', 'subscriber' ]; |
| 22 |
|
| 23 |
public function __construct() { |
| 24 |
$this->namespace = STOREENGINE_PLUGIN_SLUG . '/v1'; |
| 25 |
$this->rest_base = 'roles'; |
| 26 |
} |
| 27 |
|
| 28 |
public static function init() { |
| 29 |
$self = new self(); |
| 30 |
add_action( 'rest_api_init', [ $self, 'register_routes' ] ); |
| 31 |
} |
| 32 |
|
| 33 |
public function register_routes() { |
| 34 |
register_rest_route( $this->namespace, '/' . $this->rest_base, [ |
| 35 |
[ |
| 36 |
'methods' => WP_REST_Server::READABLE, |
| 37 |
'callback' => [ $this, 'get_items' ], |
| 38 |
'permission_callback' => [ $this, 'permissions_check' ], |
| 39 |
], |
| 40 |
] ); |
| 41 |
} |
| 42 |
|
| 43 |
public function permissions_check(): bool { |
| 44 |
return current_user_can( 'manage_options' ); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* @param \WP_REST_Request $request |
| 49 |
* |
| 50 |
* @return \WP_REST_Response |
| 51 |
*/ |
| 52 |
public function get_items( $request ) { |
| 53 |
if ( ! class_exists( '\WP_Roles' ) ) { |
| 54 |
return rest_ensure_response( [] ); |
| 55 |
} |
| 56 |
|
| 57 |
$wp_roles = wp_roles(); |
| 58 |
|
| 59 |
// One query for all per-role user counts (WP populates `avail_roles`). |
| 60 |
$counts = count_users(); |
| 61 |
$avail = $counts['avail_roles'] ?? []; |
| 62 |
|
| 63 |
$data = []; |
| 64 |
foreach ( $wp_roles->roles as $slug => $role ) { |
| 65 |
$caps = array_filter( (array) ( $role['capabilities'] ?? [] ) ); |
| 66 |
|
| 67 |
if ( in_array( $slug, self::CORE_ROLES, true ) ) { |
| 68 |
$type = 'wordpress'; |
| 69 |
} elseif ( 0 === strpos( $slug, 'storeengine_' ) ) { |
| 70 |
$type = 'storeengine'; |
| 71 |
} else { |
| 72 |
$type = 'custom'; |
| 73 |
} |
| 74 |
|
| 75 |
$data[] = [ |
| 76 |
'slug' => $slug, |
| 77 |
'name' => translate_user_role( $role['name'] ?? $slug ), |
| 78 |
'type' => $type, |
| 79 |
'user_count' => (int) ( $avail[ $slug ] ?? 0 ), |
| 80 |
'capability_count' => count( $caps ), |
| 81 |
]; |
| 82 |
} |
| 83 |
|
| 84 |
// Alphabetical by display name for a stable, scannable list. |
| 85 |
usort( $data, static fn( $a, $b ) => strcasecmp( $a['name'], $b['name'] ) ); |
| 86 |
|
| 87 |
return rest_ensure_response( $data ); |
| 88 |
} |
| 89 |
} |
| 90 |
|