-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractCaptcha.php
74 lines (59 loc) · 1.93 KB
/
AbstractCaptcha.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
<?php
namespace Ady\Bundle\CaptchaBundle\Captcha;
use Ady\Bundle\CaptchaBundle\Contracts\CaptchaInterface;
use Ady\Bundle\CaptchaBundle\Service\DictionaryService;
use RuntimeException;
use Symfony\Contracts\Translation\TranslatorInterface;
abstract class AbstractCaptcha implements CaptchaInterface
{
protected const INDEX_MAPPING = [];
/**
* @var DictionaryService
*/
protected $dictionary;
/**
* @var TranslatorInterface
*/
protected $translator;
public function __construct(DictionaryService $dictionary, TranslatorInterface $translator)
{
$this->dictionary = $dictionary;
$this->translator = $translator;
}
public function getChallenge(): array
{
$letterIndex = $this->getRandomIndex();
$word = $this->dictionary->getRandomWord();
return [
$this->getQuestion($word, $letterIndex),
$this->getAnswer($word, $letterIndex),
];
}
protected function getQuestion(string $word, int $letterIndex): string
{
throw new RuntimeException('You must override this method.');
}
protected function getAnswer(string $word, int $letterIndex): string
{
throw new RuntimeException('You must override this method.');
}
public function checkAnswer($expected, $given): bool
{
return strtoupper($given) === strtoupper($expected);
}
protected function getRandomIndex(): string
{
if (!is_array($this::INDEX_MAPPING) || [] === $this::INDEX_MAPPING) {
throw new RuntimeException('INDEX_MAPPING constant must be an array and be overridden.');
}
return array_rand($this::INDEX_MAPPING);
}
protected function handleLastIndex(string $word, int $letterIndex): array
{
if (0 > $letterIndex) {
$letterIndex = abs($letterIndex) - 1;
$word = strrev($word);
}
return [$word, $letterIndex];
}
}