Files
myep-team/src/BusProNet/UserDataHandler.php
T

115 lines
3.3 KiB
PHP

<?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,
array $crmSelections = []
): User {
$user = new User();
$user
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setEmail($profileResponse->getCommunication()->getEmail())
->setBusProPersonId($profileResponse->getPersonId())
->setBusProAddressId($profileResponse->getAddressId())
->setRoles($roles)
;
if (true === $isTeamer) {
$teamer = Teamer::fromApiResponse($profileResponse);
$teamer->setCrmSelections($crmSelections);
$user->setTeamer($teamer);
$this->logger->info('Create teamer', [
'id' => $teamer->getId(),
'name' => $teamer->getFullName(),
]);
}
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->logger->info('Create user', [
'id' => $user->getId(),
'email' => $user->getEmail(),
]);
return $user;
}
public function updateLocalUser(
User $user,
ProfileResponse $profileResponse,
array $roles,
bool $isTeamer = false,
array $crmSelections = []
): void {
$user->setRoles($roles);
if (true === $isTeamer) {
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
$user
->getTeamer()
->setAddress($address)
->setCommunication($communication)
->setCrmSelections($crmSelections)
;
}
$this->logger->info('Update user', [
'id' => $user->getId(),
'email' => $user->getEmail(),
]);
$this->entityManager->flush();
}
}