Browse Source

PHP8.1 - New in initializers (start)

SpacePossum 3 years ago
parent
commit
6b4ded3437

+ 1 - 1
src/Fixer/Alias/EregToPregFixer.php

@@ -161,7 +161,7 @@ final class EregToPregFixer extends AbstractFixer
      */
     private function getBestDelimiter(string $pattern): string
     {
-        // try do find something that's not used
+        // try to find something that's not used
         $delimiters = [];
         foreach (self::$delimiters as $k => $d) {
             if (!str_contains($pattern, $d)) {

+ 10 - 3
src/Fixer/Basic/PsrAutoloadingFixer.php

@@ -26,6 +26,7 @@ use PhpCsFixer\Preg;
 use PhpCsFixer\StdinFileInfo;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Tokens;
+use PhpCsFixer\Tokenizer\TokensAnalyzer;
 
 /**
  * @author Jordi Boggiano <j.boggiano@seld.be>
@@ -153,6 +154,8 @@ class InvalidName {}
      */
     protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
     {
+        $tokenAnalyzer = new TokensAnalyzer($tokens);
+
         if (null !== $this->configuration['dir'] && !str_starts_with($file->getRealPath(), $this->configuration['dir'])) {
             return;
         }
@@ -172,10 +175,9 @@ class InvalidName {}
 
                 $namespaceStartIndex = $tokens->getNextMeaningfulToken($index);
                 $namespaceEndIndex = $tokens->getNextTokenOfKind($namespaceStartIndex, [';']);
-
                 $namespace = trim($tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex - 1));
             } elseif ($token->isClassy()) {
-                if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW)) {
+                if ($tokenAnalyzer->isAnonymousClass($index)) {
                     continue;
                 }
 
@@ -208,6 +210,7 @@ class InvalidName {}
 
         $configuredDir = realpath($this->configuration['dir']);
         $fileDir = \dirname($file->getRealPath());
+
         if (\strlen($configuredDir) >= \strlen($fileDir)) {
             return;
         }
@@ -230,7 +233,6 @@ class InvalidName {}
     private function calculateClassyName(\SplFileInfo $file, ?string $namespace, string $currentName): string
     {
         $name = $file->getBasename('.php');
-
         $maxNamespace = $this->calculateMaxNamespace($file, $namespace);
 
         if (null !== $this->configuration['dir']) {
@@ -241,9 +243,11 @@ class InvalidName {}
 
         foreach ($namespaceParts as $namespacePart) {
             $nameCandidate = sprintf('%s_%s', $namespacePart, $name);
+
             if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) {
                 break;
             }
+
             $name = $nameCandidate;
         }
 
@@ -254,6 +258,7 @@ class InvalidName {}
     {
         if (null === $this->configuration['dir']) {
             $root = \dirname($file->getRealPath());
+
             while ($root !== \dirname($root)) {
                 $root = \dirname($root);
             }
@@ -274,9 +279,11 @@ class InvalidName {}
             if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) {
                 break;
             }
+
             if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) {
                 break;
             }
+
             unset($namespaceAccordingToFileLocationPartsReversed[$key]);
         }
 

+ 5 - 2
src/Fixer/ClassNotation/FinalInternalClassFixer.php

@@ -27,6 +27,7 @@ use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
 use PhpCsFixer\Preg;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Tokens;
+use PhpCsFixer\Tokenizer\TokensAnalyzer;
 use Symfony\Component\OptionsResolver\Options;
 
 /**
@@ -105,8 +106,10 @@ final class FinalInternalClassFixer extends AbstractFixer implements Configurabl
      */
     protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
     {
+        $tokensAnalyzer = new TokensAnalyzer($tokens);
+
         for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
-            if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isClassCandidate($tokens, $index)) {
+            if (!$tokens[$index]->isGivenKind(T_CLASS) || $tokensAnalyzer->isAnonymousClass($index) || !$this->isClassCandidate($tokens, $index)) {
                 continue;
             }
 
@@ -182,7 +185,7 @@ final class FinalInternalClassFixer extends AbstractFixer implements Configurabl
      */
     private function isClassCandidate(Tokens $tokens, int $index): bool
     {
-        if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_ABSTRACT, T_FINAL, T_NEW])) {
+        if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_ABSTRACT, T_FINAL])) {
             return false; // ignore class; it is abstract or already final
         }
 

