PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / 2.4.6
Booking for Appointments and Events Calendar – Amelia v2.4.6
2.4.7 2.4.6 2.4.5 2.4.4 2.4.3 2.4.2 2.4.1 2.4 trunk 1.2.1 1.2.10 1.2.11 1.2.12 1.2.13 1.2.14 1.2.15 1.2.16 1.2.17 1.2.18 1.2.19 1.2.2 1.2.20 1.2.21 1.2.22 1.2.23 1.2.24 1.2.25 1.2.26 1.2.27 1.2.28 1.2.29 1.2.3 1.2.30 1.2.31 1.2.32 1.2.33 1.2.34 1.2.35 1.2.36 1.2.37 1.2.38 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 2.0 2.0.1 2.0.2 2.1 2.1.1 2.1.2 2.1.3 2.2 2.2.1 2.3
ameliabooking / src / Infrastructure / WP / UserService / CreateWPUser.php
ameliabooking / src / Infrastructure / WP / UserService Last commit date
CreateWPUser.php 4 weeks ago UserAvatar.php 7 years ago UserService.php 1 month ago
CreateWPUser.php
109 lines
1 <?php
2
3 namespace AmeliaBooking\Infrastructure\WP\UserService;
4
5 use WP_Error;
6
7 /**
8 * Class CreateWPUser
9 *
10 * @package AmeliaBooking\Infrastructure\WP\UserService
11 */
12 class CreateWPUser
13 {
14 /**
15 * @param string $email
16 * @param string $firstName
17 * @param string $lastName
18 * @param string|null $role
19 * @param bool $sendNewUserNotification
20 *
21 * @return mixed
22 */
23 public function create($email, $firstName, $lastName, $role = null, $sendNewUserNotification = true)
24 {
25 if (username_exists($email)) {
26 $user = get_user_by('login', $email);
27 if ($user) {
28 $user->add_role($role);
29 return $user->ID;
30 }
31 return null;
32 } elseif (email_exists($email)) {
33 $user = get_user_by('email', $email);
34 if ($user) {
35 $user->add_role($role);
36 return $user->ID;
37 }
38 return null;
39 }
40
41 $userId = wp_create_user($email, wp_generate_password(), $email);
42
43 wp_update_user(
44 [
45 'ID' => $userId,
46 'first_name' => $firstName,
47 'last_name' => $lastName,
48 ]
49 );
50
51 if ($userId instanceof WP_Error) {
52 return null;
53 }
54
55 $this->setRole($role, $userId);
56
57 if ($sendNewUserNotification) {
58 // Wrapped in try/catch because wp_new_user_notification() calls wp_mail() which uses
59 // WordPress's own PHPMailer with the mail() transport. On servers where mail() is disabled,
60 // this throws a fatal Error that would otherwise abort the entire booking process.
61 try {
62 wp_new_user_notification($userId, null, 'user');
63 } catch (\Throwable $e) {
64 }
65 }
66
67 return (int)$userId;
68 }
69
70 /**
71 * @param int $id
72 * @param string|null $role
73 *
74 * @return mixed
75 */
76 public function update($id, $role = null)
77 {
78 $this->addRole($role, $id);
79 }
80
81 /**
82 * @param string $role
83 * @param int $userId
84 */
85 private function setRole($role, $userId)
86 {
87 if ($role) {
88 $user = new \WP_User($userId);
89 if (get_role($role)) {
90 $user->set_role($role);
91 }
92 }
93 }
94
95 /**
96 * @param string $role
97 * @param int $userId
98 */
99 private function addRole($role, $userId)
100 {
101 if ($role) {
102 $user = new \WP_User($userId);
103 if (get_role($role)) {
104 $user->add_role($role);
105 }
106 }
107 }
108 }
109