Skip to content

Commit 278e5c2

Browse files
committed
Improve error handling + test the RuleType/TokenType casting better
1 parent 4bb82b6 commit 278e5c2

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

php/src/Parser/TokenRuleTypesCastTrait.php

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,26 @@
88

99
trait TokenRuleTypesCastTrait
1010
{
11-
public static function cast(TokenType $tokenType): RuleType
11+
public static function cast(TokenType $tokenType): self
1212
{
1313
$tokenName = $tokenType->name;
1414

1515
if ($tokenName != TokenType::None->name) {
1616
$tokenName = '_' . $tokenName;
1717
}
1818

19-
$newValueString = RuleType::class . '::' . $tokenName;
19+
// PHP does not currently support MyClass::$myConstant as a syntax
20+
// so the `constant()` function has to be used instead, by constructing
21+
// a string that refers to the enum case name
22+
$newValueString = self::class . '::' . $tokenName;
2023

2124
if (!defined($newValueString)) {
22-
throw new LogicException('Could not create RuleType from TokenType::' . $tokenName);
25+
throw new LogicException('Could not create RuleType from TokenType::' . $tokenType->name);
2326
}
2427

28+
/** @var self $ruleType */
2529
$ruleType = constant($newValueString);
2630

27-
if (!$ruleType instanceof RuleType) {
28-
throw new LogicException('Could not create RuleType from TokenType::' . $tokenName);
29-
}
30-
3131
return $ruleType;
3232
}
3333
}

php/tests/unit/Parser/RuleTypeTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ public function testItCanCastFromTokens(TokenType $tokenType): void
1515
self::assertInstanceOf(RuleType::class, RuleType::cast($tokenType));
1616
}
1717

18+
public function testItCanFailIfEnumDoesNotHaveMatchingValue(): void
19+
{
20+
$this->expectException(\LogicException::class);
21+
$this->expectExceptionMessage('Could not create RuleType from TokenType::Comment');
22+
23+
TooShortEnum::cast(TokenType::Comment);
24+
}
25+
1826
/**
1927
* @return Generator<string,array{0:TokenType}>
2028
*/
@@ -25,3 +33,13 @@ public function tokenCaseProvider(): Generator
2533
}
2634
}
2735
}
36+
37+
/**
38+
* An enum fixture that deliberately doesn't have cases matching TokenType
39+
*/
40+
enum TooShortEnum
41+
{
42+
use TokenRuleTypesCastTrait;
43+
44+
case Foo;
45+
}

0 commit comments

Comments
 (0)