<?php
/**
* @file
* Class for updating passwords.
*/
namespace App\Form;
use stdClass;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Regex;
/**
* Password update form
*/
class SetPasswordFormType extends AbstractType
{
/**
* {@Inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pass', PasswordType::class, [
'label' => 'New Password',
'constraints' => $this->getPasswordConstraints($options['password_constraints']),
])
->add('confirm_pass', PasswordType::class, [
'label' => 'Confirm Password',
'constraints' => $this->getPasswordConstraints($options['password_constraints']),
])
->add('verification_code', TextType::class)
->add('submit', SubmitType::class, [
'label' => "Set Password",
]);
}
/**
* {@Inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// Configure your form options here
'password_constraints' => null,
]);
}
/**
* Create the password constraints array based on the provided object.
*
* @param object|null $constraints The constraints object.
*
* @return array
*/
private function getPasswordConstraints(object $constraints = null): array
{
$out = [];
if (!$constraints) {
// No constraints provided just return the empty array.
return [];
}
// Set minimum length.
$out[] = new Length([
'min' => $constraints->minLength,
]);
if ($constraints->requireLowercase) {
$out[] = new Regex([
'pattern' => '/[a-z]/',
'message' => 'Passwords must contain at least one lowercase letter.',
]);
}
if ($constraints->requireUppercase) {
$out[] = new Regex([
'pattern' => '/[A-Z]/',
'message' => 'Passwords must contain at least one uppercase letter.',
]);
}
if ($constraints->requireNumber) {
$out[] = new Regex([
'pattern' => '/[0-9]/',
'message' => 'Passwords must contain at least one number.',
]);
}
if ($constraints->requireSpecialChar) {
$out[] = new Regex([
'pattern' => '/[!@#$%^&*()\.,\-_+=:;]/',
'message' => 'Passwords must contain at least one special character.',
]);
}
return $out;
}
}