1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Nexendrie\Utils; |
5
|
|
|
|
6
|
|
|
use Nette\Utils\Strings; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Intervals |
10
|
|
|
* |
11
|
|
|
* @author Jakub Konečný |
12
|
|
|
*/ |
13
|
1 |
|
final class Intervals { |
14
|
|
|
use \Nette\StaticClass; |
15
|
|
|
|
16
|
|
|
public const PATTERN = '/(\{\-?\d+(,\-?\d+)*\})|((?P<start>\[|\])(?P<limit1>\-?\d+|\-Inf),(?P<limit2>\-?\d+|\+Inf)(?P<end>\[|\]))/'; |
|
|
|
|
17
|
|
|
|
18
|
|
|
public static function findInterval(string $text): ?string { |
19
|
1 |
|
preg_match(static::PATTERN, $text, $result); |
20
|
1 |
|
if(!is_array($result) || count($result) < 1) { |
21
|
1 |
|
return null; |
22
|
|
|
} |
23
|
1 |
|
return $result[0]; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public static function isInInterval(int $number, string $interval): bool { |
27
|
1 |
|
if(static::findInterval($interval) === null || $interval !== static::findInterval($interval)) { |
28
|
1 |
|
return false; |
29
|
|
|
} |
30
|
1 |
|
if(Strings::startsWith($interval, "{")) { |
31
|
|
|
/** @var int[] $numbers */ |
32
|
1 |
|
$numbers = explode(",", Strings::trim($interval, "{}")); |
33
|
1 |
|
array_walk($numbers, function(&$value): void { |
34
|
1 |
|
$value = (int) $value; |
35
|
1 |
|
}); |
36
|
1 |
|
return (in_array($number, $numbers, true)); |
37
|
|
|
} |
38
|
1 |
|
preg_match(static::PATTERN, $interval, $matches); |
39
|
1 |
|
$start = $matches["start"][0]; |
40
|
1 |
|
$end = $matches["end"][0]; |
41
|
1 |
|
$limit1 = (int) str_replace("-Inf", (string) PHP_INT_MIN, $matches["limit1"]); |
42
|
1 |
|
$limit2 = (int) str_replace("+Inf", (string) PHP_INT_MAX, $matches["limit2"]); |
43
|
1 |
|
if($limit1 > $limit2) { |
44
|
1 |
|
return false; |
45
|
1 |
|
} elseif($number < $limit1) { |
46
|
1 |
|
return false; |
47
|
1 |
|
} elseif($number > $limit2) { |
48
|
1 |
|
return false; |
49
|
1 |
|
} elseif($number === $limit1 && $start === "]") { |
50
|
1 |
|
return false; |
51
|
1 |
|
} elseif($number === $limit2 && $end === "[") { |
52
|
1 |
|
return false; |
53
|
|
|
} |
54
|
1 |
|
return true; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
?> |