Select Git revision
UserBuilder.php

Camille Simiand authored
UserBuilder.php 3.42 KiB
<?php
namespace App\Builder;
use App\Entity\User;
use App\Helper\ContractHelper;
use App\Helper\StringHelper;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserBuilder
{
private UserPasswordHasherInterface $password_hasher;
public User $user;
public function __construct(UserPasswordHasherInterface $password_hasher, ?User $user = null)
{
if (!$user instanceof User) {
$this->user = new User();
} else {
$this->user = $user;
}
$this->password_hasher = $password_hasher;
$this->user->setIsVerified(false);
}
public function withEmail(string $email): UserBuilder
{
$this->user->setEmail($email);
return $this;
}
public function withFirstName(string $firstName): UserBuilder
{
$this->user->setFirstName($firstName);
return $this;
}
public function withLastName(string $lastName): UserBuilder
{
$this->user->setLastName($lastName);
return $this;
}
public function withPassword(string $salt, string $plainPassword): UserBuilder
{
ContractHelper::requires(
!StringHelper::isNullOrWhitespace($plainPassword),
'A user should have none empty password'
);
$this->user->plainPassword = $plainPassword;
return $this;
}
/**
* @param array<string> $roles
*/
public function withRoles(array $roles): UserBuilder
{
if (! in_array(['ROLE_USER'], $roles)) {
$roles[] = 'ROLE_USER';
}
$this->user->setRoles($roles);
return $this;
}
public function withIsVerified(bool $is_verified): UserBuilder
{
$this->user->setIsVerified($is_verified);
return $this;
}
public function createUser(): User
{
ContractHelper::requires(
$this->user->getEmail() !== null && filter_var($this->user->getEmail(), FILTER_VALIDATE_EMAIL),
"A user should have a valid email (current:'" . $this->user->getEmail() . "')"
);
ContractHelper::requires(
!StringHelper::isNullOrWhitespace($this->user->getLastName()),
"A user must have a last name (current:'" . $this->user->getLastName() . "')"
);
ContractHelper::requires(
!StringHelper::isNullOrWhitespace($this->user->getFirstName()),
"A user must have a first name (current:'" . $this->user->getFirstName() . "')"
);
ContractHelper::requires(
!StringHelper::isNullOrWhitespace($this->user->plainPassword),
"A user must have a have a none empty or whitespace password"
);
ContractHelper::requires(
!empty($this->user->getRoles()),
"A user must have a have roles"
);
$this->user->setSalt(random_bytes(100));
$this->user->setPassword($this->password_hasher->hashPassword($this->user, $this->user->plainPassword));
$this->user->eraseCredentials();
$this->user->setLocale('en');
return $this->user;
}
public function withAcceptGeneralConditions(bool $value): UserBuilder
{
$this->user->setAcceptGeneralConditions($value);
return $this;
}
public function withNewsLetterSubscription(bool $newsLetterSubscription): UserBuilder
{
$this->user->setSubscribedToNewsLetter($newsLetterSubscription);
return $this;
}
}