Feat: Implement entities for user and teamer, finalize login process

This commit is contained in:
Björn Fromme
2023-09-12 16:35:06 +02:00
parent 3739decab8
commit 35ca61d21b
27 changed files with 1008 additions and 442 deletions
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace App\BusProNet;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\ProfileResponse;
use App\Entity\Embeddable\Address;
use App\Entity\Embeddable\Communication;
use App\Entity\Teamer;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
class UserDataHandler
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger
) {
}
public function collectRoles(CrmAttributesResponse $crmAttributes): array
{
// Collect user's roles from CRM attributes
$roles = [];
if ($crmAttributes->isAdmin()) {
$roles[] = 'ROLE_ADMIN';
}
if ($crmAttributes->isManager()) {
$roles[] = 'ROLE_MANAGER';
}
if ($crmAttributes->isTeamer()) {
$roles[] = 'ROLE_TEAMER';
}
return $roles;
}
public function findLocalUser(ProfileResponse $profileResponse): ?User
{
// Check if user is already present in local database
$repository = $this->entityManager->getRepository(User::class);
return $repository->findOneBy([
'busProAddressId' => $profileResponse->getAddressId(),
'busProPersonId' => $profileResponse->getPersonId(),
]);
}
public function createLocalUser(ProfileResponse $profileResponse, array $roles, bool $isTeamer = false): User
{
$user = new User();
$user
->setEmail($profileResponse->getCommunication()->getEmail())
->setBusProPersonId($profileResponse->getPersonId())
->setBusProAddressId($profileResponse->getAddressId())
->setRoles($roles)
;
if (true === $isTeamer) {
$teamer = Teamer::fromApiResponse($profileResponse);
$user->setTeamer($teamer);
$this->logger->info('Create teamer', [
'uuid' => $teamer->getUuid(),
]);
}
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->logger->info('Create user', [
'uuid' => $user->getUuid(),
]);
return $user;
}
public function updateLocalUser(
User $user,
ProfileResponse $profileResponse,
array $roles,
bool $isTeamer = false
): void {
$user->setRoles($roles);
if (true === $isTeamer) {
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
$user
->getTeamer()
->setAddress($address)
->setCommunication($communication)
;
}
$this->entityManager->flush();
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Entity\Embeddable;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Embeddable]
class BankAccount
{
#[ORM\Column(nullable: true)]
private ?string $iban = null;
#[ORM\Column(nullable: true)]
private ?string $bic = null;
#[ORM\Column(nullable: true)]
private ?string $bank = null;
#[ORM\Column(nullable: true)]
private ?string $holder = null;
public function getIban(bool $obfuscated = false): ?string
{
if (false === $obfuscated) {
return $this->iban;
}
if (null === $iban = $this->getIban()) {
return '';
}
return sprintf('%s*****%s', substr($iban, 0, 6), substr($iban, -4));
}
public function setIban(?string $iban): static
{
$this->iban = $iban;
return $this;
}
public function getBic(): ?string
{
return $this->bic;
}
public function setBic(?string $bic): static
{
$this->bic = $bic;
return $this;
}
public function getBank(): ?string
{
return $this->bank;
}
public function setBank(?string $bank): static
{
$this->bank = $bank;
return $this;
}
public function getHolder(): ?string
{
return $this->holder;
}
public function setHolder(?string $holder): static
{
$this->holder = $holder;
return $this;
}
}
-149
View File
@@ -1,149 +0,0 @@
<?php
namespace App\Entity\Embeddable;
use App\BusProNet\Model\ProfileResponse;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Embeddable]
class Profile
{
#[ORM\Column]
private ?int $busProAddressId = null;
#[ORM\Column]
private ?int $busProPersonId = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
#[ORM\Column(length: 255)]
private ?string $salutation = null;
#[ORM\Column(length: 255)]
private ?string $firstName = null;
#[ORM\Column(length: 255)]
private ?string $lastName = null;
#[ORM\Column(length: 1, nullable: true)]
private ?string $gender = null;
#[ORM\Column(type: 'date_immutable', nullable: true)]
private ?\DateTimeImmutable $dateOfBirth = null;
public static function fromApiResponse(ProfileResponse $profileResponse): static
{
$instance = new static();
$instance
->setBusProAddressId($profileResponse->getAddressId())
->setBusProPersonId($profileResponse->getPersonId())
->setTitle($profileResponse->getTitle())
->setSalutation($profileResponse->getSalutation())
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setGender($profileResponse->getGender())
->setDateOfBirth($profileResponse->getDateOfBirth())
;
return $instance;
}
public function getBusProAddressId(): ?int
{
return $this->busProAddressId;
}
public function setBusProAddressId(int $busProAddressId): static
{
$this->busProAddressId = $busProAddressId;
return $this;
}
public function getBusProPersonId(): ?int
{
return $this->busProPersonId;
}
public function setBusProPersonId(int $busProPersonId): static
{
$this->busProPersonId = $busProPersonId;
return $this;
}
public function getSalutation(): ?string
{
return $this->salutation;
}
public function setSalutation(?string $salutation): static
{
$this->salutation = $salutation;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): static
{
$this->title = $title;
return $this;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): static
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): static
{
$this->lastName = $lastName;
return $this;
}
public function getGender(): ?string
{
return $this->gender;
}
public function setGender(?string $gender): static
{
$this->gender = $gender;
return $this;
}
public function getDateOfBirth(): ?\DateTimeImmutable
{
return $this->dateOfBirth;
}
public function setDateOfBirth(?\DateTimeImmutable $dateOfBirth): static
{
$this->dateOfBirth = $dateOfBirth;
return $this;
}
}
+284
View File
@@ -0,0 +1,284 @@
<?php
namespace App\Entity;
use App\BusProNet\Model\ProfileResponse;
use App\Entity\Embeddable\Address;
use App\Entity\Embeddable\BankAccount;
use App\Entity\Embeddable\Communication;
use App\Entity\Traits\TimestampableEntity;
use App\Repository\TeamerRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: TeamerRepository::class)]
class Teamer implements TimestampableEntityInterface
{
use TimestampableEntity;
public const STATUS_NEW = 'new';
public const STATUS_EXISTING = 'existing';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(length: 255)]
private ?string $firstName = null;
#[ORM\Column(length: 255)]
private ?string $lastName = null;
#[ORM\Column(length: 1)]
private ?string $gender = null;
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
private ?\DateTimeImmutable $dateOfBirth = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $academicTitle = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $salutation = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $nationality = null;
#[ORM\Embedded(class: Address::class)]
#[Assert\Valid()]
private ?Address $address = null;
#[ORM\Embedded(class: Communication::class)]
#[Assert\Valid()]
private ?Communication $communication = null;
#[ORM\Embedded(class: BankAccount::class)]
#[Assert\Valid()]
private ?BankAccount $bankAccount = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $taxId = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $healthInsuranceCompany = null;
#[ORM\Column(length: 32)]
private ?string $status = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $remarks = null;
public function __construct()
{
$this->uuid = Uuid::v4();
$this->status = static::STATUS_NEW;
}
public static function fromApiResponse(ProfileResponse $profileResponse): static
{
$instance = new static();
$instance
->setAcademicTitle($profileResponse->getTitle())
->setSalutation($profileResponse->getSalutation())
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setGender($profileResponse->getGender())
->setDateOfBirth($profileResponse->getDateOfBirth())
;
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
$instance
->setAddress($address)
->setCommunication($communication)
;
return $instance;
}
public function getId(): ?int
{
return $this->id;
}
public function getUuid(): string
{
return $this->uuid;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): static
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): static
{
$this->lastName = $lastName;
return $this;
}
public function getGender(): ?string
{
return $this->gender;
}
public function setGender(string $gender): static
{
$this->gender = $gender;
return $this;
}
public function getDateOfBirth(): ?\DateTimeImmutable
{
return $this->dateOfBirth;
}
public function setDateOfBirth(\DateTimeImmutable $dateOfBirth): static
{
$this->dateOfBirth = $dateOfBirth;
return $this;
}
public function getAcademicTitle(): ?string
{
return $this->academicTitle;
}
public function setAcademicTitle(?string $academicTitle): static
{
$this->academicTitle = $academicTitle;
return $this;
}
public function getSalutation(): ?string
{
return $this->salutation;
}
public function setSalutation(?string $salutation): static
{
$this->salutation = $salutation;
return $this;
}
public function getNationality(): ?string
{
return $this->nationality;
}
public function setNationality(string $nationality): static
{
$this->nationality = $nationality;
return $this;
}
public function getAddress(): ?Address
{
return $this->address;
}
public function setAddress(?Address $address): static
{
$this->address = $address;
return $this;
}
public function getCommunication(): ?Communication
{
return $this->communication;
}
public function setCommunication(?Communication $communication): static
{
$this->communication = $communication;
return $this;
}
public function getBankAccount(): ?BankAccount
{
return $this->bankAccount;
}
public function setBankAccount(?BankAccount $bankAccount): static
{
$this->bankAccount = $bankAccount;
return $this;
}
public function getTaxId(): ?string
{
return $this->taxId;
}
public function setTaxId(?string $taxId): static
{
$this->taxId = $taxId;
return $this;
}
public function getHealthInsuranceCompany(): ?string
{
return $this->healthInsuranceCompany;
}
public function setHealthInsuranceCompany(?string $healthInsuranceCompany): static
{
$this->healthInsuranceCompany = $healthInsuranceCompany;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): static
{
$this->status = $status;
return $this;
}
public function getRemarks(): ?string
{
return $this->remarks;
}
public function setRemarks(?string $remarks): static
{
$this->remarks = $remarks;
return $this;
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Entity;
interface TimestampableEntityInterface
{
public function getCreatedAt();
public function setCreatedAt(\DateTimeImmutable $createdAt);
public function getUpdatedAt();
public function setUpdatedAt(\DateTimeImmutable $updatedAt);
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Entity\Traits;
use Doctrine\ORM\Mapping as ORM;
trait TimestampableEntity
{
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $updatedAt = null;
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeImmutable $updatedAt): static
{
$this->updatedAt = $updatedAt;
return $this;
}
}
+63 -53
View File
@@ -2,48 +2,82 @@
namespace App\Entity;
use App\Entity\Embeddable\Address;
use App\Entity\Embeddable\Communication;
use App\Entity\Embeddable\Profile;
use App\Entity\Traits\TimestampableEntity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Uid\Uuid;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface
class User implements UserInterface, TimestampableEntityInterface
{
use TimestampableEntity;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column]
private ?int $busProAddressId = null;
#[ORM\Column]
private ?int $busProPersonId = null;
#[ORM\Column(length: 255)]
private ?string $email = null;
#[ORM\Embedded(class: Profile::class)]
#[Assert\Valid()]
private ?Profile $profile = null;
#[ORM\Embedded(class: Address::class)]
#[Assert\Valid()]
private ?Address $address = null;
#[ORM\Embedded(class: Communication::class)]
#[Assert\Valid()]
private ?Communication $communication = null;
#[ORM\Column(type: 'json')]
private array $roles = [];
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $lastLoginAt = null;
#[ORM\OneToOne(cascade: ['persist', 'remove'])]
private ?Teamer $teamer = null;
public function __construct()
{
$this->uuid = Uuid::v4();
}
public function getId(): ?int
{
return $this->id;
}
public function getUuid(): string
{
return $this->uuid;
}
public function getBusProAddressId(): ?int
{
return $this->busProAddressId;
}
public function setBusProAddressId(int $busProAddressId): static
{
$this->busProAddressId = $busProAddressId;
return $this;
}
public function getBusProPersonId(): ?int
{
return $this->busProPersonId;
}
public function setBusProPersonId(int $busProPersonId): static
{
$this->busProPersonId = $busProPersonId;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
@@ -56,42 +90,6 @@ class User implements UserInterface
return $this;
}
public function getProfile(): ?Profile
{
return $this->profile;
}
public function setProfile(?Profile $profile): static
{
$this->profile = $profile;
return $this;
}
public function getAddress(): ?Address
{
return $this->address;
}
public function setAddress(?Address $address): static
{
$this->address = $address;
return $this;
}
public function getCommunication(): ?Communication
{
return $this->communication;
}
public function setCommunication(?Communication $communication): static
{
$this->communication = $communication;
return $this;
}
public function getRoles(): array
{
$roles = ['ROLE_USER', ...$this->roles];
@@ -142,4 +140,16 @@ class User implements UserInterface
{
return $this->email;
}
public function getTeamer(): ?Teamer
{
return $this->teamer;
}
public function setTeamer(?Teamer $teamer): static
{
$this->teamer = $teamer;
return $this;
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\EventListener;
use App\Entity\TimestampableEntityInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
class TimestampableEntitySubscriber implements EventSubscriber
{
public function getSubscribedEvents(): array
{
return [
Events::prePersist,
Events::preUpdate,
];
}
public function prePersist(PrePersistEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof TimestampableEntityInterface) {
$now = new \DateTimeImmutable('now');
$entity->setCreatedAt($now);
$entity->setUpdatedAt($now);
}
}
public function preUpdate(PreUpdateEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof TimestampableEntityInterface) {
$now = new \DateTimeImmutable('now');
$entity->setUpdatedAt($now);
}
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Repository;
use App\Entity\Teamer;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Teamer>
*
* @method Teamer|null find($id, $lockMode = null, $lockVersion = null)
* @method Teamer|null findOneBy(array $criteria, array $orderBy = null)
* @method Teamer[] findAll()
* @method Teamer[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class TeamerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Teamer::class);
}
public function save(Teamer $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Teamer $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * @return Teamer[] Returns an array of Teamer objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('t.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Teamer
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+23 -44
View File
@@ -6,9 +6,7 @@ use App\BusProNet\ApiClient;
use App\BusProNet\ApiClientException;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\ProfileResponse;
use App\Entity\Embeddable\Address;
use App\Entity\Embeddable\Communication;
use App\Entity\Embeddable\Profile;
use App\BusProNet\UserDataHandler;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
@@ -33,7 +31,8 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
private readonly UrlGeneratorInterface $urlGenerator,
private readonly EntityManagerInterface $entityManager,
private readonly ApiClient $apiClient,
private readonly LoggerInterface $logger
private readonly LoggerInterface $logger,
private readonly UserDataHandler $userDataHandler
) {
}
@@ -72,6 +71,9 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$user = $token->getUser();
$user->setLastLoginAt(new \DateTimeImmutable());
$this->logger->info('Login', [
'user' => $user->getUserIdentifier(),
]);
$this->entityManager->flush();
@@ -95,56 +97,33 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
}
// Collect user's roles from CRM attributes
$roles = [];
$roles = $this
->userDataHandler
->collectRoles($crmAttributes)
;
if ($crmAttributes->isAdmin()) {
$roles[] = 'ROLE_ADMIN';
}
if ($crmAttributes->isManager()) {
$roles[] = 'ROLE_MANAGER';
}
if ($crmAttributes->isTeamer()) {
$roles[] = 'ROLE_TEAMER';
}
// Get profile data from API response
$profile = Profile::fromApiResponse($profileResponse);
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
// Determine teamer status from CRM attributes
$isTeamer = $crmAttributes->isTeamer();
// Check if user is already present in local database
$repository = $this->entityManager->getRepository(User::class);
$user = $this
->userDataHandler
->findLocalUser($profileResponse)
;
$user = $repository->findOneBy([
'profile.busProAddressId' => $profileResponse->getAddressId(),
'profile.busProPersonId' => $profileResponse->getPersonId(),
]);
// Update existing user's roles and address and return it
// Update existing user's roles and teamer data and return it
if (null !== $user) {
$user
->setProfile($profile)
->setAddress($address)
->setCommunication($communication)
->setRoles($roles)
$this
->userDataHandler
->updateLocalUser($user, $profileResponse, $roles, $isTeamer)
;
return $user;
}
// Create new user entity to persist locally otherwise
$user = new User();
$user
->setEmail($profileResponse->getCommunication()->getEmail())
->setProfile($profile)
->setAddress($address)
->setCommunication($communication)
->setRoles($roles)
return $this
->userDataHandler
->createLocalUser($profileResponse, $roles, $isTeamer)
;
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
}
}