Attempt::make()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 8
cts 8
cp 1
rs 9.7
c 0
b 0
f 0
cc 4
nc 2
nop 3
crap 4
1
<?php
2
3
namespace Openbuildings\Spiderling;
4
5
/**
6
 * A helper class to express attempting to do something several times with a small interval
7
 *
8
 * @package    Openbuildings\Spiderling
9
 * @author     Ivan Kerin
10
 * @copyright  (c) 2013 OpenBuildings Ltd.
11
 * @license    http://spdx.org/licenses/BSD-3-Clause
12
 */
13
class Attempt {
14
15
	/**
16
	 * Execute $callable until $timeout is reached. By doing an attempt each $step milliseconds
17
	 * @param  Callable  $callbale the method to be called, if the result is FALSE, try again until TRUE or timeout reached
18
	 * @param  integer $timeout  timeout in milliseconds
19
	 * @param  integer $step
20
	 * @return mixed            first not FALSE result
21
	 */
22 26
	public static function make($callbale, $timeout = 2000, $step = 50)
23
	{
24 26
		$retries = ceil($timeout / $step);
25
26
		do
27
		{
28 26
			$result = $callbale();
29 26
			$retries -= 1;
30 26
			if ( ! $result)
31
			{
32 7
				usleep($step * 1000);
33
			}
34
		}
35 26
		while ($retries > 0 AND ! $result);
36
37 26
		return $result;
38
	}
39
40
}
41