1<?php
2/**
3 * User API: WP_Role class
4 *
5 * @package WordPress
6 * @subpackage Users
7 * @since 4.4.0
8 */
9
10/**
11 * Core class used to extend the user roles API.
12 *
13 * @since 2.0.0
14 */
15#[AllowDynamicProperties]
16class WP_Role {
17 /**
18 * Role name.
19 *
20 * @since 2.0.0
21 * @var string
22 */
23 public $name;
24
25 /**
26 * List of capabilities the role contains.
27 *
28 * @since 2.0.0
29 * @var bool[] Array of key/value pairs where keys represent a capability name and boolean values
30 * represent whether the role has that capability.
31 */
32 public $capabilities;
33
34 /**
35 * Constructor - Set up object properties.
36 *
37 * The list of capabilities must have the key as the name of the capability
38 * and the value a boolean of whether it is granted to the role.
39 *
40 * @since 2.0.0
41 *
42 * @param string $role Role name.
43 * @param bool[] $capabilities Array of key/value pairs where keys represent a capability name and boolean values
44 * represent whether the role has that capability.
45 */
46 public function __construct( $role, $capabilities ) {
47 $this->name = $role;
48 $this->capabilities = $capabilities;
49 }
50
51 /**
52 * Assign role a capability.
53 *
54 * @since 2.0.0
55 *
56 * @param string $cap Capability name.
57 * @param bool $grant Whether role has capability privilege.
58 */
59 public function add_cap( $cap, $grant = true ) {
60 $this->capabilities[ $cap ] = $grant;
61 wp_roles()->add_cap( $this->name, $cap, $grant );
62 }
63
64 /**
65 * Removes a capability from a role.
66 *
67 * @since 2.0.0
68 *
69 * @param string $cap Capability name.
70 */
71 public function remove_cap( $cap ) {
72 unset( $this->capabilities[ $cap ] );
73 wp_roles()->remove_cap( $this->name, $cap );
74 }
75
76 /**
77 * Determines whether the role has the given capability.
78 *
79 * @since 2.0.0
80 *
81 * @param string $cap Capability name.
82 * @return bool Whether the role has the given capability.
83 */
84 public function has_cap( $cap ) {
85 /**
86 * Filters which capabilities a role has.
87 *
88 * @since 2.0.0
89 *
90 * @param bool[] $capabilities Array of key/value pairs where keys represent a capability name and boolean values
91 * represent whether the role has that capability.
92 * @param string $cap Capability name.
93 * @param string $name Role name.
94 */
95 $capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name );
96
97 if ( ! empty( $capabilities[ $cap ] ) ) {
98 return $capabilities[ $cap ];
99 } else {
100 return false;
101 }
102 }
103}
104