UserCreateCommand.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. $plainPassword = $io->askHidden("Mot de passe");
  35. $user = new User();
  36. $user->setEmail($email);
  37. $user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));
  38. $errors = $this->validator->validate($user);
  39. if (count($errors) > 0) {
  40. $errorsString = (string) $errors;
  41. $io->error($$errorsString);
  42. return Command::INVALID;
  43. }
  44. $this->em->persist($user);
  45. $this->em->flush();
  46. $io->success('Le nouvel utilisateur a été créé');
  47. return Command::SUCCESS;
  48. }
  49. }