mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-21 15:13:50 +00:00
fix: SA: Fix many critical rules.
SA stands for Static Analysis.
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Chill\MainBundle\Command;
|
||||
|
||||
use Chill\MainBundle\Repository\UserRepository;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
@@ -23,82 +26,35 @@ use League\Csv\Writer;
|
||||
|
||||
class ChillImportUsersCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
* @var EntityManagerInterface
|
||||
*/
|
||||
protected $em;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var ValidatorInterface
|
||||
*/
|
||||
protected $validator;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var LoggerInterface
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var UserPasswordEncoderInterface
|
||||
*/
|
||||
protected $passwordEncoder;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var \Chill\MainBundle\Repository\UserRepository
|
||||
*/
|
||||
protected $userRepository;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $doChanges = true;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var OutputInterface
|
||||
*/
|
||||
protected $tempOutput;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var InputInterface
|
||||
*/
|
||||
protected $tempInput;
|
||||
|
||||
protected EntityManagerInterface $em;
|
||||
|
||||
protected ValidatorInterface $validator;
|
||||
|
||||
protected LoggerInterface $logger;
|
||||
|
||||
protected UserPasswordEncoderInterface $passwordEncoder;
|
||||
|
||||
protected UserRepository $userRepository;
|
||||
|
||||
protected bool $doChanges = true;
|
||||
|
||||
protected OutputInterface $tempOutput;
|
||||
|
||||
protected InputInterface $tempInput;
|
||||
|
||||
/**
|
||||
* Centers and aliases.
|
||||
*
|
||||
*
|
||||
* key are aliases, values are an array of centers
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $centers = [];
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $permissionGroups = [];
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $groupCenters = [];
|
||||
|
||||
/**
|
||||
*
|
||||
* @var Writer
|
||||
*/
|
||||
protected $output = null;
|
||||
|
||||
protected array $centers;
|
||||
|
||||
protected array $permissionGroups;
|
||||
|
||||
protected array $groupCenters;
|
||||
|
||||
protected Writer $output;
|
||||
|
||||
public function __construct(
|
||||
EntityManagerInterface $em,
|
||||
LoggerInterface $logger,
|
||||
@@ -109,15 +65,12 @@ class ChillImportUsersCommand extends Command
|
||||
$this->passwordEncoder = $passwordEncoder;
|
||||
$this->validator = $validator;
|
||||
$this->logger = $logger;
|
||||
|
||||
|
||||
|
||||
$this->userRepository = $em->getRepository(User::class);
|
||||
|
||||
|
||||
parent::__construct('chill:main:import-users');
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this
|
||||
@@ -126,25 +79,24 @@ class ChillImportUsersCommand extends Command
|
||||
->addArgument('csvfile', InputArgument::REQUIRED, 'Path to the csv file. Columns are: `username`, `email`, `center` (can contain alias), `permission group`')
|
||||
->addOption('grouping-centers', null, InputOption::VALUE_OPTIONAL, 'Path to a csv file to aggregate multiple centers into a single alias')
|
||||
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Do not commit the changes')
|
||||
->addOption('csv-dump', null, InputOption::VALUE_REQUIRED, 'A path to dump a summary of the created file')
|
||||
;
|
||||
->addOption('csv-dump', null, InputOption::VALUE_REQUIRED, 'A path to dump a summary of the created file');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output)
|
||||
{
|
||||
$this->tempOutput = $output;
|
||||
$this->tempInput = $input;
|
||||
|
||||
|
||||
if ($input->getOption('dry-run')) {
|
||||
$this->doChanges = false;
|
||||
}
|
||||
|
||||
|
||||
$this->prepareWriter();
|
||||
|
||||
|
||||
if ($input->hasOption('grouping-centers')) {
|
||||
$this->prepareGroupingCenters();
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
$this->loadUsers();
|
||||
}
|
||||
@@ -152,19 +104,19 @@ class ChillImportUsersCommand extends Command
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected function prepareWriter()
|
||||
{
|
||||
$this->output = $output = Writer::createFromPath($this->tempInput
|
||||
->getOption('csv-dump'), 'a+');
|
||||
|
||||
|
||||
$output->insertOne([
|
||||
'email',
|
||||
'username',
|
||||
'id'
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
protected function appendUserToFile(User $user)
|
||||
{
|
||||
$this->output->insertOne( [
|
||||
@@ -173,35 +125,35 @@ class ChillImportUsersCommand extends Command
|
||||
$user->getId()
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
protected function loadUsers()
|
||||
{
|
||||
$reader = Reader::createFromPath($this->tempInput->getArgument('csvfile'));
|
||||
$reader->setHeaderOffset(0);
|
||||
|
||||
|
||||
foreach ($reader->getRecords() as $line => $r) {
|
||||
$this->logger->debug("starting handling new line", [
|
||||
'line' => $line
|
||||
]);
|
||||
|
||||
|
||||
if ($this->doesUserExists($r)) {
|
||||
$this->tempOutput->writeln(sprintf("User with username '%s' already "
|
||||
. "exists, skipping", $r["username"]));
|
||||
|
||||
|
||||
$this->logger->info("One user already exists, skipping creation", [
|
||||
'username_in_file' => $r['username'],
|
||||
'email_in_file' => $r['email'],
|
||||
'line' => $line
|
||||
]);
|
||||
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
$user = $this->createUser($line, $r);
|
||||
$this->appendUserToFile($user);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected function doesUserExists($data)
|
||||
{
|
||||
if ($this->userRepository->countByUsernameOrEmail($data['username']) > 0) {
|
||||
@@ -211,10 +163,10 @@ class ChillImportUsersCommand extends Command
|
||||
if ($this->userRepository->countByUsernameOrEmail($data['email']) > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
protected function createUser($offset, $data)
|
||||
{
|
||||
$user = new User();
|
||||
@@ -222,41 +174,41 @@ class ChillImportUsersCommand extends Command
|
||||
->setEmail(\trim($data['email']))
|
||||
->setUsername(\trim($data['username']))
|
||||
->setEnabled(true)
|
||||
->setPassword($this->passwordEncoder->encodePassword($user,
|
||||
->setPassword($this->passwordEncoder->encodePassword($user,
|
||||
\bin2hex(\random_bytes(32))))
|
||||
;
|
||||
|
||||
|
||||
$errors = $this->validator->validate($user);
|
||||
|
||||
|
||||
if ($errors->count() > 0) {
|
||||
$errorMessages = $this->concatenateViolations($errors);
|
||||
|
||||
|
||||
$this->tempOutput->writeln(sprintf("%d errors found with user with username \"%s\" at line %d", $errors->count(), $data['username'], $offset));
|
||||
$this->tempOutput->writeln($errorMessages);
|
||||
|
||||
throw new \RuntimeException("Found errors while creating an user. "
|
||||
. "Watch messages in command output");
|
||||
}
|
||||
|
||||
|
||||
$pgs = $this->getPermissionGroup($data['permission group']);
|
||||
$centers = $this->getCenters($data['center']);
|
||||
|
||||
|
||||
foreach($pgs as $pg) {
|
||||
foreach ($centers as $center) {
|
||||
$groupcenter = $this->createOrGetGroupCenter($center, $pg);
|
||||
|
||||
|
||||
if (FALSE === $user->getGroupCenters()->contains($groupcenter)) {
|
||||
$user->addGroupCenter($groupcenter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
if ($this->doChanges) {
|
||||
$this->em->persist($user);
|
||||
$this->em->flush();
|
||||
}
|
||||
|
||||
|
||||
$this->logger->notice("Create user", [
|
||||
'username' => $user->getUsername(),
|
||||
'id' => $user->getId(),
|
||||
@@ -265,65 +217,58 @@ class ChillImportUsersCommand extends Command
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
|
||||
protected function getPermissionGroup($alias)
|
||||
{
|
||||
if (\array_key_exists($alias, $this->permissionGroups)) {
|
||||
return $this->permissionGroups[$alias];
|
||||
}
|
||||
|
||||
|
||||
$permissionGroupsByName = [];
|
||||
|
||||
|
||||
foreach($this->em->getRepository(PermissionsGroup::class)
|
||||
->findAll() as $permissionGroup) {
|
||||
$permissionGroupsByName[$permissionGroup->getName()] = $permissionGroup;
|
||||
}
|
||||
|
||||
|
||||
if (count($permissionGroupsByName) === 0) {
|
||||
throw new \RuntimeException("no permission groups found. Create them "
|
||||
. "before importing users");
|
||||
}
|
||||
|
||||
$question = new ChoiceQuestion("To which permission groups associate with \"$alias\" ?",
|
||||
|
||||
$question = new ChoiceQuestion("To which permission groups associate with \"$alias\" ?",
|
||||
\array_keys($permissionGroupsByName));
|
||||
$question
|
||||
->setMultiselect(true)
|
||||
->setAutocompleterValues(\array_keys($permissionGroupsByName))
|
||||
->setNormalizer(function($value) {
|
||||
if (NULL === $value) { return ''; }
|
||||
|
||||
|
||||
return \trim($value);
|
||||
})
|
||||
;
|
||||
$helper = $this->getHelper('question');
|
||||
|
||||
|
||||
$keys = $helper->ask($this->tempInput, $this->tempOutput, $question);
|
||||
|
||||
|
||||
$this->tempOutput->writeln("You have chosen ".\implode(", ", $keys));
|
||||
|
||||
if ($helper->ask($this->tempInput, $this->tempOutput,
|
||||
|
||||
if ($helper->ask($this->tempInput, $this->tempOutput,
|
||||
new ConfirmationQuestion("Are you sure ?", true))) {
|
||||
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$this->permissionGroups[$alias][] = $permissionGroupsByName[$key];
|
||||
}
|
||||
|
||||
|
||||
return $this->permissionGroups[$alias];
|
||||
} else {
|
||||
$this->logger->error("Error while responding to a a question");
|
||||
|
||||
$this->tempOutput("Ok, I accept, but I do not know what to do. Please try again.");
|
||||
|
||||
throw new \RuntimeException("Error while responding to a question");
|
||||
}
|
||||
|
||||
$this->logger->error('Error while responding to a a question');
|
||||
$this->tempOutput->writeln('Ok, I accept, but I do not know what to do. Please try again.');
|
||||
|
||||
throw new \RuntimeException('Error while responding to a question');
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Center $center
|
||||
* @param \Chill\MainBundle\Command\PermissionGroup $pg
|
||||
* @return GroupCenter
|
||||
*/
|
||||
|
||||
protected function createOrGetGroupCenter(Center $center, PermissionsGroup $pg): GroupCenter
|
||||
{
|
||||
if (\array_key_exists($center->getId(), $this->groupCenters)) {
|
||||
@@ -331,36 +276,36 @@ class ChillImportUsersCommand extends Command
|
||||
return $this->groupCenters[$center->getId()][$pg->getId()];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$repository = $this->em->getRepository(GroupCenter::class);
|
||||
|
||||
|
||||
$groupCenter = $repository->findOneBy(array(
|
||||
'center' => $center,
|
||||
'permissionsGroup' => $pg
|
||||
));
|
||||
|
||||
|
||||
if ($groupCenter === NULL) {
|
||||
$groupCenter = new GroupCenter();
|
||||
$groupCenter
|
||||
->setCenter($center)
|
||||
->setPermissionsGroup($pg)
|
||||
;
|
||||
|
||||
|
||||
$this->em->persist($groupCenter);
|
||||
}
|
||||
|
||||
|
||||
$this->groupCenters[$center->getId()][$pg->getId()] = $groupCenter;
|
||||
|
||||
|
||||
return $groupCenter;
|
||||
}
|
||||
|
||||
|
||||
protected function prepareGroupingCenters()
|
||||
{
|
||||
$reader = Reader::createFromPath($this->tempInput->getOption('grouping-centers'));
|
||||
$reader->setHeaderOffset(0);
|
||||
|
||||
|
||||
foreach ($reader->getRecords() as $r) {
|
||||
$this->centers[$r['alias']] =
|
||||
$this->centers[$r['alias']] =
|
||||
\array_merge(
|
||||
$this->centers[$r['alias']] ?? [],
|
||||
$this->getCenters($r['center']
|
||||
@@ -368,18 +313,18 @@ class ChillImportUsersCommand extends Command
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* return a list of centers matching the name of alias.
|
||||
*
|
||||
*
|
||||
* If the name match one center, this center is returned in an array.
|
||||
*
|
||||
* If the name match an alias, the centers corresponding to the alias are
|
||||
*
|
||||
* If the name match an alias, the centers corresponding to the alias are
|
||||
* returned in an array.
|
||||
*
|
||||
*
|
||||
* If the center is not found or alias is not created, a new center is created
|
||||
* and suggested to user
|
||||
*
|
||||
*
|
||||
* @param string $name the name of the center or the alias regrouping center
|
||||
* @return Center[]
|
||||
*/
|
||||
@@ -387,62 +332,62 @@ class ChillImportUsersCommand extends Command
|
||||
{
|
||||
// sanitize
|
||||
$name = \trim($name);
|
||||
|
||||
|
||||
if (\array_key_exists($name, $this->centers)) {
|
||||
return $this->centers[$name];
|
||||
}
|
||||
|
||||
|
||||
// search for a center with given name
|
||||
$center = $this->em->getRepository(Center::class)
|
||||
->findOneByName($name);
|
||||
|
||||
|
||||
if ($center instanceof Center) {
|
||||
$this->centers[$name] = [$center];
|
||||
|
||||
|
||||
return $this->centers[$name];
|
||||
}
|
||||
|
||||
|
||||
// suggest and create
|
||||
$center = (new Center())
|
||||
->setName($name);
|
||||
|
||||
|
||||
$this->tempOutput->writeln("Center with name \"$name\" not found.");
|
||||
$qFormatter = $this->getHelper('question');
|
||||
$question = new ConfirmationQuestion("Create a center with name \"$name\" ?", true);
|
||||
|
||||
|
||||
if ($qFormatter->ask($this->tempInput, $this->tempOutput, $question)) {
|
||||
$this->centers[$name] = [ $center ];
|
||||
|
||||
|
||||
$errors = $this->validator->validate($center);
|
||||
|
||||
|
||||
if ($errors->count() > 0) {
|
||||
$errorMessages = $this->concatenateViolations($errors);
|
||||
|
||||
|
||||
$this->tempOutput->writeln(sprintf("%d errors found with center with name \"%s\"", $errors->count(), $name));
|
||||
$this->tempOutput->writeln($errorMessages);
|
||||
|
||||
|
||||
throw new \RuntimeException("Found errors while creating one center. "
|
||||
. "Watch messages in command output");
|
||||
}
|
||||
|
||||
|
||||
$this->em->persist($center);
|
||||
|
||||
|
||||
return $this->centers[$name];
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
protected function concatenateViolations(ConstraintViolationListInterface $list)
|
||||
{
|
||||
$str = [];
|
||||
|
||||
|
||||
foreach ($list as $e) {
|
||||
/* @var $e \Symfony\Component\Validator\ConstraintViolationInterface */
|
||||
$str[] = $e->getMessage();
|
||||
}
|
||||
|
||||
|
||||
return \implode(";", $str);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user