[core] add custom error messages for stdlib_ex, and a test

This commit is contained in:
Shish
2024-02-05 13:25:18 +00:00
parent 51afc014a2
commit 92577d355f
2 changed files with 40 additions and 5 deletions

View File

@ -5,10 +5,14 @@
* @param T|false $x * @param T|false $x
* @return T * @return T
*/ */
function false_throws(mixed $x): mixed function false_throws(mixed $x, ?callable $errorgen=null): mixed
{ {
if($x === false) { if($x === false) {
throw new \Exception("Unexpected false"); $msg = "Unexpected false";
if($errorgen) {
$msg = $errorgen();
}
throw new \Exception($msg);
} }
return $x; return $x;
} }
@ -18,10 +22,14 @@ function false_throws(mixed $x): mixed
* @param T|null $x * @param T|null $x
* @return T * @return T
*/ */
function null_throws(mixed $x): mixed function null_throws(mixed $x, ?callable $errorgen=null): mixed
{ {
if($x === null) { if($x === null) {
throw new \Exception("Unexpected null"); $msg = "Unexpected null";
if($errorgen) {
$msg = $errorgen();
}
throw new \Exception($msg);
} }
return $x; return $x;
} }
@ -31,7 +39,7 @@ function null_throws(mixed $x): mixed
*/ */
function json_encode_ex(mixed $value, int|null $flags = 0, int $depth = 512): string function json_encode_ex(mixed $value, int|null $flags = 0, int $depth = 512): string
{ {
return false_throws(json_encode($value, $flags, $depth)); return false_throws(json_encode($value, $flags, $depth), "json_last_error_msg");
} }
function strtotime_ex(string $time, int|null $now = null): int function strtotime_ex(string $time, int|null $now = null): int

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Shimmie2;
class StdLibExTest extends ShimmiePHPUnitTestCase
{
public function testJsonEncodeOk(): void
{
$this->assertEquals(
'{"a":1,"b":2,"c":3,"d":4,"e":5}',
json_encode_ex(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5])
);
}
public function testJsonEncodeError(): void
{
$e = $this->assertException(\Exception::class, function() {
json_encode_ex("\xB1\x31");
});
$this->assertEquals(
"Malformed UTF-8 characters, possibly incorrectly encoded",
$e->getMessage()
);
}
}