Commit d033f5de authored by Baudouin Feildel's avatar Baudouin Feildel
Browse files

Implement UserPermImporter

parent 6be92a5b
Pipeline #643 passed with stage
in 1 minute and 48 seconds
......@@ -10,6 +10,10 @@ use App\Service\Importer\ImportDataType;
use App\Service\Importer\ImportException;
use App\Service\Importer\ImportStrategy;
use App\Service\Importer\UserImporter;
use App\Service\Importer\UserPermImporter;
use Error;
use Exception;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\File;
......@@ -25,11 +29,15 @@ class AdminImportExportController extends AbstractController
private $groupImporter;
private $userPermImporter;
private $flashBag;
public function __construct(UserImporter $userImporter, GroupImporter $groupImporter, FlashBagInterface $flashBag) {
public function __construct(UserImporter $userImporter, GroupImporter $groupImporter, UserPermImporter $userPermImporter, FlashBagInterface $flashBag)
{
$this->userImporter = $userImporter;
$this->groupImporter = $groupImporter;
$this->userPermImporter = $userPermImporter;
$this->flashBag = $flashBag;
}
......@@ -92,7 +100,7 @@ class AdminImportExportController extends AbstractController
* @return Response
*/
private function importUsersPerms(ImportDataType $dataType, ImportStrategy $strategy, bool $dry, File $file, string $csvDelimiter): Response {
throw new NotImplementedException("AdminImportExportController.importUsersPerms");
return $this->importAny($this->userPermImporter, $dataType, $strategy, $dry, $file, $csvDelimiter);
}
/**
......@@ -110,8 +118,8 @@ class AdminImportExportController extends AbstractController
/**
* @param FormInterface $form
* @return Response
* @throws \Error
* @throws \Exception
* @throws Error
* @throws Exception
*/
private function processImportForm(FormInterface $form): Response {
/** @var ImportDataType $dataType */
......@@ -138,15 +146,15 @@ class AdminImportExportController extends AbstractController
return $this->importGroupsPerms($dataType, $strategy, $dry, $file, $csvDelimiter);
}
throw new \RuntimeException("Unreachable");
throw new RuntimeException("Unreachable");
}
/**
* @Route(path="/admin/users/import", name="admin_users_and_groups_import")
* @param Request $request
* @return Response
* @throws \Error
* @throws \Exception
* @throws Error
* @throws Exception
*/
public function importUserAndGroups(Request $request) : Response {
$form = $this->createForm(ImportType::class, [
......
<?php
namespace App\Service\Importer;
use App\Entity\User;
use App\Entity\UserPermission;
use App\Repository\UserPermissionRepository;
use App\Repository\UserRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Exception;
use Psr\Log\LoggerInterface;
class UserPermImporter extends AbstractImporter
{
private const COL_USER_EMAIL = 0;
private const COL_PERM_PATH = 1;
private const COL_PERM_READ = 2;
private const COL_PERM_WRITE = 3;
/**
* @var ObjectManager
*/
private $entityManager;
/**
* @var UserRepository
*/
private $userRepository;
/**
* @var UserPermissionRepository
*/
private $userPermRepository;
/**
* @var ImportLogger
*/
private $importLogger;
public function __construct(
ManagerRegistry $doctrine,
LoggerInterface $logger,
ImportLogger $importLogger)
{
parent::__construct($this, $logger);
$this->entityManager = $doctrine->getManager('ddec');
$this->userRepository = $this->entityManager->getRepository('App:User');
$this->userPermRepository = $this->entityManager->getRepository('App:UserPermission');
$this->importLogger = $importLogger;
}
public function getImportLog(): IImportLogger
{
return $this->importLogger;
}
protected function preCheck(): void
{
if ($this->getStrategy()->replace()) {
throw new ImportException("L'importation des permissions utilisateurs ne fonctionne pas avec la stratégie 'Remplacer'");
}
}
/**
* Flush repository
*/
protected function flushRepository(): void
{
$this->entityManager->flush();
}
/**
* Clear repository before import (used with Replace strategy)
*/
protected function clearRepository(): void
{
// Replace strategy is not supported by UserPermImporter
}
/**
* Process one line
* @param array $line
* @param int $lineNumber
* @throws ImportException
*/
protected function processLine(array $line, int $lineNumber): void
{
$this->getLogger()->debug("Process line $lineNumber: " . implode(',', $line), [
'line' => $line
]);
if (count($line) != 4)
throw new ImportException("Le fichier de permissions doit comporter exactement 4 champs par ligne", $lineNumber);
/** @var User $user */
$user = $this->userRepository->findOneBy(['email' => $line[self::COL_USER_EMAIL]]);
$this->getLogger()->debug("User loaded", [
'user' => $user,
]);
// If user doesn't exists
if ($user === null) {
$this->importLogger->reportError($lineNumber, $line, "L'utilisateur '" . $line[self::COL_USER_EMAIL] . "' n'existe pas.");
return;
}
try {
if ($this->getStrategy()->replace()) {
// In principle we never read that branch because we throw in preCheck in that case.
$this->addPermTo($user, $this->getPermFrom($line));
} else {
$perms = $this->getExistingPerm($line, $user);
$count = count($perms);
if ($count == 0) {
$this->addPermTo($user, $this->getPermFrom($line));
} else if ($count >= 1 && $this->getStrategy()->leaveExisting()) {
$this->importLogger->reportWarning($lineNumber, $line, "L'utilisateur " . $user->getEmail() . " a déjà une ou plusieurs permissions pour le chemin : " . $line[self::COL_PERM_PATH]);
} else if ($count == 1 && $this->getStrategy()->patchExisting()) {
$new_read = $line[self::COL_PERM_READ];
$new_write = $line[self::COL_PERM_WRITE];
$old_values = [];
$perm = $perms[0];
if ($new_read != $perm->getRead()) {
$old_values['perm_' . $perm->getPath() . '_read'] = $perm->getRead();
$perm->setRead($new_read);
}
if ($new_write != $perm->getWrite()) {
$old_values['perm_' . $perm->getPath() . '_write'] = $perm->getWrite();
$perm->setWrite($new_write);
}
if (count($old_values)) {
$this->importLogger->updateUser($user, $old_values);
}
} else {
$this->importLogger->reportWarning($lineNumber, $line, "L'utilisateur " . $user->getEmail() . " a plus d'une permission pour le chemin : " . $line[self::COL_PERM_PATH]);
}
}
} catch (Exception $e) {
throw new ImportException("Impossible de créer une permission depuis la ligne.", $lineNumber, $e);
}
}
private function addPermTo(User $user, UserPermission $perm)
{
$user->addPermission($perm);
$this->entityManager->persist($perm);
$this->importLogger->addUserPerm($user, $perm);
}
/**
* @param array $line
* @return UserPermission
* @throws Exception
*/
private function getPermFrom(array $line): UserPermission
{
$perm = new UserPermission();
$perm->setPath($line[self::COL_PERM_PATH]);
$perm->setRead($line[self::COL_PERM_READ]);
$perm->setWrite($line[self::COL_PERM_WRITE]);
return $perm;
}
/**
* @param array $line
* @param User $user
* @return UserPermission[]
*/
private function getExistingPerm(array $line, User $user): array
{
$permissions = $this->userPermRepository->findByUserAndPath($user, $line[self::COL_PERM_PATH]);
if ($permissions == null)
return [];
if ($permissions instanceof UserPermission)
return [$permissions];
return $permissions;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment