Skip to content

Commit f4f4772

Browse files
committed
add TypeAssertion
1 parent e232bd6 commit f4f4772

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/TypeAssertion.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Utilitte\Php;
4+
5+
use Utilitte\Php\Exception\TypeAssertionException;
6+
7+
final class TypeAssertion
8+
{
9+
10+
private const BUILTIN = [
11+
'bool' => true,
12+
'int' => true,
13+
'float' => true,
14+
'string' => true,
15+
'array' => true,
16+
'object' => true,
17+
'resource' => true,
18+
'null' => true,
19+
];
20+
21+
private const BUILTIN_MAPPING = [
22+
'integer' => 'int',
23+
'boolean' => 'bool',
24+
'double' => 'float',
25+
'NULL' => 'null',
26+
];
27+
28+
/**
29+
* @param mixed $variable
30+
*/
31+
public static function assertType($variable, string $expectType): void
32+
{
33+
$type = gettype($variable);
34+
$type = self::BUILTIN_MAPPING[$type] ?? $type;
35+
36+
if ($type === 'unknown type') {
37+
throw new TypeAssertionException(
38+
sprintf('Variable is type of "%s", expected "%s"', 'unknown type', $expectType)
39+
);
40+
}
41+
42+
if ($type === 'resource (closed)') {
43+
$type = 'resource';
44+
}
45+
46+
if (!isset(self::BUILTIN[$expectType])) {
47+
if ($variable instanceof $expectType) {
48+
return;
49+
}
50+
} elseif ($type === $expectType) {
51+
return;
52+
}
53+
54+
throw new TypeAssertionException(
55+
sprintf('Variable is type of "%s", expected "%s"', self::variableToType($variable, $type), $expectType)
56+
);
57+
}
58+
59+
/**
60+
* @param mixed $variable
61+
*/
62+
private static function variableToType($variable, string $type): string
63+
{
64+
return $type === 'object' ? get_class($variable) : $type;
65+
}
66+
67+
}

tests/cases/typeassertion.phpt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php declare(strict_types = 1);
2+
3+
use Tester\Assert;
4+
use Utilitte\Php\Exception\TypeAssertionException;
5+
use Utilitte\Php\TypeAssertion;
6+
7+
require __DIR__ . '/../bootstrap.php';
8+
9+
Assert::exception(fn () => TypeAssertion::assertType('string', 'int'), TypeAssertionException::class);
10+
Assert::exception(fn () => TypeAssertion::assertType(new stdClass(), 'int'), TypeAssertionException::class);
11+
Assert::exception(fn () => TypeAssertion::assertType('string', 'stdClass'), TypeAssertionException::class);
12+
13+
TypeAssertion::assertType(15, 'int');
14+
TypeAssertion::assertType(new stdClass(), stdClass::class);

0 commit comments

Comments
 (0)