1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace UCD\Unicode\Codepoint; |
4
|
|
|
|
5
|
|
|
use UCD\Unicode\Codepoint; |
6
|
|
|
use UCD\Unicode\Codepoint\Range\RangeRegexBuilder; |
7
|
|
|
use UCD\Unicode\Collection\TraversableBackedCollection; |
8
|
|
|
|
9
|
|
|
class Collection extends TraversableBackedCollection |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @return \Traversable|int[] |
13
|
|
|
*/ |
14
|
|
|
public function flatten() |
15
|
|
|
{ |
16
|
|
|
/** @var Codepoint $codepoint */ |
17
|
|
|
foreach ($this as $codepoint) { |
18
|
|
|
yield $codepoint->getValue(); |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param Codepoint $codepoint |
24
|
|
|
* @return bool |
25
|
|
|
*/ |
26
|
|
|
public function has(Codepoint $codepoint) |
27
|
|
|
{ |
28
|
|
|
foreach ($this as $check) { |
29
|
|
|
if ($codepoint->equals($check)) { |
30
|
|
|
return true; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return Range[]|Range\Collection |
39
|
|
|
*/ |
40
|
|
|
public function aggregate() |
41
|
|
|
{ |
42
|
|
|
$aggregator = new Aggregator(); |
43
|
|
|
|
44
|
|
|
$this->traverseWith(function (Codepoint $codepoint) use ($aggregator) { |
45
|
|
|
$aggregator->addCodepoint($codepoint); |
46
|
|
|
}); |
47
|
|
|
|
48
|
|
|
return $aggregator->getAggregated(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @return string |
53
|
|
|
*/ |
54
|
|
|
public function toRegexCharacterClass() |
55
|
|
|
{ |
56
|
|
|
$builder = new RegexBuilder(); |
57
|
|
|
|
58
|
|
|
$this->traverseWith(function (Codepoint $codepoint) use ($builder) { |
59
|
|
|
$builder->addCodepoint($codepoint); |
60
|
|
|
}); |
61
|
|
|
|
62
|
|
|
return $builder->getCharacterClass(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $string |
67
|
|
|
* @return static |
68
|
|
|
*/ |
69
|
|
|
public static function fromUTF8($string) |
70
|
|
|
{ |
71
|
|
|
static $encoding = 'UTF-8'; |
72
|
|
|
$codepoints = []; |
73
|
|
|
|
74
|
|
|
for ($i = 0; $i < mb_strlen($string, $encoding); $i++) { |
75
|
|
|
$character = mb_substr($string, $i, 1, $encoding); |
76
|
|
|
$codepoint = Codepoint::fromUTF8($character); |
77
|
|
|
array_push($codepoints, $codepoint); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return static::fromArray($codepoints); |
81
|
|
|
} |
82
|
|
|
} |