View source
<?php
namespace Drupal\recaptcha_v3\Form;
use Drupal\captcha\Service\CaptchaService;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\recaptcha_v3\Entity\ReCaptchaV3Action;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ReCaptchaV3ActionForm extends EntityForm {
protected $captchaService;
public function __construct(CaptchaService $captcha_service) {
$this->captchaService = $captcha_service;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('captcha.helper'));
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$recaptcha_v3_action = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#maxlength' => 255,
'#default_value' => $recaptcha_v3_action
->label(),
'#description' => $this
->t('Label for the reCAPTCHA v3 action.'),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $recaptcha_v3_action
->id(),
'#required' => TRUE,
'#machine_name' => [
'exists' => [
ReCaptchaV3Action::class,
'load',
],
],
'#disabled' => !$recaptcha_v3_action
->isNew(),
];
$form['threshold'] = [
'#type' => 'number',
'#title' => $this
->t('Threshold'),
'#min' => 0,
'#max' => 1,
'#step' => 0.1,
'#required' => TRUE,
'#default_value' => $recaptcha_v3_action
->getThreshold(),
];
$challenges = $this->captchaService
->getAvailableChallengeTypes(FALSE);
$challenges = array_filter($challenges, static function ($captcha_type) {
return !(strpos($captcha_type, 'recaptcha_v3') === 0);
}, ARRAY_FILTER_USE_KEY);
$challenges = [
'default' => $this
->t('Default fallback challenge'),
] + $challenges;
$form['challenge'] = [
'#type' => 'select',
'#title' => $this
->t('Fallback challenge'),
'#description' => $this
->t('Select the fallback challenge on reCAPTCHA v3 user validation fail.'),
'#options' => $challenges,
'#default_value' => $recaptcha_v3_action
->getChallenge(),
'#empty_option' => $this
->t('- None -'),
'#empty_value' => '',
];
return $form;
}
public function save(array $form, FormStateInterface $form_state) {
$label = $this->entity
->label();
$saved_state = parent::save($form, $form_state);
switch ($saved_state) {
case SAVED_NEW:
$this
->messenger()
->addStatus($this
->t('Created the %label reCAPTCHA v3 action.', [
'%label' => $label,
]));
$this
->getLogger('recaptcha_v3')
->info('Created the %label reCAPTCHA v3 action.', [
'%label' => $label,
]);
break;
default:
$this
->messenger()
->addStatus($this
->t('Saved the %label reCAPTCHA v3 action.', [
'%label' => $label,
]));
$this
->getLogger('recaptcha_v3')
->info('Saved the %label reCAPTCHA v3 action.', [
'%label' => $label,
]);
}
$form_state
->setRedirectUrl($this->entity
->toUrl('collection'));
return $saved_state;
}
}