add-user-role.php
93 lines
| 1 | <?php |
| 2 | /** |
| 3 | * AddUserRole. |
| 4 | * php version 5.6 |
| 5 | * |
| 6 | * @category AddUserRole |
| 7 | * @package SureTriggers |
| 8 | * @author BSF <username@example.com> |
| 9 | * @license https://www.gnu.org/licenses/gpl-3.0.html GPLv3 |
| 10 | * @link https://www.brainstormforce.com/ |
| 11 | * @since 1.0.0 |
| 12 | */ |
| 13 | |
| 14 | use SureTriggers\Integrations\AutomateAction; |
| 15 | use SureTriggers\Traits\SingletonLoader; |
| 16 | |
| 17 | /** |
| 18 | * AddUserRole |
| 19 | * |
| 20 | * @category AddUserRole |
| 21 | * @package SureTriggers |
| 22 | * @author BSF <username@example.com> |
| 23 | * @license https://www.gnu.org/licenses/gpl-3.0.html GPLv3 |
| 24 | * @link https://www.brainstormforce.com/ |
| 25 | * @since 1.0.0 |
| 26 | */ |
| 27 | class AddUserRole extends AutomateAction { |
| 28 | |
| 29 | /** |
| 30 | * Integration type. |
| 31 | * |
| 32 | * @var string |
| 33 | */ |
| 34 | public $integration = 'UltimateMember'; |
| 35 | |
| 36 | /** |
| 37 | * Action name. |
| 38 | * |
| 39 | * @var string |
| 40 | */ |
| 41 | public $action = 'um_add_user_role'; |
| 42 | |
| 43 | use SingletonLoader; |
| 44 | |
| 45 | /** |
| 46 | * Register a action. |
| 47 | * |
| 48 | * @param array $actions actions. |
| 49 | * @return array |
| 50 | */ |
| 51 | public function register( $actions ) { |
| 52 | $actions[ $this->integration ][ $this->action ] = [ |
| 53 | 'label' => __( "Add a role to the user's roles", 'suretriggers' ), |
| 54 | 'action' => $this->action, |
| 55 | 'function' => [ $this, 'action_listener' ], |
| 56 | ]; |
| 57 | return $actions; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Action listener. |
| 62 | * |
| 63 | * @param int $user_id user_id. |
| 64 | * @param int $automation_id automation_id. |
| 65 | * @param array $fields fields. |
| 66 | * @param array $selected_options selectedOptions. |
| 67 | * @psalm-suppress UndefinedMethod |
| 68 | * @throws Exception Exception. |
| 69 | * |
| 70 | * @return array|bool|void |
| 71 | */ |
| 72 | public function _action_listener( $user_id, $automation_id, $fields, $selected_options ) { |
| 73 | $field = reset( $fields ); |
| 74 | $user = new WP_User( $user_id ); |
| 75 | |
| 76 | if ( ! ( $user instanceof WP_User ) ) { |
| 77 | $this->set_error( |
| 78 | [ |
| 79 | 'wp_user_id' => $user_id, |
| 80 | 'msg' => __( 'This user is not type of WP_User', 'suretriggers' ), |
| 81 | |
| 82 | ] |
| 83 | ); |
| 84 | return false; |
| 85 | } |
| 86 | $user->add_role( $selected_options[ $field['name'] ] ); |
| 87 | |
| 88 | return true; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | AddUserRole::get_instance(); |
| 93 |