Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Normalize enum value to ClassConstFetch #940

Open
wants to merge 2 commits into
base: 4.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/PhpParser/BuilderHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\NullableType;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
Expand Down Expand Up @@ -215,7 +216,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 +270,10 @@ public static function normalizeValue($value) : Expr {
return new Expr\Array_($items);
}

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

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

Expand Down
19 changes: 19 additions & 0 deletions test/PhpParser/BuilderHelpersPHP81Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php declare(strict_types=1);

namespace PhpParser;

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

class BuilderHelpersPHP81Test extends \PHPUnit\Framework\TestCase
{
public function testNormalizeValueEnum() {
if (\PHP_VERSION_ID <= 80100) {
$this->markTestSkipped('Enums are supported since PHP 8.1');
}

include __DIR__ . '/../code/Suit.php';
Comment on lines +12 to +16
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nikic Is this the correct way to handle this?


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

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