Skip to content

Commit 4e0bcad

Browse files
committed
Support for cast in constant expressions
1 parent 3a971f3 commit 4e0bcad

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/NodeCompiler/CompileNodeToValue.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,30 @@ public function __invoke(Node $node, CompilerContext $context): CompiledValue
140140
return $this->getEnumPropertyValue($node, $context);
141141
}
142142

143+
if ($node instanceof Node\Expr\Cast\Int_) {
144+
return (int) $this($node->expr, $context)->value;
145+
}
146+
147+
if ($node instanceof Node\Expr\Cast\Double) {
148+
return (float) $this($node->expr, $context)->value;
149+
}
150+
151+
if ($node instanceof Node\Expr\Cast\Bool_) {
152+
return (bool) $this($node->expr, $context)->value;
153+
}
154+
155+
if ($node instanceof Node\Expr\Cast\String_) {
156+
return (string) $this($node->expr, $context)->value;
157+
}
158+
159+
if ($node instanceof Node\Expr\Cast\Array_) {
160+
return (array) $this($node->expr, $context)->value;
161+
}
162+
163+
if ($node instanceof Node\Expr\Cast\Object_) {
164+
return (object) $this($node->expr, $context)->value;
165+
}
166+
143167
throw Exception\UnableToCompileNode::forUnRecognizedExpressionInContext($node, $context);
144168
});
145169

test/unit/NodeCompiler/CompileNodeToValueTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
use Roave\BetterReflectionTest\Fixture\MagicConstantsClass;
3737
use Roave\BetterReflectionTest\Fixture\MagicConstantsInPropertyHooks;
3838
use Roave\BetterReflectionTest\Fixture\MagicConstantsTrait;
39+
use stdClass;
3940

4041
use function assert;
4142
use function define;
@@ -200,6 +201,11 @@ public static function nodeProvider(): array
200201
['4 <=> 1', 1],
201202
['1 <=> 1', 0],
202203
['5 ?? 4', 5],
204+
['(int) true', 1],
205+
['(float) true', 1.0],
206+
['(string) true', '1'],
207+
['(bool) 1', true],
208+
['(array) 1', [1]],
203209
];
204210
}
205211

@@ -1127,6 +1133,15 @@ public function testMagicConstantsInPropertyHooks(string $propertyName, mixed $e
11271133
self::assertSame($expectedValue, $getHookParameterAttribute->getArguments()[0]);
11281134
}
11291135

1136+
public function testObjectCast(): void
1137+
{
1138+
$node = $this->parseCode('(object) []');
1139+
1140+
$compiledValue = (new CompileNodeToValue())->__invoke($node, $this->getDummyContext());
1141+
1142+
self::assertInstanceOf(stdClass::class, $compiledValue->value);
1143+
}
1144+
11301145
/** @return non-empty-string */
11311146
private static function realPath(string $path): string
11321147
{

0 commit comments

Comments
 (0)