Completed
Push — master ( 27da95...1cbe19 )
by Ron
06:49
created

IntervalParser::nearst()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
namespace Kir\Services\Cmd\Dispatcher\Common;
3
4
use Exception;
5
6
class IntervalParser {
7
	/**
8
	 * @param string|int $interval
9
	 * @return int
10
	 */
11
	public static function parse($interval) {
12
		if(is_array($interval)) {
13
			$result = [];
14
			foreach($interval as $intervalStr) {
15
				$result[] = self::parseString($intervalStr);
16
			}
17
			return min($result);
18
		} else {
19
			return self::parseString((string) $interval);
20
		}
21
	}
22
23
	/**
24
	 * @param int|string $interval
25
	 * @return int
26
	 */
27
	private static function parseString($interval) {
28
		if(preg_match('/^\\d+$/', $interval)) {
29
			return $interval;
30
		}
31
		if(preg_match('/^(\\d{1,2}|\\*):(\\d{1,2}|\\*)(?::(\\d{1,2}|\\*))?$/', $interval, $matches)) {
32
			$matches[] = 0;
33
			list($hours, $minutes, $seconds) = array_slice($matches, 1);
34
			$possibleDates = [
35
				sprintf('today %02d:%02d:%02d', $hours, $minutes, $seconds),
36
				sprintf('tomorrow %02d:%02d:%02d', $hours, $minutes, $seconds),
37
			];
38
			return self::nearst($possibleDates);
39
		}
40
	}
41
42
	/**
43
	 * @param array $possibleDates
44
	 * @return int
45
	 * @throws Exception
46
	 */
47
	private static function nearst(array $possibleDates) {
48
		foreach($possibleDates as $possibleDate) {
49
			$time = strtotime($possibleDate);
50
			if($time > time()) {
51
				return $time - time();
52
			}
53
		}
54
		throw new Exception('No alternative lays in the future');
55
	}
56
}
57