File tree Expand file tree Collapse file tree 2 files changed +25
-7
lines changed
Expand file tree Collapse file tree 2 files changed +25
-7
lines changed Original file line number Diff line number Diff line change 88
99trait 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}
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments