Skip to content

Commit 5ee5c38

Browse files
committed
added Reflection::getPropertyType() (for PHP 7.4)
1 parent fd81195 commit 5ee5c38

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Utils/Reflection.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,14 @@ public static function getParameterType(\ReflectionParameter $param): ?string
4747
}
4848

4949

50+
public static function getPropertyType(\ReflectionProperty $prop): ?string
51+
{
52+
return PHP_VERSION_ID >= 70400 && $prop->hasType()
53+
? self::normalizeType($prop->getType()->getName(), $prop)
54+
: null;
55+
}
56+
57+
5058
private static function normalizeType(string $type, $reflection): string
5159
{
5260
$lower = strtolower($type);
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Reflection::getPropertyType
5+
* @phpversion 7.4
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
use Nette\Utils\Reflection;
11+
use Test\B; // for testing purposes
12+
use Tester\Assert;
13+
14+
15+
require __DIR__ . '/../bootstrap.php';
16+
17+
18+
class A
19+
{
20+
public Undeclared $undeclared;
21+
public B $b;
22+
public array $array;
23+
public self $self;
24+
public $none;
25+
public ?B $nullable;
26+
}
27+
28+
class AExt extends A
29+
{
30+
public parent $parent;
31+
}
32+
33+
$class = new ReflectionClass('A');
34+
$props = $class->getProperties();
35+
36+
Assert::same('Undeclared', Reflection::getPropertyType($props[0]));
37+
Assert::same('Test\B', Reflection::getPropertyType($props[1]));
38+
Assert::same('array', Reflection::getPropertyType($props[2]));
39+
Assert::same('A', Reflection::getPropertyType($props[3]));
40+
Assert::null(Reflection::getPropertyType($props[4]));
41+
Assert::same('Test\B', Reflection::getPropertyType($props[5]));
42+
43+
$class = new ReflectionClass('AExt');
44+
$props = $class->getProperties();
45+
46+
Assert::same('A', Reflection::getPropertyType($props[0]));

0 commit comments

Comments
 (0)