<?php
namespace App\Manager\Admin;
use App\Entity\Admin\Produit;
use App\Entity\Admin\Proprietaire;
use App\Entity\Admin\User;
use App\Entity\Admin\UserProduit;
use App\Repository\Admin\UserProduitRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\HttpFoundation\Request;
class UserProduitManager
{
public function __construct(private readonly EntityManagerInterface $entityManager) {}
public function getRepository(): UserProduitRepository
{
return $this->entityManager->getRepository(UserProduit::class);
}
private function save(UserProduit $userProduit): UserProduit
{
$this->entityManager->persist($userProduit);
$this->entityManager->flush();
return $userProduit;
}
public function insert(User $user, Produit $profil, bool $isActive, ?bool $hasDbAuth, ?Proprietaire $defaultProprietaire): UserProduit
{
$userProduit = new UserProduit();
$userProduit
->setUser($user)
->setProduit($profil)
->setIsActive($isActive)
->setDefaultProprietaire($defaultProprietaire)
->setHasDbAuth($hasDbAuth ? true : false);
return $this->save($userProduit);
}
public function delete(UserProduit $userProduit): void
{
$this->entityManager->remove($userProduit);
$this->entityManager->flush();
}
public function update(UserProduit $userProduit): UserProduit
{
return $this->save($userProduit);
}
public function checkAndInsert(User $user, Produit $produit, bool $isActive = false, ?bool $hasDbAuth = false, bool $insert = true, ?int $defaultProprietaire): ?UserProduit
{
$userProduit = $this->getRepository()->findOneBy(['user' => $user, 'produit' => $produit]);
if (!empty($defaultProprietaire)) {
$defaultProprietaire = $this->entityManager->getRepository(Proprietaire::class)->find($defaultProprietaire);
}
if ($userProduit) {
if ($insert) {
if (!is_null($hasDbAuth)) $userProduit->setHasDbAuth($hasDbAuth);
$userProduit->setDefaultProprietaire($defaultProprietaire);
$userProduit->setIsActive($isActive);
$userProduit = $this->update($userProduit);
}
} else {
$userProduit = $this->insert($user, $produit, $isActive, $hasDbAuth, $defaultProprietaire);
}
return $userProduit;
}
public function processRequest(User $user, Produit $produit, Request $request, bool $okForm): ?UserProduit
{
// Réglages
$hasDbAuth = $request->get('user_reglages_hasDbAuth_' . $produit->getId());
$hasDbAuth = ((@$hasDbAuth == 'on' || @$hasDbAuth == '1') ? 1 : 0);
$defaultProprietaire = $request->get('user_reglages_defaultProprietaire_' . $produit->getId());
$isActiveProduit = $request->get('user_produit_' . $produit->getId());
$isActiveProduit = ((@$isActiveProduit == 'on' || @$isActiveProduit == '1') ? 1 : 0);
return $this->checkAndInsert($user, $produit, $isActiveProduit, $hasDbAuth, $okForm, $defaultProprietaire);
}
}