File size: 2,109 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <?php
declare(strict_types=1);
namespace User\Application\CommandHandlers;
use Affiliate\Domain\Exceptions\AffiliateNotFoundException;
use Affiliate\Domain\Repositories\AffiliateRepositoryInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use User\Application\Commands\CreateUserCommand;
use User\Domain\Entities\UserEntity;
use User\Domain\Events\UserCreatedEvent;
use User\Domain\Exceptions\EmailTakenException;
use User\Domain\Repositories\UserRepositoryInterface;
class CreateUserCommandHandler
{
public function __construct(
private UserRepositoryInterface $repo,
private AffiliateRepositoryInterface $affiliateRepo,
private EventDispatcherInterface $dispatcher,
) {}
/**
* @throws EmailTakenException
*/
public function handle(CreateUserCommand $cmd): UserEntity
{
$user = new UserEntity(
email: $cmd->email,
firstName: $cmd->firstName,
lastName: $cmd->lastName
);
if ($cmd->password) {
$user->setPassword($cmd->password);
}
if ($cmd->language) {
$user->setLanguage($cmd->language);
}
if ($cmd->ip) {
$user->setIp($cmd->ip);
}
if ($cmd->countryCode) {
$user->setCountryCode($cmd->countryCode);
}
if ($cmd->cityName) {
$user->setCityName($cmd->cityName);
}
if ($cmd->role) {
$user->setRole($cmd->role);
}
if ($cmd->status) {
$user->setStatus($cmd->status);
}
// Find the affiliate
if ($cmd->refCode) {
try {
$affiliate = $this->affiliateRepo->ofCode($cmd->refCode);
$user->setReferredBy($affiliate->getUser());
} catch (AffiliateNotFoundException $th) {
//throw $th;
}
}
$this->repo->add($user);
// Dispatch the user created event
$event = new UserCreatedEvent($user);
$this->dispatcher->dispatch($event);
return $user;
}
}
|