-
Notifications
You must be signed in to change notification settings - Fork 43
/
AsyncCaptchaSolvingCallback.php
58 lines (52 loc) · 1.55 KB
/
AsyncCaptchaSolvingCallback.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
<?php
/**
* @license see LICENSE
*/
namespace Serps\Core\Captcha;
class AsyncCaptchaSolvingCallback implements AsyncCaptchaSolvingInterface
{
protected $getCaptchaCb;
protected $captchaDone = null;
protected $tryForDefaultDelay;
/**
* @param callable $getCaptcha handler called to get captcha if it was solved
* @param int $tryFprDefaultDelay default delay to use in the tryFor() method
*/
public function __construct(callable $getCaptcha, $tryForDefaultDelay = 1000)
{
$this->getCaptchaCb = $getCaptcha;
$this->tryForDefaultDelay = $tryForDefaultDelay;
}
public function getCaptcha()
{
if (null === $this->captchaDone) {
$captcha = call_user_func($this->getCaptchaCb);
if (false !== $captcha) {
$this->captchaDone = $captcha;
}
return $captcha;
} else {
return $this->captchaDone;
}
}
/**
* try to get the captcha for the given time
* @param int $time max time to wait in second
* @param int $interval interval between 2 test in micro second
* @return null|mixed
*/
public function tryFor($time, $interval = null)
{
if (null == $interval) {
$interval = $this->tryForDefaultDelay;
}
$tryUntil = microtime(true) + ($time / 1000);
while ($tryUntil > microtime(true)) {
if ($c = $this->getCaptcha()) {
return $c;
}
usleep($interval);
}
return null;
}
}