Skip to content

Commit

Permalink
added Strings::ord()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Mar 12, 2022
1 parent 38b8f98 commit 47c0644
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Utils/Strings.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ 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
44 changes: 44 additions & 0 deletions tests/Utils/Strings.ord().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?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(
fn() => Strings::ord("\u{D800}"),
Nette\InvalidArgumentException::class,
'Invalid UTF-8 character "\xEDA080".',
);

Assert::exception(
fn() => Strings::ord(''),
Nette\InvalidArgumentException::class,
'Invalid UTF-8 character "".',
);

Assert::exception(
fn() => Strings::ord("\xFF"),
Nette\InvalidArgumentException::class,
'Invalid UTF-8 character "\xFF".',
);

0 comments on commit 47c0644

Please sign in to comment.