| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\DonationForms\Actions; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use Give\Donors\Models\Donor; |
| 7 |
|
| 8 |
/** |
| 9 |
* @since 3.2.0 |
| 10 |
*/ |
| 11 |
class GetOrCreateDonor |
| 12 |
{ |
| 13 |
public $donorCreated = false; |
| 14 |
|
| 15 |
/** |
| 16 |
* @since 3.9.0 Add support to "phone" property |
| 17 |
* @since 3.2.0 |
| 18 |
* |
| 19 |
* @throws Exception |
| 20 |
*/ |
| 21 |
public function __invoke( |
| 22 |
?int $userId, |
| 23 |
string $donorEmail, |
| 24 |
string $firstName, |
| 25 |
string $lastName, |
| 26 |
?string $honorific, |
| 27 |
?string $donorPhone |
| 28 |
): Donor { |
| 29 |
// first check if donor exists as a user |
| 30 |
$donor = $userId ? Donor::whereUserId($userId) : null; |
| 31 |
|
| 32 |
// if they exist as a donor & user then make sure they don't already own this email before adding to their additional emails list.. |
| 33 |
if ($donor && !$donor->hasEmail($donorEmail) && !Donor::whereEmail($donorEmail)) { |
| 34 |
$donor->additionalEmails = array_merge($donor->additionalEmails ?? [], [$donorEmail]); |
| 35 |
$donor->save(); |
| 36 |
} |
| 37 |
|
| 38 |
// if donor is not a user than check for any donor matching this email |
| 39 |
if (!$donor) { |
| 40 |
$donor = Donor::whereEmail($donorEmail); |
| 41 |
} |
| 42 |
|
| 43 |
// if they exist as a donor & user but don't have a phone number then add it to their profile. |
| 44 |
if ($donor && empty($donor->phone)) { |
| 45 |
$donor->phone = $donorPhone; |
| 46 |
$donor->save(); |
| 47 |
} |
| 48 |
|
| 49 |
// if no donor exists then create a new one using their personal information from the form. |
| 50 |
if (!$donor) { |
| 51 |
$donor = Donor::create([ |
| 52 |
'name' => trim("$firstName $lastName"), |
| 53 |
'firstName' => $firstName, |
| 54 |
'lastName' => $lastName, |
| 55 |
'email' => $donorEmail, |
| 56 |
'phone' => $donorPhone, |
| 57 |
'userId' => $userId ?: null, |
| 58 |
'prefix' => $honorific, |
| 59 |
]); |
| 60 |
|
| 61 |
$this->donorCreated = true; |
| 62 |
} |
| 63 |
|
| 64 |
return $donor; |
| 65 |
} |
| 66 |
} |
| 67 |
|