-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
ReCaptchaField.php
91 lines (67 loc) · 1.75 KB
/
ReCaptchaField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php declare(strict_types = 1);
namespace Contributte\ReCaptcha\Forms;
use Contributte\ReCaptcha\ReCaptchaProvider;
use Nette\Forms\Controls\TextInput;
use Nette\Forms\Form;
use Nette\Forms\Rules;
use Nette\Utils\Html;
class ReCaptchaField extends TextInput
{
private ReCaptchaProvider $provider;
private bool $configured = false;
private ?string $message = null;
public function __construct(ReCaptchaProvider $provider, ?string $label = null, ?string $message = null)
{
parent::__construct($label);
$this->provider = $provider;
$this->setOmitted(true);
$this->control = Html::el('div');
$this->control->addClass('g-recaptcha');
$this->message = $message;
}
public function loadHttpData(): void
{
$form = $this->getForm();
assert($form !== null);
$this->setValue($form->getHttpData(Form::DATA_TEXT, ReCaptchaProvider::FORM_PARAMETER));
}
public function setMessage(string $message): self
{
$this->message = $message;
return $this;
}
public function validate(): void
{
$this->configureValidation();
parent::validate();
}
public function getRules(): Rules
{
$this->configureValidation();
return parent::getRules();
}
public function verify(): bool
{
return $this->provider->validateControl($this) === true;
}
public function getControl(): Html
{
$this->configureValidation();
$el = parent::getControl();
$el->addAttributes([
'id' => $this->getHtmlId(),
'name' => $this->getHtmlName(),
'data-sitekey' => $this->provider->getSiteKey(),
]);
return $el;
}
private function configureValidation(): void
{
if ($this->configured) {
return;
}
$this->configured = true;
$message = $this->message ?? 'Are you a bot?';
$this->addRule(fn ($code): bool => $this->verify() === true, $message);
}
}