Skip to content

Commit 3683686

Browse files
committed
added Strings::ord()
1 parent 63f70f7 commit 3683686

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Utils/Strings.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,22 @@ public static function chr(int $code): string
5757
}
5858

5959

60+
/**
61+
* Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF).
62+
*/
63+
public static function ord(string $c): int
64+
{
65+
if (!extension_loaded('iconv')) {
66+
throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
67+
}
68+
$tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c);
69+
if (!$tmp) {
70+
throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".');
71+
}
72+
return unpack('N', $tmp)[1];
73+
}
74+
75+
6076
/**
6177
* Starts the $haystack string with the prefix $needle?
6278
*/

tests/Utils/Strings.ord().phpt

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Strings::ord()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Strings;
10+
use Tester\Assert;
11+
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
Assert::same(0x000000, Strings::ord("\x00"));
17+
Assert::same(0x00007F, Strings::ord("\x7F"));
18+
Assert::same(0x000080, Strings::ord("\u{80}"));
19+
Assert::same(0x0007FF, Strings::ord("\u{7FF}"));
20+
Assert::same(0x000800, Strings::ord("\u{800}"));
21+
Assert::same(0x00D7FF, Strings::ord("\u{D7FF}"));
22+
Assert::same(0x00E000, Strings::ord("\u{E000}"));
23+
Assert::same(0x00FFFF, Strings::ord("\u{FFFF}"));
24+
Assert::same(0x010000, Strings::ord("\u{10000}"));
25+
Assert::same(0x10FFFF, Strings::ord("\u{10FFFF}"));
26+
Assert::same(0x000080, Strings::ord("\u{80}\u{80}"));
27+
28+
Assert::exception(function () {
29+
Strings::ord("\u{D800}");
30+
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "\xEDA080".');
31+
32+
Assert::exception(function () {
33+
Strings::ord('');
34+
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "".');
35+
36+
Assert::exception(function () {
37+
Strings::ord("\xFF");
38+
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "\xFF".');

0 commit comments

Comments
 (0)