Skip to content

Commit

Permalink
Normalize enum value to ClassConstFetch
Browse files Browse the repository at this point in the history
Fixes nikic#930
  • Loading branch information
ruudk committed Aug 15, 2023
1 parent a6303e5 commit f7db927
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/PhpParser/BuilderHelpers.php
Expand Up @@ -215,7 +215,7 @@ public static function normalizeType($type) {
* Normalizes a value: Converts nulls, booleans, integers,
* floats, strings and arrays into their respective nodes
*
* @param Node\Expr|bool|null|int|float|string|array $value The value to normalize
* @param Node\Expr|bool|null|int|float|string|array|\UnitEnum $value The value to normalize
*
* @return Expr The normalized value
*/
Expand Down Expand Up @@ -269,6 +269,10 @@ public static function normalizeValue($value) : Expr {
return new Expr\Array_($items);
}

if ($value instanceof \UnitEnum) {
return new Expr\ClassConstFetch(new Name(\get_class($value)), $value->name);
}

throw new \LogicException('Invalid value');
}

Expand Down
18 changes: 18 additions & 0 deletions test/PhpParser/BuilderHelpersPHP81Test.php
@@ -0,0 +1,18 @@
<?php declare(strict_types=1);

namespace PhpParser;

use PhpParser\Node\Expr;
use PhpParser\Node\Name;

/**
* @requires php 8.1
*/
class BuilderHelpersPHP81Test extends \PHPUnit\Framework\TestCase
{
public function testNormalizeValueEnum() {
include __DIR__ . '/../code/Suit.php';

$this->assertEquals(new Expr\ClassConstFetch(new Name(\Suit::class), 'Hearts'), BuilderHelpers::normalizeValue(\Suit::Hearts));
}
}
9 changes: 9 additions & 0 deletions test/code/Suit.php
@@ -0,0 +1,9 @@
<?php

enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

0 comments on commit f7db927

Please sign in to comment.