Skip to content

Commit

Permalink
added Strings::ord()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 1, 2021
1 parent 6cd4758 commit a828903
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Utils/Strings.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ public static function chr(int $code): string
}


/**
* Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF).
*/
public static function ord(string $c): int
{
if (!extension_loaded('iconv')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
}
$tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c);
if (!$tmp) {
throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".');
}
return unpack('N', $tmp)[1];
}


/**
* Starts the $haystack string with the prefix $needle?
*/
Expand Down
38 changes: 38 additions & 0 deletions tests/Utils/Strings.ord().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/**
* Test: Nette\Utils\Strings::ord()
*/

declare(strict_types=1);

use Nette\Utils\Strings;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


Assert::same(0x000000, Strings::ord("\x00"));
Assert::same(0x00007F, Strings::ord("\x7F"));
Assert::same(0x000080, Strings::ord("\u{80}"));
Assert::same(0x0007FF, Strings::ord("\u{7FF}"));
Assert::same(0x000800, Strings::ord("\u{800}"));
Assert::same(0x00D7FF, Strings::ord("\u{D7FF}"));
Assert::same(0x00E000, Strings::ord("\u{E000}"));
Assert::same(0x00FFFF, Strings::ord("\u{FFFF}"));
Assert::same(0x010000, Strings::ord("\u{10000}"));
Assert::same(0x10FFFF, Strings::ord("\u{10FFFF}"));
Assert::same(0x000080, Strings::ord("\u{80}\u{80}"));

Assert::exception(function () {
Strings::ord("\u{D800}");
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "\xEDA080".');

Assert::exception(function () {
Strings::ord('');
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "".');

Assert::exception(function () {
Strings::ord("\xFF");
}, Nette\InvalidArgumentException::class, 'Invalid UTF-8 character "\xFF".');

0 comments on commit a828903

Please sign in to comment.