vendor/nucleos/user-bundle/src/Form/Type/LoginFormType.php line 26

  1. <?php
  2. /*
  3. * (c) Christian Gripp <mail@core23.de>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. namespace Nucleos\UserBundle\Form\Type;
  9. use Symfony\Component\Form\AbstractType;
  10. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  11. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  12. use Symfony\Component\Form\Extension\Core\Type\TextType;
  13. use Symfony\Component\Form\FormBuilderInterface;
  14. use Symfony\Component\Form\FormError;
  15. use Symfony\Component\Form\FormEvent;
  16. use Symfony\Component\Form\FormEvents;
  17. use Symfony\Component\OptionsResolver\OptionsResolver;
  18. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. /**
  21. * @extends AbstractType<mixed>
  22. */
  23. final class LoginFormType extends AbstractType
  24. {
  25. private readonly AuthenticationUtils $authenticationUtils;
  26. private readonly TranslatorInterface $translator;
  27. public function __construct(AuthenticationUtils $authenticationUtils, TranslatorInterface $translator)
  28. {
  29. $this->authenticationUtils = $authenticationUtils;
  30. $this->translator = $translator;
  31. }
  32. public function buildForm(FormBuilderInterface $builder, array $options): void
  33. {
  34. $builder
  35. ->add('_username', TextType::class, [
  36. 'label' => 'security.login.username',
  37. 'attr' => [
  38. 'autocomplete' => 'username',
  39. ],
  40. ])
  41. ->add('_password', PasswordType::class, [
  42. 'label' => 'security.login.password',
  43. 'attr' => [
  44. 'autocomplete' => 'password',
  45. ],
  46. ])
  47. ->add('_target_path', HiddenType::class)
  48. ;
  49. $authenticationUtils = $this->authenticationUtils;
  50. $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($authenticationUtils): void {
  51. $error = $authenticationUtils->getLastAuthenticationError();
  52. if (null !== $error) {
  53. $message = $this->translator->trans($error->getMessageKey(), [], 'security');
  54. $event->getForm()->addError(new FormError($message));
  55. }
  56. $event->setData(array_replace((array) $event->getData(), [
  57. 'username' => $authenticationUtils->getLastUsername(),
  58. ]));
  59. });
  60. }
  61. public function configureOptions(OptionsResolver $resolver): void
  62. {
  63. $resolver->setDefaults([
  64. 'translation_domain' => 'NucleosUserBundle',
  65. 'csrf_field_name' => '_csrf_token',
  66. 'csrf_token_id' => 'authenticate',
  67. ]);
  68. }
  69. public function getBlockPrefix(): string
  70. {
  71. return '';
  72. }
  73. }