Browse Source

fix: `OrderedClassElementsFixer` - sort correctly typed constants (#8408)

Kuba Werłos 1 month ago
parent
commit
dd9402489c

+ 4 - 1
src/Fixer/ClassNotation/OrderedClassElementsFixer.php

@@ -410,7 +410,10 @@ Custom values:
 
                 if ('property' === $element['type']) {
                     $element['name'] = $tokens[$i]->getContent();
-                } elseif (\in_array($element['type'], ['use_trait', 'case', 'constant', 'method', 'magic', 'construct', 'destruct'], true)) {
+                } elseif ('constant' === $element['type']) {
+                    $equalsSignIndex = $tokens->getNextTokenOfKind($i, ['=']);
+                    $element['name'] = $tokens[$tokens->getPrevMeaningfulToken($equalsSignIndex)]->getContent();
+                } elseif (\in_array($element['type'], ['use_trait', 'case', 'method', 'magic', 'construct', 'destruct'], true)) {
                     $element['name'] = $tokens[$tokens->getNextMeaningfulToken($i)]->getContent();
                 }
 

+ 43 - 0
tests/Fixer/ClassNotation/OrderedClassElementsFixerTest.php

@@ -1634,4 +1634,47 @@ class A
             '<?php trait Foo { protected $abc = "abc"; const C1 = 1; }',
         ];
     }
+
+    /**
+     * @param _AutogeneratedInputConfiguration $configuration
+     *
+     * @dataProvider provideFix83Cases
+     *
+     * @requires PHP 8.3
+     */
+    public function testFix83(string $expected, ?string $input = null, array $configuration = []): void
+    {
+        $this->fixer->configure($configuration);
+        $this->doTest($expected, $input);
+    }
+
+    /**
+     * @return iterable<array{string, string, _AutogeneratedInputConfiguration}>
+     */
+    public static function provideFix83Cases(): iterable
+    {
+        yield [
+            <<<'PHP'
+                <?php
+                class Foo
+                {
+                    public const int A = 42;
+                    public const string B = 'bravo';
+                    public const bool C = true;
+                }
+                PHP,
+            <<<'PHP'
+                <?php
+                class Foo
+                {
+                    public const string B = 'bravo';
+                    public const bool C = true;
+                    public const int A = 42;
+                }
+                PHP,
+            [
+                'sort_algorithm' => 'alpha',
+            ],
+        ];
+    }
 }