UserCreateCommand.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Command;
  3. use App\Entity\User;
  4. use App\Repository\UserRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Console\Attribute\AsCommand;
  7. use Symfony\Component\Console\Command\Command;
  8. use Symfony\Component\Console\Input\InputArgument;
  9. use Symfony\Component\Console\Input\InputInterface;
  10. use Symfony\Component\Console\Input\InputOption;
  11. use Symfony\Component\Console\Output\OutputInterface;
  12. use Symfony\Component\Console\Style\SymfonyStyle;
  13. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Validator\Validator\ValidatorInterface;
  15. #[AsCommand(
  16. name: 'app:user:create',
  17. description: 'Créer un nouvel utilisateur',
  18. )]
  19. class UserCreateCommand extends Command
  20. {
  21. public function __construct(
  22. protected readonly UserRepository $userRepository,
  23. protected readonly EntityManagerInterface $em,
  24. protected readonly UserPasswordHasherInterface $passwordHasher,
  25. protected readonly ValidatorInterface $validator
  26. )
  27. {
  28. parent::__construct();
  29. }
  30. protected function execute(InputInterface $input, OutputInterface $output): int
  31. {
  32. $io = new SymfonyStyle($input, $output);
  33. $email = $io->ask("Email de l'utilisateur");
  34. $user = $this->userRepository->findOneBy(['email' => $email]);
  35. if ($user) {
  36. $modif = $io->confirm(sprintf("Utilisateur existant : %s\nVoulez vous le modifier", $user->getPseudo()), false);
  37. if (!$modif) {
  38. $io->info("Pas de modification");
  39. return Command::SUCCESS;
  40. }
  41. }
  42. $name = $io->ask("Nom de l'utilisateur");
  43. $plainPassword = $io->askHidden("Mot de passe");
  44. $user = $user ?? new User();
  45. $user->setName($name);
  46. $user->setEmail($email);
  47. $user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));
  48. $errors = $this->validator->validate($user);
  49. if (count($errors) > 0) {
  50. $errorsString = (string) $errors;
  51. $io->error($errorsString);
  52. return Command::INVALID;
  53. }
  54. $this->em->persist($user);
  55. $this->em->flush();
  56. $io->success('Le nouvel utilisateur a été créé');
  57. return Command::SUCCESS;
  58. }
  59. }