12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- namespace App\Command;
- use App\Entity\User;
- use App\Repository\UserRepository;
- use Doctrine\ORM\EntityManagerInterface;
- use Symfony\Component\Console\Attribute\AsCommand;
- use Symfony\Component\Console\Command\Command;
- use Symfony\Component\Console\Input\InputArgument;
- use Symfony\Component\Console\Input\InputInterface;
- use Symfony\Component\Console\Input\InputOption;
- use Symfony\Component\Console\Output\OutputInterface;
- use Symfony\Component\Console\Style\SymfonyStyle;
- use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
- use Symfony\Component\Validator\Validator\ValidatorInterface;
- #[AsCommand(
- name: 'app:user:create',
- description: 'Créer un nouvel utilisateur',
- )]
- class UserCreateCommand extends Command
- {
- public function __construct(
- protected readonly UserRepository $userRepository,
- protected readonly EntityManagerInterface $em,
- protected readonly UserPasswordHasherInterface $passwordHasher,
- protected readonly ValidatorInterface $validator
- )
- {
- parent::__construct();
- }
- protected function execute(InputInterface $input, OutputInterface $output): int
- {
- $io = new SymfonyStyle($input, $output);
-
- $email = $io->ask("Email de l'utilisateur");
-
- $user = $this->userRepository->findOneBy(['email' => $email]);
-
- if ($user) {
- $modif = $io->confirm(sprintf("Utilisateur existant : %s\nVoulez vous le modifier", $user->getPseudo()), false);
- if (!$modif) {
- $io->info("Pas de modification");
- return Command::SUCCESS;
- }
- }
-
- $name = $io->ask("Nom de l'utilisateur");
- $plainPassword = $io->askHidden("Mot de passe");
-
- $user = $user ?? new User();
- $user->setName($name);
- $user->setEmail($email);
- $user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));
- $errors = $this->validator->validate($user);
- if (count($errors) > 0) {
- $errorsString = (string) $errors;
- $io->error($errorsString);
- return Command::INVALID;
- }
- $this->em->persist($user);
- $this->em->flush();
- $io->success('Le nouvel utilisateur a été créé');
- return Command::SUCCESS;
- }
- }
|