Browse Source

bug: TypeColonTransformer - fix for backed enum types (#6494)

TypeColonTransformer - fix for backed enum types
Jeremiasz Major 2 years ago
parent
commit
c87361818e

+ 9 - 0
src/Tokenizer/Transformer/TypeColonTransformer.php

@@ -57,6 +57,15 @@ final class TypeColonTransformer extends AbstractTransformer
 
         $endIndex = $tokens->getPrevMeaningfulToken($index);
 
+        if (
+            \defined('T_ENUM') // @TODO: drop condition when PHP 8.1+ is required
+            && $tokens[$tokens->getPrevMeaningfulToken($endIndex)]->isGivenKind(T_ENUM)
+        ) {
+            $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']);
+
+            return;
+        }
+
         if (!$tokens[$endIndex]->equals(')')) {
             return;
         }

+ 26 - 0
tests/Fixer/Operator/TernaryOperatorSpacesFixerTest.php

@@ -225,4 +225,30 @@ class Foo
             ],
         ];
     }
+
+    /**
+     * @dataProvider provideFix81Cases
+     * @requires PHP 8.1
+     */
+    public function testFix81(string $expected, ?string $input = null): void
+    {
+        $this->doTest($expected, $input);
+    }
+
+    public function provideFix81Cases(): iterable
+    {
+        yield [
+            <<<'PHP'
+                <?php
+
+                enum TaskType: int
+                {
+                    public function foo(bool $value): string
+                    {
+                        return $value ? 'foo' : 'bar';
+                    }
+                }
+                PHP,
+        ];
+    }
 }

+ 33 - 0
tests/Tokenizer/Transformer/TypeColonTransformerTest.php

@@ -100,4 +100,37 @@ final class TypeColonTransformerTest extends AbstractTransformerTestCase
             ],
         ];
     }
+
+    /**
+     * @dataProvider provideProcess81Cases
+     * @requires PHP 8.1
+     */
+    public function testProcess81(string $source, array $expectedTokens = []): void
+    {
+        $this->doTest(
+            $source,
+            $expectedTokens,
+            [
+                CT::T_TYPE_COLON,
+            ]
+        );
+    }
+
+    public function provideProcess81Cases(): array
+    {
+        return [
+            [
+                '<?php enum Foo: int {}',
+                [
+                    4 => CT::T_TYPE_COLON,
+                ],
+            ],
+            [
+                '<?php enum Foo /** */ : int {}',
+                [
+                    7 => CT::T_TYPE_COLON,
+                ],
+            ],
+        ];
+    }
 }