PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / trunk
Booking for Appointments and Events Calendar – Amelia vtrunk
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 3 months ago UserAvatar.php 7 years ago UserService.php 2 weeks ago
CreateWPUser.php
106 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 *
20 * @return mixed
21 */
22 public function create($email, $firstName, $lastName, $role = null)
23 {
24 if (username_exists($email)) {
25 $user = get_user_by('login', $email);
26 if ($user) {
27 $user->add_role($role);
28 return $user->ID;
29 }
30 return null;
31 } elseif (email_exists($email)) {
32 $user = get_user_by('email', $email);
33 if ($user) {
34 $user->add_role($role);
35 return $user->ID;
36 }
37 return null;
38 }
39
40 $userId = wp_create_user($email, wp_generate_password(), $email);
41
42 wp_update_user(
43 [
44 'ID' => $userId,
45 'first_name' => $firstName,
46 'last_name' => $lastName,
47 ]
48 );
49
50 if ($userId instanceof WP_Error) {
51 return null;
52 }
53
54 $this->setRole($role, $userId);
55
56 // Wrapped in try/catch because wp_new_user_notification() calls wp_mail() which uses
57 // WordPress's own PHPMailer with the mail() transport. On servers where mail() is disabled,
58 // this throws a fatal Error that would otherwise abort the entire booking process.
59 try {
60 wp_new_user_notification($userId, null, 'user');
61 } catch (\Throwable $e) {
62 }
63
64 return (int)$userId;
65 }
66
67 /**
68 * @param int $id
69 * @param string|null $role
70 *
71 * @return mixed
72 */
73 public function update($id, $role = null)
74 {
75 $this->addRole($role, $id);
76 }
77
78 /**
79 * @param string $role
80 * @param int $userId
81 */
82 private function setRole($role, $userId)
83 {
84 if ($role) {
85 $user = new \WP_User($userId);
86 if (get_role($role)) {
87 $user->set_role($role);
88 }
89 }
90 }
91
92 /**
93 * @param string $role
94 * @param int $userId
95 */
96 private function addRole($role, $userId)
97 {
98 if ($role) {
99 $user = new \WP_User($userId);
100 if (get_role($role)) {
101 $user->add_role($role);
102 }
103 }
104 }
105 }
106