-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCharRange.php
More file actions
95 lines (79 loc) · 2.25 KB
/
CharRange.php
File metadata and controls
95 lines (79 loc) · 2.25 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace TaranovEgor\StringGenerator;
/**
* Predefined ASCII character ranges for random string generation.
*
* @link https://en.wikipedia.org/wiki/ASCII
*/
enum CharRange
{
/** Digits 0-9 */
case Numeric;
/** Lowercase a-z */
case Lowercase;
/** Uppercase A-Z */
case Uppercase;
/** Printable special characters (!@#$%^&* etc.) */
case Special;
/** Letters a-zA-Z */
case Alpha;
/** Letters + digits a-zA-Z0-9 */
case AlphaNumeric;
/** All printable ASCII (33-126) */
case Any;
/**
* Returns the ASCII code-point ranges for this variant.
*
* @return list<array{int<0, 255>, int<0, 255>}>
*/
public function ranges(): array
{
return match ($this) {
self::Numeric => [[48, 57]],
self::Lowercase => [[97, 122]],
self::Uppercase => [[65, 90]],
self::Special => [[33, 47], [58, 64], [91, 96], [123, 126]],
self::Alpha => self::combine(self::Lowercase, self::Uppercase),
self::AlphaNumeric => self::combine(self::Alpha, self::Numeric),
self::Any => [[33, 126]],
};
}
/**
* Builds and caches the flat alphabet string for this variant.
*
* The result is computed once per enum case and reused on subsequent calls.
*/
public function alphabet(): string
{
/** @var array<string, string> $cache */
static $cache = [];
return $cache[$this->name] ??= self::buildAlphabet($this->ranges());
}
/**
* @param list<array{int<0, 255>, int<0, 255>}> $ranges
*/
public static function buildAlphabet(array $ranges): string
{
$chars = '';
foreach ($ranges as [$min, $max]) {
for ($i = $min; $i <= $max; $i++) {
$chars .= \chr($i);
}
}
return $chars;
}
/**
* @return list<array{int<0, 255>, int<0, 255>}>
*/
private static function combine(self ...$cases): array
{
$combined = [];
foreach ($cases as $case) {
foreach ($case->ranges() as $range) {
$combined[] = $range;
}
}
return $combined;
}
}