<?php
namespace App\Manager;
use App\Entity\Authorization;
use App\Entity\AuthorizationGroup;
use App\Entity\Contact;
use App\Entity\Group;
use App\Entity\GroupRealEstate;
use App\Entity\Instance;
use App\Entity\RealEstate;
use App\Entity\Taxonomy\Category;
use App\Entity\Taxonomy\CategoryRealEstate;
use App\Entity\Taxonomy\CategoryType;
use App\Entity\User;
use App\Entity\UserGroup;
use App\Service\File\FileService;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\Boolean;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class EchoParkRestManager
{
public function __construct(
private HttpClientInterface $client,
private EntityManagerInterface $entityManager,
private FileService $fileService,
private LoggerInterface $logger
) {
}
public function getToken(Instance $instance): ?string
{
$cache = new FilesystemAdapter();
$instanceCache = $cache->getItem('instance_token_'.$instance->getId());
if (!$instanceCache->isHit()) {
$response = $this->client->request(
method: 'POST',
url: $instance->getUrl().'api/login_check',
options: array_merge(
['verify_peer' => false, 'verify_host' => false],
json_decode($instance->getOptions(), true)
)
);
$response = $response->toArray();
$return = $response['token'];
$instanceCache->expiresAfter(\DateInterval::createFromDateString('20 minutes'));
$cache->save($instanceCache->set($return));
} else {
$return = $instanceCache->get();
}
return $return;
}
public function getUserDetails(User $user): array
{
$cache = new FilesystemAdapter();
$instanceCache = $cache->getItem('instance_user_'.$user->getId());
if (!$user->getEchoparkName()) {
return [];
}
if (!$instanceCache->isHit()) {
$token = $this->getToken($user->getInstance());
$instance = $user->getInstance();
$username = $user->getEchoparkName();
$response = $this->client->request(
method: 'POST',
url: $instance->getUrl()."api/rest/v1.2/$username/switchUser",
options: $this->getOptions($token, [])
);
$response = $response->toArray();
$token = $response['token'];
$response = $this->client->request(
method: 'GET',
url: $instance->getUrl().'api/rest/v1.2/users/me',
options: $this->getOptions($token, [])
);
$return = [
'token' => $token,
'user' => $response->toArray(),
];
$instanceCache->expiresAfter(\DateInterval::createFromDateString('20 minutes'));
$cache->save($instanceCache->set($return));
} else {
$return = $instanceCache->get();
}
return $return;
}
public function getUserDetailsForPartUser(User $user): array
{
return $this->getUserDetails($user);
}
public function getRequestList(User $user, bool $withoutCache): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$cache = new FilesystemAdapter();
$instanceCache = $cache->getItem('instance_request_list_'.$communityId.'_'.$user->getId());
if (!$instanceCache->isHit() || $withoutCache) {
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl() . "api/rest/v1.2/$communityId/requests",
options: $this->getOptions($userData['token'], [])
);
$return = $response->toArray();
$instanceCache->expiresAfter(\DateInterval::createFromDateString('1 hour'));
$cache->save($instanceCache->set($return));
} else {
$return = $instanceCache->get();
}
return $return;
}
public function getRequestDetail(User $user, int $id): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$id",
options: $this->getOptions($userData['token'], [
'body' => [
'withSteps'=>1,
'withRecipients'=>1,
'withForms'=>1,
'withPictures'=>1,
'withMessages'=>1,
]
])
);
return $response->toArray();
}
public function getRequestConsigne(User $user, int $id): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/request_consigne/notification/$id",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function getRequestConsigneDetail(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$requestTypeId = $data['requestTypeId'];
$domaineTreeId = $data['domaineTreeId'];
$realEstateId = $data['realEstateId'];
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/request_consigne/notification/$communityId/$requestTypeId/$domaineTreeId/$realEstateId",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function getRequestPicture(User $user, int $id): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getPicture/$id",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function getTenantList(User $user): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/tenants",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function getRequestsForms(User $user): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getRequestsForms",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function setRequest(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl() . "api/rest/v1.2/$communityId/setRequest",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
public function setDebrief(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/debriefing",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
public function setRead(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/set/read",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
public function setStep(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
$requestId = $data['requestId'];
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/setStep/$requestId",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
public function setRequestMessage(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
$requestId = $data['requestId'];
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$requestId/set/message",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray(false);
}
public function setRequestForm(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
$requestId = $data['requestId'];
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$requestId/set/form",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
public function setDomain(User $user, array $data): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
$requestId = $data['requestId'];
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$requestId/setDomain",
options: $this->getOptions($userData['token'], ['body' => $data])
);
return $response->toArray();
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
*/
public function setPicture(User $user, int $requestId, UploadedFile $file): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$file = $this->fileService->upload($file, 'echopark_uploads_directory' , true);
$this->logger->info($file);
$data = [
'file' => DataPart::fromPath($file),
];
$formData = new FormDataPart($data);
$headers = $formData->getPreparedHeaders()->toArray();
$response = $this->client->request(
method: 'POST',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/setPicture/$requestId",
options: [
'verify_peer' => false,
'verify_host' => false,
'auth_bearer' => $userData['token'],
'headers' => $headers,
'body'=>$formData->bodyToString()
]
);
return $response->toArray();
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
*/
public function getFormFile(User $user, int $fieldDataId): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getFormFile/$fieldDataId",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
*/
public function getDocx(User $user, int $requestId, int $field): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getDocx/$requestId/$field",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
*/
public function getMessageFile(User $user, int $messageFileId): array
{
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getMessageFile/$messageFileId",
options: $this->getOptions($userData['token'], [])
);
return $response->toArray();
}
public function getRequestsMap(User $user): array
{
$cache = new FilesystemAdapter();
$userData = $this->getUserDetails($user);
$communityId = $this->getCommunityId($user, $userData);
$instanceCache = $cache->getItem('instance_requestmap_user_'.$user->getId() . '_' . $communityId);
if (!$instanceCache->isHit()) {
if (!$user->getEchoparkName() || !$communityId) {
return [];
}
$response = $this->client->request(
method: 'GET',
url: $user->getInstance()->getUrl()."api/rest/v1.2/requestsmap/$communityId",
options: $this->getOptions($userData['token'], [])
);
$return = $response->toArray();
$instanceCache->expiresAfter(\DateInterval::createFromDateString('6 days'));
$cache->save($instanceCache->set($return));
} else {
$return = $instanceCache->get();
}
return $return;
}
private function getCommunityId(User $user, array $userData): ?int
{
$communityId = $user->getEchoparkMainCommunityId();
if (!$user->getEchoparkMainCommunityId()) {
$communityId = $userData['user']['communitiesIds'][0]['id'];
$user->setEchoparkMainCommunityId($communityId);
$this->entityManager->flush();
}
return $communityId;
}
private function getOptions(string $token, array $data): array
{
return array_merge(
$data,
[
'verify_peer' => false,
'verify_host' => false,
'auth_bearer' => $token,
],
);
}
public function getRealEstates(string $instanceName, int $communityId): bool
{
$instance = $this->entityManager->getRepository(Instance::class)->findOneBy(['name' => $instanceName]);
if(!is_object($instance) && is_null($instance->getCompany())) {
return false;
}
$companyId = $instance->getCompany()->getId();
$token = $this->getToken($instance);
$response = $this->client->request(
method: 'GET',
url: $instance->getUrl()."api/rest/v1.2/$communityId/getRealEstateArbo",
options: $this->getOptions($token, [])
);
$categoryType = $this->entityManager->getRepository(CategoryType::class)->findOneBy(['main' => true, 'company' => $companyId, 'enabled' => 1, 'deleted' => 0]);
$categoriesByExternalId = $this->entityManager->getRepository(Category::class)->getAllCategoriesForCompany($companyId, $communityId);
$realEstatesByExternalId = $this->entityManager->getRepository(RealEstate::class)->getAllRealEstatesForCompany($instance->getCompany(), $communityId);
$realEstateCategories = $this->entityManager->getRepository(CategoryRealEstate::class)->getAllForCompany($companyId, $communityId);
foreach ($categoriesByExternalId as $category) {
$category->setEnabled(0);
$category->setDeleted(1);
$this->entityManager->persist($category);
}
foreach ($realEstatesByExternalId as $realEstate) {
$realEstate->setEnabled(0);
$realEstate->setDeleted(1);
$this->entityManager->persist($realEstate);
$mainContact = $realEstate->getMainContact();
if(is_object($mainContact)) {
$mainContact->setEnabled(0);
$mainContact->setDeleted(1);
$this->entityManager->persist($mainContact);
}
}
foreach ($realEstateCategories as $rel) {
$rel->setEnabled(0);
$rel->setDeleted(1);
$this->entityManager->persist($rel);
}
$this->updateRealEstateArbo($response->toArray(), $parent = null, $categoryType, $categoriesByExternalId, $realEstatesByExternalId, $realEstateCategories, $communityId);
$this->entityManager->flush();
$this->entityManager->clear();
return true;
}
private function updateRealEstateArbo($realEstates, $parent = null, $categoryType, array &$categoriesByExternalId, array &$realEstatesByExternalId, array &$realEstateCategories, $communityId):void
{
$i = 0;
foreach ($realEstates as $item) {
if ($i == 0) {
var_dump($item['attr']['name']);
$i++;
}
$id = $item['attr']['id'];
if(!empty($item['children'])) {
/* Catégorie *//* rajoute la company dans la recherche ! et réactiver. Idem pour toutes les maj de cette fonction */
if(!isset($categoriesByExternalId[$id])) {
$category = new Category();
$category->setExternalId($id);
$category->setExternalRef($communityId);
$categoriesByExternalId[$id] = $category;
} else {
$category = $categoriesByExternalId[$id];
}
$category->setCategoryType($categoryType);
$category->setCompany($categoryType->getCompany());
$category->setName($item['attr']['name']);
$category->setParent($parent);
$category->setEnabled(1);
$category->setDeleted(0);
$this->entityManager->persist($category);
$this->updateRealEstateArbo($item['children'], $category, $categoryType, $categoriesByExternalId, $realEstatesByExternalId, $realEstateCategories, $communityId);
} else {
/* Patrimoine */
if (!isset($realEstatesByExternalId[$id])) {
$realEstate = new RealEstate();
$realEstate->setExternalId($item['attr']['id']);
$realEstate->setExternalRef($communityId);
$mainContact = new Contact();
$realEstatesByExternalId[$id] = $realEstate;
} else {
$realEstate = $realEstatesByExternalId[$id];
$mainContact = $realEstate->getMainContact();
if(!is_object($mainContact)) {
$mainContact = new Contact();
}
}
$mainContact->setTitle('Adresse ' . $item['attr']['name']);
$mainContact->setAddress($item['attr']['address'] ?? '');
$mainContact->setAdditionalAddress(null);
$mainContact->setPostalCode($item['attr']['cp'] ?? '');
$mainContact->setCity($item['attr']['city'] ?? '');
$mainContact->setCountry('France');
$mainContact->setState('France');
$mainContact->setEnabled(1);
$mainContact->setDeleted(0);
$this->entityManager->persist($mainContact);
$realEstate->setMainContact($mainContact);
$realEstate->setCompany($categoryType->getCompany());
$realEstate->setCode($item['attr']['name']);
$realEstate->setName($item['attr']['name']);
$realEstate->setEnabled(1);
$realEstate->setDeleted(0);
$this->entityManager->persist($realEstate);
$key = $realEstate->getId() . '-' . $parent->getId();
if (!isset($realEstateCategories[$key])) {
$realEstateCategory = new CategoryRealEstate();
$realEstateCategory->setCategory($parent);
$realEstateCategory->setRealEstate($realEstate);
} else {
$realEstateCategory = $realEstateCategories[$key];
}
$realEstateCategory->setEnabled(1);
$realEstateCategory->setDeleted(0);
$this->entityManager->persist($realEstateCategory);
}
}
}
public function getVisitUsers(string $instanceName): bool
{
$instance = $this->entityManager->getRepository(Instance::class)->findOneBy(['name' => $instanceName]);
if(!is_object($instance) && is_null($instance->getCompany())) {
return false;
}
$companyId = $instance->getCompany()->getId();
$token = $this->getToken($instance);
$response = $this->client->request(
method: 'GET',
url: $instance->getUrl()."api/rest/v1.2/echoqualite-users",
options: $this->getOptions($token, [])
);
$referents = $this->client->request(
method: 'GET',
url: $instance->getUrl()."api/rest/v1.2/echoqualite-referents",
options: $this->getOptions($token, [])
);
$realEstatesByExternalId = $this->entityManager->getRepository(RealEstate::class)->getAllRealEstatesForCompany($instance->getCompany());
$usersByExternalId = $this->entityManager->getRepository(User::class)->getAllByExternalId($companyId);
$rolesByCode = $this->entityManager->getRepository(Authorization::class)->getAuthorizationsByCode();
$groupsByUsers = $this->entityManager->getRepository(Group::class)->getAllVisitGroupsByUser($companyId);
$this->updateUserAccess($response->toArray(), $realEstatesByExternalId, $usersByExternalId, $rolesByCode, $groupsByUsers, $referents->toArray(), $instance);
$this->entityManager->flush();
$this->entityManager->clear();
return true;
}
private function updateUserAccess($access, $realEstatesByExternalId, $usersByExternalId, $rolesByCode, $groupsByUsers, $referents, $instance):void
{
var_dump('updateUserAccess');
$usersUpdates = [];
$usersEideticUpdates = [];
$token = $this->getToken($instance);
$company = $instance->getCompany();
$reorganizedTable = [];
foreach ($access as $item) {
$externalUserId = $item['utilisateur_id'];
if(!isset($reorganizedTable[$externalUserId])) {
$reorganizedTable[$externalUserId] = [];
}
if(!isset($reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']])) {
$reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']] = [];
}
array_push($reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']], $item);
/* On récupère les info du user sur EP seulement si c'est la 1ère fois qu'on a ce user dans la boucle */
if(!in_array($externalUserId, $usersUpdates)) {
$theUserData = $this->client->request(
method: 'POST',
url: $instance->getUrl() . "api/rest/v1.2/get-user",
options: $this->getOptions($token, ['body' => ['id' => $externalUserId]]),
);
$theUser = $theUserData->toArray()[0];
if(!empty($theUser['email'])) {
if (!isset($usersByExternalId[$externalUserId])) {
$user = new User();
$user->setExternalId($externalUserId);
$user->setPassword('tmp');
} else {
$user = $usersByExternalId[$externalUserId];
}
$user->setEmail($theUser['email']);
$user->setFirstName($theUser['firstname']);
$user->setLastName($theUser['lastname']);
$user->setEchoparkName($theUser['username']);
if (!empty($theUser['gsm'])) {
$user->setGsm($theUser['gsm']);
}
if (!empty($theUser['phone'])) {
$user->setPhone($theUser['phone']);
}
$user->setCompany($instance->getCompany());
$this->entityManager->persist($user);
$this->entityManager->flush();
$usersByExternalId[$externalUserId] = $user;
}
array_push($usersEideticUpdates, $user->getId());
array_push($usersUpdates, $externalUserId);
}
}
/* Dans EP le user peut avoir plusieurs rôles echoqualité sur un patrimoine, on ne garde que celui qui est le plus élévé. */
/* Pour chaque user */
foreach ($reorganizedTable as $userTable) {
$username = null;
$pat = null;
/* Pour chaque patrimoine */
foreach ($userTable as $realEstateTable) {
$bestRole = null;
$userExternalId = null;
$realEstateExternalId = null;
/* Pour chaque rôle (patrimoine attribué à l'utilisateur), on boucle sur la liste de ses droits pour trouver le plus haut level */
foreach ($realEstateTable as $roleTable) {
$userExternalId = $roleTable['utilisateur_id'];
$realEstateExternalId = $roleTable['patrimoine_enfant_id'];
if(!isset($realEstatesByExternalId[$realEstateExternalId])) {
continue;
}
if(isset($usersByExternalId[$userExternalId])) {
$user = $usersByExternalId[$userExternalId];
//$pat = $roleTable['patrimoine_enfant_nom'];
if ($roleTable['role'] == 'MANAGER') {
$bestRole = ['ROLE_VISIT_MANAGER'];
} else if ($roleTable['role'] == 'GESTIONNAIRE REFERENT' && $bestRole != 'MANAGER') {
$bestRole = ['ROLE_VISIT_MANAGER', 'ROLE_PLANIFICATION_VISIT'];
} else if ($bestRole == null) {
$bestRole = ['ROLE_VISIT_TECHNICIAN'];
}
}
}
/* Pour chaque plus haut level d'authorazation qu'on a trouvé pour le user sur le patrimoine */
if($bestRole != null) {
foreach ($bestRole as $role) {
$authorization = $rolesByCode[$role];
$group = null;
/* On récupère le group s'il existe déjà */
if(isset($groupsByUsers[$user->getId()]) && isset($groupsByUsers[$user->getId()][$authorization->getCode()])) {
$group = $groupsByUsers[$user->getId()][$authorization->getCode()];
}
/* On créé le groupe s'il n'existe pas */
if (!is_object($group)) {
$group = new Group();
$group->setName($user->getEmail() . ' - ' . $role);
$group->setCompany($company);
$this->entityManager->persist($group);
/* On ajour le user au groupe */
$userGroup = new UserGroup();
$userGroup->setUser($user);
$userGroup->setGroup($group);
$this->entityManager->persist($userGroup);
/* On lui donne l'authorisation sur laquelle on boucle */
$groupAuthorization = new AuthorizationGroup();
$groupAuthorization->setAuthorization($authorization);
$groupAuthorization->setGroup($group);
$this->entityManager->persist($groupAuthorization);
/* On ajoute le group au tab */
$groupsByUsers[$user->getId()][$authorization->getCode()] = $group;
}
/* On récupère la relation groupe - realestate pour chaque patrimoine */
$groupRealEstates = $group->getRealEstates();
//var_dump(count($groupRealEstates));
$findRealEstateGroup = null;
/* Pour chaque patrimoine attribué au groupe */
foreach ($groupRealEstates as $groupRealEstate) {
/* On désactive */
$groupRealEstate->setEnabled(0);
$groupRealEstate->setDeleted(1);
/* Si la relation existe toujours, on réactive */
if($groupRealEstate->getRealEstate()->getExternalId() == $realEstateExternalId) {
$groupRealEstate->setEnabled(0);
$groupRealEstate->setDeleted(1);
/* La relation existe déjà */
$findRealEstateGroup = $groupRealEstate;
}
$this->entityManager->persist($groupRealEstate);
}
/* Si la relation n'existe pas on la créé */
if($findRealEstateGroup == null) {
$groupRealEstate = new GroupRealEstate();
$groupRealEstate->setGroup($group);
$groupRealEstate->setRealEstate($realEstatesByExternalId[$realEstateExternalId]);
$this->entityManager->persist($groupRealEstate);
}
}
}
/* Set realestate referent if empty */
if(isset($realEstatesByExternalId[$realEstateExternalId]) && isset($referents[$realEstateExternalId])) {
$realEstate = $realEstatesByExternalId[$realEstateExternalId];
if(is_null($realEstate->getReferent()) && isset($usersByExternalId[$referents[$realEstateExternalId]])) {
$realEstate->setReferent($usersByExternalId[$referents[$realEstateExternalId]]);
$this->entityManager->persist($realEstate);
}
}
}
}
}
private int $batchSize = 500;
private int $i = 0;
private function persistAndMaybeFlush(object $entity): void
{
$this->entityManager->persist($entity);
if ((++$this->i % $this->batchSize) === 0) {
$this->entityManager->flush();
}
}
}