+ 3 - 3
src/Fixer/ClassNotation/SelfStaticAccessorFixer.php

@@ -114,14 +114,14 @@ $a = new class() {
      */
     protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
     {
-        $this->tokensAnalyzer = $tokensAnalyzer = new TokensAnalyzer($tokens);
+        $this->tokensAnalyzer = new TokensAnalyzer($tokens);
 
         $classIndex = $tokens->getNextTokenOfKind(0, [[T_CLASS]]);
 
         while (null !== $classIndex) {
             if (
-                $tokens[$tokens->getPrevMeaningfulToken($classIndex)]->isGivenKind(T_FINAL)
-                || $tokensAnalyzer->isAnonymousClass($classIndex)
+                $this->tokensAnalyzer->isAnonymousClass($classIndex)
+                || $tokens[$tokens->getPrevMeaningfulToken($classIndex)]->isGivenKind(T_FINAL)
             ) {
                 $classIndex = $this->fixClass($tokens, $classIndex);
             }

+ 18 - 21
src/Fixer/ClassUsage/DateTimeImmutableFixer.php

@@ -18,6 +18,7 @@ use PhpCsFixer\AbstractFixer;
 use PhpCsFixer\FixerDefinition\CodeSample;
 use PhpCsFixer\FixerDefinition\FixerDefinition;
 use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
+use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Tokens;
 
@@ -60,6 +61,12 @@ final class DateTimeImmutableFixer extends AbstractFixer
      */
     protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
     {
+        $functionsAnalyzer = new FunctionsAnalyzer();
+        $functionMap = [
+            'date_create' => 'date_create_immutable',
+            'date_create_from_format' => 'date_create_immutable_from_format',
+        ];
+
         $isInNamespace = false;
         $isImported = false; // e.g. use DateTime;
 
@@ -72,12 +79,15 @@ final class DateTimeImmutableFixer extends AbstractFixer
                 continue;
             }
 
-            if ($token->isGivenKind(T_USE) && $isInNamespace) {
+            if ($isInNamespace && $token->isGivenKind(T_USE)) {
                 $nextIndex = $tokens->getNextMeaningfulToken($index);
+
                 if ('datetime' !== strtolower($tokens[$nextIndex]->getContent())) {
                     continue;
                 }
+
                 $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
+
                 if ($tokens[$nextNextIndex]->equals(';')) {
                     $isImported = true;
                 }
@@ -92,6 +102,7 @@ final class DateTimeImmutableFixer extends AbstractFixer
             }
 
             $prevIndex = $tokens->getPrevMeaningfulToken($index);
+
             if ($tokens[$prevIndex]->isGivenKind(T_FUNCTION)) {
                 continue;
             }
@@ -101,10 +112,12 @@ final class DateTimeImmutableFixer extends AbstractFixer
             if ('datetime' === $lowercaseContent) {
                 $this->fixClassUsage($tokens, $index, $isInNamespace, $isImported);
                 $limit = $tokens->count(); // update limit, as fixing class usage may insert new token
-            } elseif ('date_create' === $lowercaseContent) {
-                $this->fixFunctionUsage($tokens, $index, 'date_create_immutable');
-            } elseif ('date_create_from_format' === $lowercaseContent) {
-                $this->fixFunctionUsage($tokens, $index, 'date_create_immutable_from_format');
+
+                continue;
+            }
+
+            if (isset($functionMap[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
+                $tokens[$index] = new Token([T_STRING, $functionMap[$lowercaseContent]]);
             }
         }
     }
@@ -142,20 +155,4 @@ final class DateTimeImmutableFixer extends AbstractFixer
             }
         }
     }
-
-    private function fixFunctionUsage(Tokens $tokens, int $index, string $replacement): void
-    {
-        $prevIndex = $tokens->getPrevMeaningfulToken($index);
-        if ($tokens[$prevIndex]->isGivenKind([T_DOUBLE_COLON, T_NEW]) || $tokens[$prevIndex]->isObjectOperator()) {
-            return;
-        }
-        if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
-            $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
-            if ($tokens[$prevPrevIndex]->isGivenKind([T_NEW, T_STRING])) {
-                return;
-            }
-        }
-
-        $tokens[$index] = new Token([T_STRING, $replacement]);
-    }
 }

