Completed
Pull Request — master (#20)
by Haralan
18:05 queued 16:21
created

Attempt::make()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.5923

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 6
cts 9
cp 0.6667
rs 9.2
cc 4
eloc 9
nc 2
nop 3
crap 4.5923
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 7
	public static function make($callbale, $timeout = 2000, $step = 50)
23
	{
24
		$retries = ceil($timeout / $step);
25
26
		do
27
		{
28
			$result = $callbale();
29 7
			$retries -= 1;
30 7
			if ( ! $result)
31
			{
32
				usleep($step * 1000);
33
			}
34
		}
35 7
		while ($retries > 0 AND ! $result);
36
37 7
		return $result;
38 3
	}
39
40
}
41