+ 1 - 1
src/Fixer/Comment/SingleLineCommentStyleFixer.php

@@ -135,7 +135,7 @@ $c = 3;
 
             if ($this->hashEnabled && '#' === $content[0]) {
                 if (isset($content[1]) && '[' === $content[1]) {
-                    continue; // This might be attribute on PHP8, do not change
+                    continue; // This might be an attribute on PHP8, do not change
                 }
 
                 $tokens[$index] = new Token([$token->getId(), '//'.substr($content, 1)]);

+ 1 - 1
src/Fixer/Import/SingleImportPerStatementFixer.php

@@ -155,7 +155,7 @@ final class SingleImportPerStatementFixer extends AbstractFixer implements White
                     $i += 2;
                 }
 
-                if ($token->isWhitespace(" \t") || '//' !== substr($tokens[$i - 1]->getContent(), 0, 2)) {
+                if ($token->isWhitespace(" \t") || !str_starts_with($tokens[$i - 1]->getContent(), '//')) {
                     continue;
                 }
             }

+ 2 - 1
src/Fixer/Operator/ConcatSpaceFixer.php

@@ -122,7 +122,8 @@ final class ConcatSpaceFixer extends AbstractFixer implements ConfigurableFixerI
     private function fixConcatenationToNoSpace(Tokens $tokens, int $index): void
     {
         $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
-        if (!$prevNonWhitespaceToken->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT]) || '/*' === substr($prevNonWhitespaceToken->getContent(), 0, 2)) {
+
+        if (!$prevNonWhitespaceToken->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT]) || str_starts_with($prevNonWhitespaceToken->getContent(), '/*')) {
             $tokens->removeLeadingWhitespace($index, " \t");
         }
 

+ 1 - 3
src/Fixer/Operator/NewWithBracesFixer.php

@@ -101,9 +101,7 @@ final class NewWithBracesFixer extends AbstractFixer
         }
 
         for ($index = $tokens->count() - 3; $index > 0; --$index) {
-            $token = $tokens[$index];
-
-            if (!$token->isGivenKind(T_NEW)) {
+            if (!$tokens[$index]->isGivenKind(T_NEW)) {
                 continue;
             }
 

+ 4 - 1
src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php

@@ -355,18 +355,21 @@ final class MyTest extends \PHPUnit_Framework_TestCase
 
         for ($index = $endIndex; $index > $startIndex; --$index) {
             $index = $tokens->getPrevTokenOfKind($index, [[T_STRING]]);
+
             if (null === $index) {
                 return;
             }
 
             // test if "assert" something call
             $loweredContent = strtolower($tokens[$index]->getContent());
-            if ('assert' !== substr($loweredContent, 0, 6)) {
+
+            if (!str_starts_with($loweredContent, 'assert')) {
                 continue;
             }
 
             // test candidate for simple calls like: ([\]+'some fixable call'(...))
             $openBraceIndex = $tokens->getNextMeaningfulToken($index);
+
             if (!$tokens[$openBraceIndex]->equals('(')) {
                 continue;
             }

Some files were not shown because too many files changed in this diff