#!/usr/bin/env php * Dariusz Rumiński * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED); } if (defined('HHVM_VERSION_ID')) { fwrite(STDERR, "HHVM is not supported.\n"); if (getenv('PHP_CS_FIXER_IGNORE_ENV')) { fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); } else { exit(1); } } elseif (!defined('PHP_VERSION_ID') || \PHP_VERSION_ID < 50600 || \PHP_VERSION_ID >= 70500) { fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 7.4.*.\n"); if (getenv('PHP_CS_FIXER_IGNORE_ENV')) { fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); } else { exit(1); } } foreach (['json', 'tokenizer'] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, sprintf("PHP extension ext-%s is missing from your system. Install or enable it.\n", $extension)); if (getenv('PHP_CS_FIXER_IGNORE_ENV')) { fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); } else { exit(1); } } } unset($extension); set_error_handler(static function ($severity, $message, $file, $line) { if ($severity & error_reporting()) { throw new ErrorException($message, 0, $severity, $file, $line); } }); $require = true; if (class_exists('Phar')) { // Maybe this file is used as phar-stub? Let's try! try { Phar::mapPhar('php-cs-fixer.phar'); require_once 'phar://php-cs-fixer.phar/vendor/autoload.php'; $require = false; } catch (PharException $e) { } } if ($require) { // OK, it's not, let give Composer autoloader a try! $possibleFiles = [__DIR__.'/../../autoload.php', __DIR__.'/../autoload.php', __DIR__.'/vendor/autoload.php']; $file = null; foreach ($possibleFiles as $possibleFile) { if (file_exists($possibleFile)) { $file = $possibleFile; break; } } if (null === $file) { throw new RuntimeException('Unable to locate autoload.php file.'); } require_once $file; unset($possibleFiles, $possibleFile, $file); } unset($require); use Composer\XdebugHandler\XdebugHandler; use PhpCsFixer\Console\Application; // Restart if xdebug is loaded, unless the environment variable PHP_CS_FIXER_ALLOW_XDEBUG is set. $xdebug = new XdebugHandler('PHP_CS_FIXER', '--ansi'); $xdebug->check(); unset($xdebug); $application = new Application(); $application->run(); __HALT_COMPILER(); ?> 7'src/AbstractDoctrineAnnotationFixer.php ~_ 3.'src/FixerDefinition/FixerDefinition.php~_z=:src/FixerDefinition/VersionSpecificCodeSampleInterface.php~_l1src/FixerDefinition/VersionSpecificCodeSample.php~_$NW0src/FixerDefinition/FixerDefinitionInterface.phpb~_b4/"src/FixerDefinition/CodeSample.php~_M +src/FixerDefinition/CodeSampleInterface.php~_4/5src/FixerDefinition/VersionSpecificationInterface.php~_ݬ,src/FixerDefinition/VersionSpecification.phpm~_m0E 7src/FixerDefinition/FileSpecificCodeSampleInterface.php~_vO.src/FixerDefinition/FileSpecificCodeSample.phph~_huϋsrc/Report/GitlabReporter.php~_nۛsrc/Report/JsonReporter.php~_ (ʴsrc/Report/ReporterFactory.php~_Mg.src/Report/ReportSummary.php~_)nU!src/Report/CheckstyleReporter.php~_Csrc/Report/XmlReporter.phpI ~_I kѴsrc/Report/TextReporter.phpd~_dAIմsrc/Report/JunitReporter.php ~_ !s src/Report/ReporterInterface.php~_!src/Doctrine/Annotation/Token.php~_y7"src/Doctrine/Annotation/Tokens.php~_yːsrc/FixerFileProcessedEvent.php~_f src/Preg.php~_8src/FixerNameValidator.php~_R,src/Documentation/DocumentationGenerator.phpd/~_d/osrc/Console/Application.php ~_ wL src/Console/WarningsDetector.php~_/-src/Console/Output/ProcessOutputInterface.php~~_~Ճ$src/Console/Output/ProcessOutput.php ~_ Y!src/Console/Output/NullOutput.php~_~|U"src/Console/Output/ErrorOutput.php ~_ y=4%src/Console/ConfigurationResolver.phpnE~_nEW)src/Console/Command/SelfUpdateCommand.php~_0},src/Console/Command/DocumentationCommand.php ~_ :k#src/Console/Command/HelpCommand.php$F~_$F;"src/Console/Command/FixCommand.php~_36src/Console/Command/FixCommandExitStatusCalculator.php;~_;#5src/Console/Command/DescribeNameNotFoundException.php~_'src/Console/Command/DescribeCommand.phpz)~_z)ݴ5src/Console/SelfUpdate/NewVersionCheckerInterface.php~_,Kl0src/Console/SelfUpdate/GithubClientInterface.php~_]δ,src/Console/SelfUpdate/NewVersionChecker.phpy~_yI'src/Console/SelfUpdate/GithubClient.php~_99⌴src/AbstractProxyFixer.php3~_3nmsrc/RuleSet.phpb~_bGsrc/FixerFactory.php~_u4src/PharChecker.php~_C"}Ŵ)src/Runner/FileCachingLintingIterator.php~_ev src/Runner/Runner.php~_+zUA"src/Runner/FileLintingIterator.php>~_>9!src/Runner/FileFilterIterator.phpL~_Lsrc/RuleSetInterface.phpw~_wLfsrc/Linter/ProcessLinter.php] ~_] TF#src/Linter/ProcessLintingResult.phpt~_t^%src/Linter/LintingResultInterface.phps~_sO:Nsrc/Linter/LintingException.phpg~_gK*src/Linter/ProcessLinterProcessBuilder.phpR~_RCsrc/Linter/TokenizerLinter.php~_gh)src/Linter/UnavailableLinterException.phps~_sGɴsrc/Linter/Linter.php8~_8Xϴ%src/Linter/TokenizerLintingResult.phpF~_Fo6src/Linter/CachingLinter.php~_lnsrc/Linter/LinterInterface.php~_/Xƴ"src/AbstractNoUselessElseFixer.phpW ~_W )&Msrc/DocBlock/DocBlock.php ~_ guxsrc/DocBlock/TagComparator.phpo~_oZc(src/DocBlock/Line.php:~_:src/DocBlock/Tag.php~_!src/DocBlock/ShortDescription.php~_㖴src/DocBlock/Annotation.phpS~_S'w)src/AbstractLinesBeforeNamespaceFixer.phpA~_AyKM=src/FixerConfiguration/FixerConfigurationResolverRootless.php!~_!L90src/FixerConfiguration/DeprecatedFixerOption.php~_I&src/FixerConfiguration/FixerOption.php~_J--src/FixerConfiguration/FixerOptionBuilder.php:~_:=.>src/FixerConfiguration/FixerConfigurationResolverInterface.php~_#/src/FixerConfiguration/FixerOptionInterface.php\~_\j,5src/FixerConfiguration/FixerConfigurationResolver.php~_m$4src/FixerConfiguration/AliasedFixerOptionBuilder.php~_*-src/FixerConfiguration/AllowedValueSubset.php~_89src/FixerConfiguration/DeprecatedFixerOptionInterface.php~_$8src/FixerConfiguration/InvalidOptionsForEnvException.php~_R-src/FixerConfiguration/AliasedFixerOption.php~_y#src/AbstractPsrAutoloadingFixer.php!~_!$ij:src/Differ/NullDiffer.php~_Dsrc/Differ/UnifiedDiffer.php~_/1src/Differ/FullDiffer.php~_Am&src/Differ/SebastianBergmannDiffer.php=~_=q#src/Differ/DiffConsoleFormatter.php~_+src/Differ/SebastianBergmannShortDiffer.phpb~_bZ!5src/Differ/DifferInterface.php|~_|hBsrc/Event/Event.php~_mݴsrc/ToolInfoInterface.phpB~_B-Wsrc/ConfigInterface.phpe~_e**=src/PharCheckerInterface.php~_ѝsrc/ToolInfo.php~_| src/AbstractAlignFixerHelper.php~_:usrc/Finder.php~_+8src/WordMatcher.php~_xsrc/AbstractFopenFlagFixer.php~_'aдsrc/StdinFileInfo.php#~_#`)Dsrc/Error/ErrorsManager.php~_錴src/Error/Error.php0~_0|شsrc/FileRemoval.phpb~_bTsrc/Config.php0 ~_0  src/AbstractPhpdocTypesFixer.php~_-src/WhitespacesFixerConfig.php~_B&src/AbstractFunctionReferenceFixer.php~_H2src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php~_ ^E2src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.phpY ~_Y nA7src/Fixer/Whitespace/MethodChainingIndentationFixer.phpH~_HY2src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php~_Fi-src/Fixer/Whitespace/IndentationTypeFixer.php ~_ (`W6src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php~_*7src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php/~_/$5src/Fixer/Whitespace/CompactNullableTypehintFixer.php~_ig::src/Fixer/Whitespace/NoExtraConsecutiveBlankLinesFixer.php;~_;Sд/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php!~_!N;(src/Fixer/Whitespace/LineEndingFixer.php~_ 5src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php~_tδ0src/Fixer/Whitespace/HeredocIndentationFixer.phpT ~_T ț9.src/Fixer/Whitespace/ArrayIndentationFixer.phph~_ha%src/Fixer/Strict/StrictParamFixer.php ~_ d‹*src/Fixer/Strict/StrictComparisonFixer.phpt~_tc,src/Fixer/Strict/DeclareStrictTypesFixer.phpw ~_w Rw>src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.phpW#~_W#eGsrc/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php~_mE/Csrc/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php%~_%w>src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php ~_ G:s#src/Fixer/DefinedFixerInterface.php~_ܴ/src/Fixer/Import/GlobalNamespaceImportFixer.php=~_=)src/Fixer/Import/NoUnusedImportsFixer.php~_R93src/Fixer/Import/FullyQualifiedStrictTypesFixer.php! ~_! .src/Fixer/Import/NoLeadingImportSlashFixer.php~~_~02ۯ2src/Fixer/Import/SingleImportPerStatementFixer.phpq~_qÂi(src/Fixer/Import/OrderedImportsFixer.php)~_).ׅ0src/Fixer/Import/SingleLineAfterImportsFixer.phpJ ~_J K[}&src/Fixer/PhpTag/NoClosingTagFixer.php~_ +2src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php~_{2src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php<~_<(src/Fixer/PhpTag/NoShortEchoTagFixer.php.~_.їI(src/Fixer/PhpTag/FullOpeningTagFixer.phpL~_LE*src/Fixer/ListNotation/ListSyntaxFixer.php ~_ #Χ6src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php ~_ 47src/Fixer/ReturnNotation/BlankLineBeforeReturnFixer.php~_Gї2src/Fixer/ReturnNotation/ReturnAssignmentFixer.phpa~_a31src/Fixer/ReturnNotation/NoUselessReturnFixer.phpp~_pR|х-src/Fixer/Comment/HashToSlashCommentFixer.php~_MZ`)src/Fixer/Comment/NoEmptyCommentFixer.php" ~_" h9src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php~_Q8src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php~_Ś*src/Fixer/Comment/CommentToPhpdocFixer.phpk~_kEP1src/Fixer/Comment/SingleLineCommentStyleFixer.php ~_ k8(src/Fixer/Comment/HeaderCommentFixer.php'~_'h+3src/Fixer/ConfigurationDefinitionFixerInterface.php~_M㵴#src/Fixer/Alias/EregToPregFixer.php ~_ ^+src/Fixer/Alias/RandomApiMigrationFixer.php~_)3)src/Fixer/Alias/NoAliasFunctionsFixer.php~_+g)src/Fixer/Alias/NoMixedEchoPrintFixer.php ~_ J&src/Fixer/Alias/SetTypeToCastFixer.php~_,src/Fixer/Alias/PowToExponentiationFixer.php~_ 'src/Fixer/Alias/MbStrFunctionsFixer.php ~_ a,src/Fixer/Alias/BacktickToShellExecFixer.php. ~_. F=&src/Fixer/PhpUnit/PhpUnitMockFixer.phpN ~_N +,src/Fixer/PhpUnit/PhpUnitNamespacedFixer.phpd~_dZI35src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php?~_?^V(<src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php~_0src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php&~_&7J;src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php]0~_]0v9src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.phpg~_gtb/src/Fixer/PhpUnit/PhpUnitOrderedCoversFixer.phpO~_OK;+src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php~_[LZ9src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.phpi~_iF>9e.src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.phpr~_r`5*src/Fixer/PhpUnit/PhpUnitTargetVersion.php~_7+src/Fixer/PhpUnit/PhpUnitConstructFixer.phpr~_r᮸-src/Fixer/PhpUnit/PhpUnitExpectationFixer.php~_占9src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php] ~_] WmԴ0src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php!~_!%T%0src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php'~_'~](src/Fixer/PhpUnit/PhpUnitStrictFixer.php ~_ 0/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php~_Uesrc/Fixer/FixerInterface.php~_eus`(src/Fixer/ConfigurableFixerInterface.php~_:src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php> ~_> O+src/Fixer/LanguageConstruct/IsNullFixer.php~_pN7src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.phpi~_ixT´6src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.phpE~_E;7=src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php~_Z#5src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php ~_ t'7src/Fixer/LanguageConstruct/FunctionToConstantFixer.php~_G=src/Fixer/LanguageConstruct/SilencedDeprecationErrorFixer.php~_Q<=src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php ~_ jދ=src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php ~_ c0src/Fixer/LanguageConstruct/DirConstantFixer.php4 ~_4 1/@src/Fixer/Basic/Psr4Fixer.php*~_*Oʹ.src/Fixer/Basic/NonPrintableCharacterFixer.php~__'src/Fixer/Basic/Psr0Fixer.php~_̙Msrc/Fixer/Basic/BracesFixer.phpP`~_P`'ˠe!src/Fixer/Basic/EncodingFixer.php;~_;xAШ0src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php ~_ UJ5-src/Fixer/Semicolon/NoEmptyStatementFixer.php ~_ MCsrc/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php,~_,aܴ6src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php~__kBsrc/Fixer/Semicolon/NoMultilineWhitespaceBeforeSemicolonsFixer.php~_.@src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php.~_.3),src/Fixer/WhitespacesAwareFixerInterface.php~_gs&src/Fixer/DeprecatedFixerInterface.php~_=rT<src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php~_Asrc/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php~_$쳴4src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php~_$ݓ0src/Fixer/ArrayNotation/TrimArraySpacesFixer.php~_5>src/Fixer/ArrayNotation/TrailingCommaInMultilineArrayFixer.php ~_ 3{-?src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php ~_ N,src/Fixer/ArrayNotation/ArraySyntaxFixer.phpV ~_V ؆)Gsrc/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php~_m;,src/Fixer/AbstractIncrementOperatorFixer.php~_0<src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php~_-"src/Fixer/AbstractPhpUnitFixer.phpC~_C63src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php~_*Ց$src/Fixer/Phpdoc/PhpdocTrimFixer.phpo~_o*src/Fixer/Phpdoc/PhpdocSeparationFixer.php] ~_] tj1src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php*~_*|޴)src/Fixer/Phpdoc/PhpdocInlineTagFixer.phpk~_ky%src/Fixer/Phpdoc/PhpdocOrderFixer.php3 ~_3 8`'src/Fixer/Phpdoc/NoEmptyPhpdocFixer.phpu~_u>pô)src/Fixer/Phpdoc/PhpdocNoPackageFixer.php~_9*src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php~_.Ir9src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php~_P 'src/Fixer/Phpdoc/PhpdocSummaryFixer.php3~_3}x%src/Fixer/Phpdoc/PhpdocTypesFixer.php~_*src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.phpX ~_X mC&src/Fixer/Phpdoc/PhpdocIndentFixer.php/~_/1,]^%src/Fixer/Phpdoc/PhpdocAlignFixer.php~_z!:1src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php~_(src/Fixer/Phpdoc/PhpdocLineSpanFixer.php ~_ 'Ĵ4src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.phpv~_v7&src/Fixer/Phpdoc/PhpdocScalarFixer.php~_7ɴ7src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.phpB~_B@(src/Fixer/Phpdoc/PhpdocNoAccessFixer.php~_ lH-src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php~_Xë)src/Fixer/Phpdoc/PhpdocToCommentFixer.php%~_%3src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php ~_ %e/src/Fixer/Phpdoc/AlignMultilineCommentFixer.phpI ~_I O4src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php ~_ 9src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php~_].src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.phpb ~_b DLBsrc/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php ~_ r^Q,src/Fixer/Operator/LogicalOperatorsFixer.phpQ~_Qh'src/Fixer/Operator/ConcatSpaceFixer.php ~_ <%w0src/Fixer/Operator/NotOperatorWithSpaceFixer.php,~_,GƦ)src/Fixer/Operator/NewWithBracesFixer.php ~_ b˴/src/Fixer/Operator/UnaryOperatorSpacesFixer.php~_0src/Fixer/Operator/StandardizeIncrementFixer.php~_Ĵ1src/Fixer/Operator/TernaryOperatorSpacesFixer.php~_q.-src/Fixer/Operator/AlignEqualsFixerHelper.php~_4IUR*src/Fixer/Operator/IncrementStyleFixer.php ~_ ˴9src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php~_}0src/Fixer/Operator/StandardizeNotEqualsFixer.php5~_5GΫ3src/Fixer/Operator/TernaryToNullCoalescingFixer.php*~_*oPN#0src/Fixer/Operator/BinaryOperatorSpacesFixer.phpfC~_fCK;;src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php~_t˴2src/Fixer/Operator/AlignDoubleArrowFixerHelper.phpg ~_g L=(src/Fixer/Operator/PreIncrementFixer.php~_-src/Fixer/ClassNotation/SelfAccessorFixer.php~_1Ҵ6src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php ~_ .2src/Fixer/ClassNotation/OrderedInterfacesFixer.php~_363src/Fixer/ClassNotation/ProtectedToPrivateFixer.phpi~_isj_3src/Fixer/ClassNotation/VisibilityRequiredFixer.php~_ΰ"1src/Fixer/ClassNotation/MethodSeparationFixer.php~_Qx3src/Fixer/ClassNotation/SelfStaticAccessorFixer.php ~_ >>src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php~_ δ5src/Fixer/ClassNotation/OrderedClassElementsFixer.php=&~_=&c{)0src/Fixer/ClassNotation/ClassDefinitionFixer.php)~_)f2src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php~_Ty ?src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php~_Y?t=src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php~_nʹ+src/Fixer/ClassNotation/FinalClassFixer.phpU~_UEh:src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php ~_ *"2src/Fixer/ClassNotation/FinalStaticAccessFixer.phpc ~_c vX>src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php~_`k3src/Fixer/ClassNotation/FinalInternalClassFixer.php ~_ >Bsrc/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php ~_ 2/src/Fixer/ClassUsage/DateTimeImmutableFixer.php ~_ x-0src/Fixer/StringNotation/NoBinaryStringFixer.php~_9t?src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php~_2src/Fixer/StringNotation/StringLineEndingFixer.php9~_9k u-src/Fixer/StringNotation/SingleQuoteFixer.php,~_,7;src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php~_11src/Fixer/StringNotation/HeredocToNowdocFixer.phps~_so\ٴ8src/Fixer/StringNotation/ExplicitStringVariableFixer.php~_0src/Fixer/FunctionNotation/StaticLambdaFixer.php ~_ z̴Nsrc/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php\ ~_\ t&BO/src/Fixer/FunctionNotation/ImplodeCallFixer.php[ ~_[ Y,8=src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php ~_ :9´8src/Fixer/FunctionNotation/CombineNestedDirnameFixer.phpD~_Dʹ蓴.src/Fixer/FunctionNotation/VoidReturnFixer.phpH~_H m3src/Fixer/FunctionNotation/SingleLineThrowFixer.php ~_ ^^49src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php ~_ NQ5src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php~_nɴ<src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.phpe~_e?-Jô7src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php-~_-y6src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php~_y^o.src/Fixer/FunctionNotation/FopenFlagsFixer.php0 ~_0 +9src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php~_'7src/Fixer/FunctionNotation/FunctionDeclarationFixer.php~_F#2src/Fixer/FunctionNotation/FopenFlagOrderFixer.phpW~_WdEsrc/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php~_T)*src/Fixer/Naming/NoHomoglyphNamesFixer.php ~_ {˴-src/Fixer/Casing/MagicConstantCasingFixer.php>~_>6ݴ.src/Fixer/Casing/NativeFunctionCasingFixer.php~_hz3)&src/Fixer/Casing/ConstantCaseFixer.php ~_ W,src/Fixer/Casing/LowercaseConstantsFixer.php~_<~@Ѵ+src/Fixer/Casing/LowercaseKeywordsFixer.phpM~_M +src/Fixer/Casing/MagicMethodCasingFixer.php~_C}V2src/Fixer/Casing/LowercaseStaticReferenceFixer.php~_B=src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php6 ~_6 3<src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php ~_ |Asrc/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.phpA~_AmJCsrc/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php~_4$@src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php~_u-src/Fixer/CastNotation/LowercaseCastFixer.php9~_9ϯ"*src/Fixer/CastNotation/CastSpacesFixer.phpE~_Ed+src/Fixer/CastNotation/NoUnsetCastFixer.php~_ ) /src/Fixer/CastNotation/NoShortBoolCastFixer.php~_'/src/Fixer/CastNotation/ShortScalarCastFixer.php~_t5src/Fixer/CastNotation/ModernizeTypesCastingFixer.php ~_ m+src/Fixer/ControlStructure/IncludeFixer.php ~_ j}9src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.phpV ~_V '|1src/Fixer/ControlStructure/NoUselessElseFixer.php~_J4=.7src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php~_nY3src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php~_=@src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.phpz~_z2src/Fixer/ControlStructure/NoBreakCommentFixer.php#~_#p*>src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php~_<ô*src/Fixer/ControlStructure/ElseifFixer.phpF~_F'k=src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php~_YN-src/Fixer/ControlStructure/YodaStyleFixer.php5~_5em7src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php~_;src/PregException.phpg~_gٴ2src/Tokenizer/Transformer/AttributeTransformer.php4~_4V:src/Tokenizer/Transformer/NamespaceOperatorTransformer.php~_P/src/Tokenizer/Transformer/ImportTransformer.php0~_0i2src/Tokenizer/Transformer/TypeColonTransformer.php~_ǔ@src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php~_rSH[8src/Tokenizer/Transformer/TypeAlternationTransformer.phpv~_v72src/Tokenizer/Transformer/ReturnRefTransformer.php~_4δ4src/Tokenizer/Transformer/SquareBraceTransformer.php ~_ k셴,src/Tokenizer/Analyzer/ArgumentsAnalyzer.php ~_ "+src/Tokenizer/Analyzer/CommentsAnalyzer.php~_Դ)src/Tokenizer/Analyzer/BlocksAnalyzer.php!~_!=-src/Tokenizer/Analyzer/NamespacesAnalyzer.php~_bĴ)src/Tokenizer/Analyzer/ClassyAnalyzer.php~_ ϴ0src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php~_꼴)src/Tokenizer/Analyzer/SwitchAnalyzer.php< ~_< s 6>src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php~_`98src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php~_ˆ2src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php ~_ d4src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.phpA~_A1WX5src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php ~_ 70src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php~_],D 0src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php~_',src/Tokenizer/Analyzer/FunctionsAnalyzer.php~_,4~src/Tokenizer/Transformers.php~_-ܴsrc/Tokenizer/Tokens.phpX~_X3%src/Tokenizer/AbstractTransformer.phpv~_v'0msrc/Tokenizer/CT.phph~_h=Usrc/AbstractFixer.php~_&,src/AbstractPhpdocToTypeDeclarationFixer.php~_Uشsrc/FileReader.php~_1src/RuleSet/RuleSet.php'~_'/Du>+src/RuleSet/RuleSetDescriptionInterface.php~_ src/RuleSet/RuleSetInterface.phps~_s4N&src/RuleSet/Sets/PHP70MigrationSet.php~~_~;ϴ/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php~_c+/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php~_hXU/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php~_XѴ/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php~__}+src/RuleSet/Sets/PHP80MigrationRiskySet.php#~_#0usrc/RuleSet/Sets/SymfonySet.php~_\/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php~_G4/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php~_ Ǵ&src/RuleSet/Sets/PHP56MigrationSet.php=~_=h=c/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php~_0+src/RuleSet/Sets/PHP71MigrationRiskySet.phpz~_zsrc/RuleSet/Sets/PSR1Set.php{~_{"src/RuleSet/Sets/PhpCsFixerSet.php~_//src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php~_xbY/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php~_$ܒ/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php~_9/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php~_GO/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php~_@&src/RuleSet/Sets/PHP71MigrationSet.php~_9`}*src/RuleSet/Sets/DoctrineAnnotationSet.phpE~_Ea+src/RuleSet/Sets/PHP70MigrationRiskySet.php[~_[١4B+src/RuleSet/Sets/PHP56MigrationRiskySet.phpc~_c>4src/RuleSet/Sets/PSR2Set.php~_\-]&src/RuleSet/Sets/PHP73MigrationSet.phpw~_w$src/RuleSet/Sets/SymfonyRiskySet.php:~_:hڴ'src/RuleSet/Sets/PhpCsFixerRiskySet.phpE~_E1/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php~_uϴ&src/RuleSet/Sets/PHP80MigrationSet.php~_.Nsrc/RuleSet/RuleSets.phpt~_t.H*src/RuleSet/AbstractRuleSetDescription.php~_9 src/Cache/DirectoryInterface.php~_Fdsrc/Cache/FileHandler.php~_̴src/Cache/CacheInterface.php~_'뭴src/Cache/Directory.phpP~_PT"src/Cache/FileHandlerInterface.php~_hsrc/Cache/Cache.php*~_*oܴsrc/Cache/Signature.php{~_{#R src/Cache/SignatureInterface.php4~_4Jsrc/Cache/FileCacheManager.php~_#src/Cache/CacheManagerInterface.php~_Dsrc/Cache/NullCacheManager.php~_4nci-integration.sh~_|U{(vendor/symfony/filesystem/Filesystem.php;~_;#A)vendor/symfony/filesystem/LockHandler.php;~_;f$<vendor/symfony/filesystem/Exception/IOExceptionInterface.php~_jwM:vendor/symfony/filesystem/Exception/ExceptionInterface.phpi~_i$ 3vendor/symfony/filesystem/Exception/IOException.php~_\5=vendor/symfony/filesystem/Exception/FileNotFoundException.php~_9`vendor/symfony/finder/Glob.php~_U)j%vendor/symfony/finder/SplFileInfo.php~_5vendor/symfony/finder/Comparator/NumberComparator.php~_ڡ33vendor/symfony/finder/Comparator/DateComparator.php#~_#δ/vendor/symfony/finder/Comparator/Comparator.php~_:vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php`~_`!ky1vendor/symfony/finder/Iterator/FilterIterator.php~_ =vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php ~_ ƺ9vendor/symfony/finder/Iterator/FilenameFilterIterator.phpr~_rtu;vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php~_۴Avendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php~_f_=vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php= ~_= Y9vendor/symfony/finder/Iterator/FileTypeFilterIterator.phpZ~_Z(&:vendor/symfony/finder/Iterator/DateRangeFilterIterator.phps~_s=x7vendor/symfony/finder/Iterator/CustomFilterIterator.phpX~_XDVSB5vendor/symfony/finder/Iterator/PathFilterIterator.php~_F<vendor/symfony/finder/Iterator/FilecontentFilterIterator.phpA~_A&ޤ3vendor/symfony/finder/Iterator/SortableIterator.phpN~_N% vendor/symfony/finder/Finder.php%"~_%"uH9vendor/symfony/finder/Exception/AccessDeniedException.php~_s6vendor/symfony/finder/Exception/ExceptionInterface.php~_L~&vendor/symfony/process/InputStream.php'~_'X>/vendor/symfony/process/Pipes/PipesInterface.phpm~_mu-vendor/symfony/process/Pipes/WindowsPipes.php0 ~_0 A.vendor/symfony/process/Pipes/AbstractPipes.php ~_ ym*vendor/symfony/process/Pipes/UnixPipes.php~_%vendor/symfony/process/PhpProcess.php~_x=vendor/symfony/process/Exception/ProcessTimedOutException.php~_;vendor/symfony/process/Exception/ProcessFailedException.phpx~_xzy7vendor/symfony/process/Exception/ExceptionInterface.phpf~_f]>T5vendor/symfony/process/Exception/RuntimeException.php~_:3vendor/symfony/process/Exception/LogicException.php~_ =vendor/symfony/process/Exception/InvalidArgumentException.php~_+_'vendor/symfony/process/ProcessUtils.php:~_:)vendor/symfony/process/ProcessBuilder.php ~_ VqѴ.vendor/symfony/process/PhpExecutableFinder.php~_*>+vendor/symfony/process/ExecutableFinder.php~_ô"vendor/symfony/process/Process.phpl~_l0mU+vendor/symfony/polyfill-php70/bootstrap.phpw~_wb'vendor/symfony/polyfill-php70/Php70.php~_=+Evendor/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php3~_3h;Avendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php/~_/|mʹ<vendor/symfony/polyfill-php70/Resources/stubs/ParseError.php*~_*ᤴ@vendor/symfony/polyfill-php70/Resources/stubs/AssertionError.php.~_.&8yXvendor/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php~_~;vendor/symfony/polyfill-php70/Resources/stubs/TypeError.php)~_)O_7vendor/symfony/polyfill-php70/Resources/stubs/Error.php)~_)[k &vendor/symfony/console/Application.phpQh~_Qh>vendor/symfony/console/Formatter/OutputFormatterStyleStack.php;~_;%9vendor/symfony/console/Formatter/OutputFormatterStyle.php~_`*4vendor/symfony/console/Formatter/OutputFormatter.php~_:n=vendor/symfony/console/Formatter/OutputFormatterInterface.php~_Bvendor/symfony/console/Formatter/OutputFormatterStyleInterface.php~_G8vendor/symfony/console/Question/ConfirmationQuestion.php~_d?,vendor/symfony/console/Question/Question.php ~_ N2vendor/symfony/console/Question/ChoiceQuestion.phpB ~_B дDvendor/symfony/console/DependencyInjection/AddConsoleCommandPass.phpb ~_b 蒜#vendor/symfony/console/Terminal.php ~_ Ѵ0vendor/symfony/console/Output/BufferedOutput.php`~_`蟗(vendor/symfony/console/Output/Output.php ~_ 0p/vendor/symfony/console/Output/ConsoleOutput.php~_Sc8vendor/symfony/console/Output/ConsoleOutputInterface.php~_ʴ.vendor/symfony/console/Output/StreamOutput.php~_$W1vendor/symfony/console/Output/OutputInterface.php~_n ,vendor/symfony/console/Output/NullOutput.php~_Z6vendor/symfony/console/Event/ConsoleExceptionEvent.php~_(4vendor/symfony/console/Event/ConsoleCommandEvent.php~_!ȴ6vendor/symfony/console/Event/ConsoleTerminateEvent.phpz~_z,L-vendor/symfony/console/Event/ConsoleEvent.php~_Ӵ2vendor/symfony/console/Event/ConsoleErrorEvent.phpb~_bMh.vendor/symfony/console/Input/InputArgument.php ~_ ;0vendor/symfony/console/Input/InputDefinition.php~_qR&vendor/symfony/console/Input/Input.phpG ~_G ,vendor/symfony/console/Input/StringInput.phpW~_W}j*vendor/symfony/console/Input/ArgvInput.php~_N ɴ/vendor/symfony/console/Input/InputInterface.php~_rrg,vendor/symfony/console/Input/InputOption.php ~_ 4vendor/symfony/console/Input/InputAwareInterface.php~_O9vendor/symfony/console/Input/StreamableInputInterface.php~_B+vendor/symfony/console/Input/ArrayInput.php+ ~_+ 'ٴ=vendor/symfony/console/Exception/CommandNotFoundException.php~_K*5;vendor/symfony/console/Exception/InvalidOptionException.php~_H7vendor/symfony/console/Exception/ExceptionInterface.phpf~_fAB5vendor/symfony/console/Exception/RuntimeException.php~_,63vendor/symfony/console/Exception/LogicException.php~_O\e=vendor/symfony/console/Exception/InvalidArgumentException.php~_̽Z8vendor/symfony/console/Descriptor/MarkdownDescriptor.php~_>4<vendor/symfony/console/Descriptor/ApplicationDescription.php ~_ @?,״0vendor/symfony/console/Descriptor/Descriptor.phps~_scBM4vendor/symfony/console/Descriptor/JsonDescriptor.php~_S]R9vendor/symfony/console/Descriptor/DescriptorInterface.php~_P~4vendor/symfony/console/Descriptor/TextDescriptor.php"~_"O굴3vendor/symfony/console/Descriptor/XmlDescriptor.php ~_ 4 δ.vendor/symfony/console/Command/HelpCommand.php~_<.vendor/symfony/console/Command/ListCommand.php~_5-*vendor/symfony/console/Command/Command.php:!~_:!o%0vendor/symfony/console/Command/LockableTrait.php2~_2Nߴ/vendor/symfony/console/Tester/CommandTester.php~_Uc3vendor/symfony/console/Tester/ApplicationTester.php) ~_) X6vendor/symfony/console/Helper/DebugFormatterHelper.phpj~_jOG 1vendor/symfony/console/Helper/HelperInterface.php~_/vendor/symfony/console/Helper/ProcessHelper.php ~_ O2vendor/symfony/console/Helper/InputAwareHelper.phpc~_c(vendor/symfony/console/Helper/Helper.phpk~_k'颴'vendor/symfony/console/Helper/Table.php-~_-2vendor/symfony/console/Helper/DescriptorHelper.phpe~_e2_7vendor/symfony/console/Helper/SymfonyQuestionHelper.php ~_ 0vendor/symfony/console/Helper/TableSeparator.php~_1vendor/symfony/console/Helper/FormatterHelper.phpD~_D+L+vendor/symfony/console/Helper/HelperSet.phpf~_fx,vendor/symfony/console/Helper/TableStyle.php+ ~_+ 86+vendor/symfony/console/Helper/TableCell.phpv~_v+ 3vendor/symfony/console/Helper/ProgressIndicator.phpD~_DJxF0vendor/symfony/console/Helper/QuestionHelper.php^%~_^%3Ph-vendor/symfony/console/Helper/ProgressBar.php9%~_9%/vendor/symfony/console/Style/StyleInterface.php~_-vendor/symfony/console/Style/SymfonyStyle.php\~_\豞,vendor/symfony/console/Style/OutputStyle.phpX~_X/vendor/symfony/console/Logger/ConsoleLogger.php ~_  Z(vendor/symfony/console/ConsoleEvents.php~_'?vendor/symfony/console/CommandLoader/ContainerCommandLoader.phpH~_H-ߴ?vendor/symfony/console/CommandLoader/CommandLoaderInterface.phpG~_G?=vendor/symfony/console/CommandLoader/FactoryCommandLoader.php~_m6vendor/symfony/console/EventListener/ErrorListener.php"~_"M^ %vendor/symfony/debug/ErrorHandler.php8H~_8Hw+)vendor/symfony/debug/ExceptionHandler.phpM~_Mۡ)vendor/symfony/debug/DebugClassLoader.php\+~_\+owgIvendor/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php ~_ FKvendor/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.phpO~_OhѴMvendor/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php~_Fd-Evendor/symfony/debug/FatalErrorHandler/FatalErrorHandlerInterface.php~_ĹBV6vendor/symfony/debug/Exception/FatalErrorException.php.~_.J0=vendor/symfony/debug/Exception/UndefinedFunctionException.php~_J8vendor/symfony/debug/Exception/ContextErrorException.php~_67vendor/symfony/debug/Exception/OutOfMemoryException.php~~_~o7vendor/symfony/debug/Exception/SilencedErrorContext.php(~_(+l3vendor/symfony/debug/Exception/FlattenException.phpn~_nw 6vendor/symfony/debug/Exception/FatalThrowableError.phpZ~_Z;9vendor/symfony/debug/Exception/ClassNotFoundException.php~_i;vendor/symfony/debug/Exception/UndefinedMethodException.php~_nش(vendor/symfony/debug/BufferingLogger.php`~_`Dm۴vendor/symfony/debug/Debug.php.~_.B;+vendor/symfony/polyfill-php72/bootstrap.phpu~_u&'vendor/symfony/polyfill-php72/Php72.php~_W+vendor/symfony/polyfill-ctype/bootstrap.php~_|p:'vendor/symfony/polyfill-ctype/Ctype.phpH ~_H ݴ.vendor/symfony/polyfill-mbstring/bootstrap.php~_J-vendor/symfony/polyfill-mbstring/Mbstring.phpG~_G̴ֽ@vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.phpU~_U`8QFvendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php~_y_@vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.phpT~_T2?Dvendor/symfony/polyfill-mbstring/Resources/mb_convert_variables.php8?~_?3vendor/symfony/options-resolver/OptionsResolver.php:~_:!xEvendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php~_ܴ+vendor/symfony/options-resolver/Options.php{~_{|Evendor/symfony/options-resolver/Exception/MissingOptionsException.php~_==vendor/symfony/options-resolver/Exception/AccessException.php~_5@vendor/symfony/options-resolver/Exception/ExceptionInterface.phpn~_nyGvendor/symfony/options-resolver/Exception/OptionDefinitionException.php~_@4Fvendor/symfony/options-resolver/Exception/NoConfigurationException.php~_jEGvendor/symfony/options-resolver/Exception/UndefinedOptionsException.php~_p ͐Evendor/symfony/options-resolver/Exception/InvalidOptionsException.php~_k Cvendor/symfony/options-resolver/Exception/NoSuchOptionException.php~_g]ȴFvendor/symfony/options-resolver/Exception/InvalidArgumentException.php~_G9vendor/symfony/event-dispatcher/Debug/WrappedListener.php ~_ !Kvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php5~_5fVBvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php~_O 'Mvendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php~_\]<vendor/symfony/event-dispatcher/EventDispatcherInterface.php~_pX0vendor/symfony/event-dispatcher/GenericEvent.phpl~_l@F^Ĵ3vendor/symfony/event-dispatcher/EventDispatcher.php3~_3Krx"Avendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php~_0Ѵ)vendor/symfony/event-dispatcher/Event.php:~_:E <vendor/symfony/event-dispatcher/ImmutableEventDispatcher.phpq~_q<vendor/symfony/event-dispatcher/EventSubscriberInterface.php~_,vendor/symfony/stopwatch/StopwatchPeriod.phpp~_pΧ!&vendor/symfony/stopwatch/Stopwatch.php~_#i{+vendor/symfony/stopwatch/StopwatchEvent.php ~_ !A $vendor/symfony/stopwatch/Section.php~_-vendor/autoload.php~_y? D#vendor/composer/autoload_static.phpl*~_l* "4vendor/composer/xdebug-handler/src/XdebugHandler.php$~_${Ĕ0vendor/composer/xdebug-handler/src/PhpConfig.php~_*D-vendor/composer/xdebug-handler/src/Status.php ~_ $v-.vendor/composer/xdebug-handler/src/Process.php ~_ 5ʴ%vendor/composer/InstalledVersions.php)~_)?_!vendor/composer/autoload_real.php~_^#vendor/composer/installed.php~_Py"vendor/composer/autoload_files.php5~_5&-!vendor/composer/autoload_psr4.php~_%vendor/composer/autoload_classmap.phpf~_f("vendor/composer/platform_check.phpe~_eݿJ/vendor/composer/semver/src/CompilingMatcher.php~_?u'vendor/composer/semver/src/Interval.php~_ ȏ۴,vendor/composer/semver/src/VersionParser.php+~_+7m<vendor/composer/semver/src/Constraint/MatchAllConstraint.php~_4vendor/composer/semver/src/Constraint/Constraint.php~_h=vendor/composer/semver/src/Constraint/ConstraintInterface.php~_?[=vendor/composer/semver/src/Constraint/MatchNoneConstraint.php~_괠/vendor/composer/semver/src/Constraint/Bound.phpt~_tۜ9vendor/composer/semver/src/Constraint/MultiConstraint.php~_)vendor/composer/semver/src/Comparator.php~_^݊(vendor/composer/semver/src/Intervals.php:,~_:,D%vendor/composer/semver/src/Semver.php~_`e'vendor/composer/autoload_namespaces.phpd~_dZHvendor/composer/ClassLoader.php~_jŴMvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php~_nWSFvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php"~_"Р@ִKvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php|~_|wPvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.phph~_hzԷSvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.phpm~_mZ[vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php~_Tvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php~_fʓ۴Uvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php~_~ĴOvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.phpt~_t]Qvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php0~_0 uOvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/FileCacheReader.php~_qIvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php~_VHvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.phpw~_w&nLvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/CachedReader.phpj~_j&}Svendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php-~_-aIvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php V~_ V`Jvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php<~_<zXRvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php~_Vvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/SimpleAnnotationReader.phpJ~_Jq*Avendor/doctrine/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php9 ~_9 Z/vendor/psr/log/Psr/Log/LoggerAwareInterface.php|~_|$+vendor/psr/log/Psr/Log/LoggerAwareTrait.php~_TB)vendor/psr/log/Psr/Log/AbstractLogger.php;~_;>3[%vendor/psr/log/Psr/Log/NullLogger.php~_Di#vendor/psr/log/Psr/Log/LogLevel.php~_j8&vendor/psr/log/Psr/Log/LoggerTrait.phpk~_k}*vendor/psr/log/Psr/Log/LoggerInterface.php~_x3vendor/psr/log/Psr/Log/InvalidArgumentException.php`~_` X1+vendor/php-cs-fixer/diff/src/v1_4/Chunk.php ~_ ۴*vendor/php-cs-fixer/diff/src/v1_4/Line.php~_!/,vendor/php-cs-fixer/diff/src/v1_4/Differ.phpa~_aB]vendor/php-cs-fixer/diff/src/v1_4/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php~_ 8_vendor/php-cs-fixer/diff/src/v1_4/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php~_:Bvendor/php-cs-fixer/diff/src/v1_4/LCS/LongestCommonSubsequence.php~_),vendor/php-cs-fixer/diff/src/v1_4/Parser.php~_6qc*vendor/php-cs-fixer/diff/src/v1_4/Diff.php~_0}n+vendor/php-cs-fixer/diff/src/v3_0/Chunk.php~_&_F*vendor/php-cs-fixer/diff/src/v3_0/Line.php~_8,vendor/php-cs-fixer/diff/src/v3_0/Differ.php~_ F*,vendor/php-cs-fixer/diff/src/v3_0/Parser.php~_j?Uvendor/php-cs-fixer/diff/src/v3_0/TimeEfficientLongestCommonSubsequenceCalculator.php~_#1Kvendor/php-cs-fixer/diff/src/v3_0/Output/StrictUnifiedDiffOutputBuilder.php~_}Bvendor/php-cs-fixer/diff/src/v3_0/Output/DiffOnlyOutputBuilder.php~_7Gvendor/php-cs-fixer/diff/src/v3_0/Output/AbstractChunkOutputBuilder.php~_=hGvendor/php-cs-fixer/diff/src/v3_0/Output/DiffOutputBuilderInterface.php~_R8OEvendor/php-cs-fixer/diff/src/v3_0/Output/UnifiedDiffOutputBuilder.php~_IWƴHvendor/php-cs-fixer/diff/src/v3_0/LongestCommonSubsequenceCalculator.php~_kbFvendor/php-cs-fixer/diff/src/v3_0/Exception/ConfigurationException.php~_ks9vendor/php-cs-fixer/diff/src/v3_0/Exception/Exception.phpH~_H{nHvendor/php-cs-fixer/diff/src/v3_0/Exception/InvalidArgumentException.php~_*vendor/php-cs-fixer/diff/src/v3_0/Diff.php~_aFWvendor/php-cs-fixer/diff/src/v3_0/MemoryEfficientLongestCommonSubsequenceCalculator.php ~_ _Wvendor/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/ConfigurationException.php~_z8Yvendor/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/UnifiedDiffOutputBuilder.php~_@:L+vendor/php-cs-fixer/diff/src/v2_0/Chunk.php~_k˴*vendor/php-cs-fixer/diff/src/v2_0/Line.php~_AQ,vendor/php-cs-fixer/diff/src/v2_0/Differ.php+~_+N1 δ,vendor/php-cs-fixer/diff/src/v2_0/Parser.php~_lCUvendor/php-cs-fixer/diff/src/v2_0/TimeEfficientLongestCommonSubsequenceCalculator.php~_KBvendor/php-cs-fixer/diff/src/v2_0/Output/DiffOnlyOutputBuilder.php~_E{IGvendor/php-cs-fixer/diff/src/v2_0/Output/AbstractChunkOutputBuilder.php~_1%|Gvendor/php-cs-fixer/diff/src/v2_0/Output/DiffOutputBuilderInterface.php~_uEvendor/php-cs-fixer/diff/src/v2_0/Output/UnifiedDiffOutputBuilder.php ~_ .۴Hvendor/php-cs-fixer/diff/src/v2_0/LongestCommonSubsequenceCalculator.php~_59vendor/php-cs-fixer/diff/src/v2_0/Exception/Exception.phpH~_Hs-Hvendor/php-cs-fixer/diff/src/v2_0/Exception/InvalidArgumentException.php~_;$*vendor/php-cs-fixer/diff/src/v2_0/Diff.php~_Wvendor/php-cs-fixer/diff/src/v2_0/MemoryEfficientLongestCommonSubsequenceCalculator.php ~_ h 3vendor/paragonie/random_compat/phpunit-autoload.php~_4GYY>vendor/paragonie/random_compat/lib/random_bytes_com_dotnet.php~_vA:vendor/paragonie/random_compat/lib/random_bytes_mcrypt.php5~_5IWyl8vendor/paragonie/random_compat/lib/byte_safe_strings.phpp~_p36d-vendor/paragonie/random_compat/lib/random.php ~_ =vendor/paragonie/random_compat/lib/random_bytes_libsodium.php~_3+2g5vendor/paragonie/random_compat/lib/error_polyfill.php~_a42vendor/paragonie/random_compat/lib/cast_to_int.php~_|wDvendor/paragonie/random_compat/lib/random_bytes_libsodium_legacy.php~_!?vendor/paragonie/random_compat/lib/random_bytes_dev_urandom.php~_1vendor/paragonie/random_compat/lib/random_int.php.~_.m1LICENSES~_SRMS php-cs-fixer ~_ !isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, PhpTokens $phpTokens) { $analyzer = new TokensAnalyzer($phpTokens); $this->classyElements = $analyzer->getClassyElements(); foreach ($phpTokens->findGivenKind(T_DOC_COMMENT) as $index => $docCommentToken) { if (!$this->nextElementAcceptsDoctrineAnnotations($phpTokens, $index)) { continue; } $tokens = DoctrineAnnotationTokens::createFromDocComment( $docCommentToken, $this->configuration['ignored_tags'] ); $this->fixAnnotations($tokens); $phpTokens[$index] = new PhpToken([T_DOC_COMMENT, $tokens->getCode()]); } } abstract protected function fixAnnotations(DoctrineAnnotationTokens $doctrineAnnotationTokens); protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('ignored_tags', 'List of tags that must not be treated as Doctrine Annotations.')) ->setAllowedTypes(['array']) ->setAllowedValues([static function ($values) { foreach ($values as $value) { if (!\is_string($value)) { return false; } } return true; }]) ->setDefault([ 'abstract', 'access', 'code', 'deprec', 'encode', 'exception', 'final', 'ingroup', 'inheritdoc', 'inheritDoc', 'magic', 'name', 'toc', 'tutorial', 'private', 'static', 'staticvar', 'staticVar', 'throw', 'api', 'author', 'category', 'copyright', 'deprecated', 'example', 'filesource', 'global', 'ignore', 'internal', 'license', 'link', 'method', 'package', 'param', 'property', 'property-read', 'property-write', 'return', 'see', 'since', 'source', 'subpackage', 'throws', 'todo', 'TODO', 'usedBy', 'uses', 'var', 'version', 'after', 'afterClass', 'backupGlobals', 'backupStaticAttributes', 'before', 'beforeClass', 'codeCoverageIgnore', 'codeCoverageIgnoreStart', 'codeCoverageIgnoreEnd', 'covers', 'coversDefaultClass', 'coversNothing', 'dataProvider', 'depends', 'expectedException', 'expectedExceptionCode', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp', 'group', 'large', 'medium', 'preserveGlobalState', 'requires', 'runTestsInSeparateProcesses', 'runInSeparateProcess', 'small', 'test', 'testdox', 'ticket', 'uses', 'SuppressWarnings', 'noinspection', 'package_version', 'enduml', 'startuml', 'fix', 'FIXME', 'fixme', 'override', ]) ->getOption(), ]); } private function nextElementAcceptsDoctrineAnnotations(PhpTokens $tokens, $index) { do { $index = $tokens->getNextMeaningfulToken($index); if (null === $index) { return false; } } while ($tokens[$index]->isGivenKind([T_ABSTRACT, T_FINAL])); if ($tokens[$index]->isClassy()) { return true; } while ($tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_NS_SEPARATOR, T_STRING, CT::T_NULLABLE_TYPE])) { $index = $tokens->getNextMeaningfulToken($index); } return isset($this->classyElements[$index]); } } summary = $summary; $this->codeSamples = $codeSamples; $this->description = $description; $this->configurationDescription = $configurationDescription; $this->defaultConfiguration = $defaultConfiguration; $this->riskyDescription = $riskyDescription; } public function getSummary() { return $this->summary; } public function getDescription() { return $this->description; } public function getConfigurationDescription() { @trigger_error(sprintf('%s is deprecated and will be removed in 3.0.', __METHOD__), E_USER_DEPRECATED); return $this->configurationDescription; } public function getDefaultConfiguration() { @trigger_error(sprintf('%s is deprecated and will be removed in 3.0.', __METHOD__), E_USER_DEPRECATED); return $this->defaultConfiguration; } public function getRiskyDescription() { return $this->riskyDescription; } public function getCodeSamples() { return $this->codeSamples; } } codeSample = new CodeSample($code, $configuration); $this->versionSpecification = $versionSpecification; } public function getCode() { return $this->codeSample->getCode(); } public function getConfiguration() { return $this->codeSample->getConfiguration(); } public function isSuitableFor($version) { return $this->versionSpecification->isSatisfiedBy($version); } } code = $code; $this->configuration = $configuration; } public function getCode() { return $this->code; } public function getConfiguration() { return $this->configuration; } } $minimum)) { throw new \InvalidArgumentException('Minimum needs to be either null or an integer greater than 0.'); } if (null !== $maximum) { if (!\is_int($maximum) || 1 > $maximum) { throw new \InvalidArgumentException('Maximum needs to be either null or an integer greater than 0.'); } if (null !== $minimum && $maximum < $minimum) { throw new \InvalidArgumentException('Maximum should not be lower than the minimum.'); } } $this->minimum = $minimum; $this->maximum = $maximum; } public function isSatisfiedBy($version) { if (null !== $this->minimum && $version < $this->minimum) { return false; } if (null !== $this->maximum && $version > $this->maximum) { return false; } return true; } } codeSample = new CodeSample($code, $configuration); $this->splFileInfo = $splFileInfo; } public function getCode() { return $this->codeSample->getCode(); } public function getConfiguration() { return $this->codeSample->getConfiguration(); } public function getSplFileInfo() { return $this->splFileInfo; } } getChanged() as $fileName => $change) { foreach ($change['appliedFixers'] as $fixerName) { $report[] = [ 'description' => $fixerName, 'fingerprint' => md5($fileName.$fixerName), 'location' => [ 'path' => $fileName, 'lines' => [ 'begin' => 0, ], ], ]; } } $jsonString = json_encode($report); return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($jsonString) : $jsonString; } } getChanged() as $file => $fixResult) { $jfile = ['name' => $file]; if ($reportSummary->shouldAddAppliedFixers()) { $jfile['appliedFixers'] = $fixResult['appliedFixers']; } if (!empty($fixResult['diff'])) { $jfile['diff'] = $fixResult['diff']; } $jFiles[] = $jfile; } $json = [ 'files' => $jFiles, ]; if (null !== $reportSummary->getTime()) { $json['time'] = [ 'total' => round($reportSummary->getTime() / 1000, 3), ]; } if (null !== $reportSummary->getMemory()) { $json['memory'] = round($reportSummary->getMemory() / 1024 / 1024, 3); } $json = json_encode($json); return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($json) : $json; } } files()->name('*Reporter.php')->in(__DIR__) as $file) { $relativeNamespace = $file->getRelativePath(); $builtInReporters[] = sprintf( '%s\\%s%s', __NAMESPACE__, $relativeNamespace ? $relativeNamespace.'\\' : '', $file->getBasename('.php') ); } } foreach ($builtInReporters as $reporterClass) { $this->registerReporter(new $reporterClass()); } return $this; } public function registerReporter(ReporterInterface $reporter) { $format = $reporter->getFormat(); if (isset($this->reporters[$format])) { throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is already registered.', $format)); } $this->reporters[$format] = $reporter; return $this; } public function getFormats() { $formats = array_keys($this->reporters); sort($formats); return $formats; } public function getReporter($format) { if (!isset($this->reporters[$format])) { throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is not registered.', $format)); } return $this->reporters[$format]; } } changed = $changed; $this->time = $time; $this->memory = $memory; $this->addAppliedFixers = $addAppliedFixers; $this->isDryRun = $isDryRun; $this->isDecoratedOutput = $isDecoratedOutput; } public function isDecoratedOutput() { return $this->isDecoratedOutput; } public function isDryRun() { return $this->isDryRun; } public function getChanged() { return $this->changed; } public function getMemory() { return $this->memory; } public function getTime() { return $this->time; } public function shouldAddAppliedFixers() { return $this->addAppliedFixers; } } appendChild($dom->createElement('checkstyle')); foreach ($reportSummary->getChanged() as $filePath => $fixResult) { $file = $checkstyles->appendChild($dom->createElement('file')); $file->setAttribute('name', $filePath); foreach ($fixResult['appliedFixers'] as $appliedFixer) { $error = $this->createError($dom, $appliedFixer); $file->appendChild($error); } } $dom->formatOutput = true; return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); } private function createError(\DOMDocument $dom, $appliedFixer) { $error = $dom->createElement('error'); $error->setAttribute('severity', 'warning'); $error->setAttribute('source', 'PHP-CS-Fixer.'.$appliedFixer); $error->setAttribute('message', 'Found violation(s) of type: '.$appliedFixer); return $error; } } createElement('report'); $dom->appendChild($root); $filesXML = $dom->createElement('files'); $root->appendChild($filesXML); $i = 1; foreach ($reportSummary->getChanged() as $file => $fixResult) { $fileXML = $dom->createElement('file'); $fileXML->setAttribute('id', (string) $i++); $fileXML->setAttribute('name', $file); $filesXML->appendChild($fileXML); if ($reportSummary->shouldAddAppliedFixers()) { $fileXML->appendChild($this->createAppliedFixersElement($dom, $fixResult)); } if (!empty($fixResult['diff'])) { $fileXML->appendChild($this->createDiffElement($dom, $fixResult)); } } if (0 !== $reportSummary->getTime()) { $root->appendChild($this->createTimeElement($reportSummary->getTime(), $dom)); } if (0 !== $reportSummary->getMemory()) { $root->appendChild($this->createMemoryElement($reportSummary->getMemory(), $dom)); } $dom->formatOutput = true; return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); } private function createAppliedFixersElement($dom, array $fixResult) { $appliedFixersXML = $dom->createElement('applied_fixers'); foreach ($fixResult['appliedFixers'] as $appliedFixer) { $appliedFixerXML = $dom->createElement('applied_fixer'); $appliedFixerXML->setAttribute('name', $appliedFixer); $appliedFixersXML->appendChild($appliedFixerXML); } return $appliedFixersXML; } private function createDiffElement(\DOMDocument $dom, array $fixResult) { $diffXML = $dom->createElement('diff'); $diffXML->appendChild($dom->createCDATASection($fixResult['diff'])); return $diffXML; } private function createTimeElement($time, \DOMDocument $dom) { $time = round($time / 1000, 3); $timeXML = $dom->createElement('time'); $timeXML->setAttribute('unit', 's'); $timeTotalXML = $dom->createElement('total'); $timeTotalXML->setAttribute('value', (string) $time); $timeXML->appendChild($timeTotalXML); return $timeXML; } private function createMemoryElement($memory, \DOMDocument $dom) { $memory = round($memory / 1024 / 1024, 3); $memoryXML = $dom->createElement('memory'); $memoryXML->setAttribute('value', (string) $memory); $memoryXML->setAttribute('unit', 'MB'); return $memoryXML; } } getChanged() as $file => $fixResult) { ++$i; $output .= sprintf('%4d) %s', $i, $file); if ($reportSummary->shouldAddAppliedFixers()) { $output .= $this->getAppliedFixers($reportSummary->isDecoratedOutput(), $fixResult); } $output .= $this->getDiff($reportSummary->isDecoratedOutput(), $fixResult); $output .= PHP_EOL; } return $output.$this->getFooter($reportSummary->getTime(), $reportSummary->getMemory(), $reportSummary->isDryRun()); } private function getAppliedFixers($isDecoratedOutput, array $fixResult) { return sprintf( $isDecoratedOutput ? ' (%s)' : ' (%s)', implode(', ', $fixResult['appliedFixers']) ); } private function getDiff($isDecoratedOutput, array $fixResult) { if (empty($fixResult['diff'])) { return ''; } $diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, sprintf( ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', PHP_EOL, PHP_EOL )); return PHP_EOL.$diffFormatter->format($fixResult['diff']).PHP_EOL; } private function getFooter($time, $memory, $isDryRun) { if (0 === $time || 0 === $memory) { return ''; } return PHP_EOL.sprintf( '%s all files in %.3f seconds, %.3f MB memory used'.PHP_EOL, $isDryRun ? 'Checked' : 'Fixed', $time / 1000, $memory / 1024 / 1024 ); } } appendChild($dom->createElement('testsuites')); $testsuite = $testsuites->appendChild($dom->createElement('testsuite')); $testsuite->setAttribute('name', 'PHP CS Fixer'); if (\count($reportSummary->getChanged())) { $this->createFailedTestCases($dom, $testsuite, $reportSummary); } else { $this->createSuccessTestCase($dom, $testsuite); } if ($reportSummary->getTime()) { $testsuite->setAttribute( 'time', sprintf( '%.3f', $reportSummary->getTime() / 1000 ) ); } $dom->formatOutput = true; return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); } private function createSuccessTestCase(\DOMDocument $dom, \DOMElement $testsuite) { $testcase = $dom->createElement('testcase'); $testcase->setAttribute('name', 'All OK'); $testcase->setAttribute('assertions', '1'); $testsuite->appendChild($testcase); $testsuite->setAttribute('tests', '1'); $testsuite->setAttribute('assertions', '1'); $testsuite->setAttribute('failures', '0'); $testsuite->setAttribute('errors', '0'); } private function createFailedTestCases(\DOMDocument $dom, \DOMElement $testsuite, ReportSummary $reportSummary) { $assertionsCount = 0; foreach ($reportSummary->getChanged() as $file => $fixResult) { $testcase = $this->createFailedTestCase( $dom, $file, $fixResult, $reportSummary->shouldAddAppliedFixers() ); $testsuite->appendChild($testcase); $assertionsCount += (int) $testcase->getAttribute('assertions'); } $testsuite->setAttribute('tests', (string) \count($reportSummary->getChanged())); $testsuite->setAttribute('assertions', (string) $assertionsCount); $testsuite->setAttribute('failures', (string) $assertionsCount); $testsuite->setAttribute('errors', '0'); } private function createFailedTestCase(\DOMDocument $dom, $file, array $fixResult, $shouldAddAppliedFixers) { $appliedFixersCount = \count($fixResult['appliedFixers']); $testName = str_replace('.', '_DOT_', Preg::replace('@\.'.pathinfo($file, PATHINFO_EXTENSION).'$@', '', $file)); $testcase = $dom->createElement('testcase'); $testcase->setAttribute('name', $testName); $testcase->setAttribute('file', $file); $testcase->setAttribute('assertions', (string) $appliedFixersCount); $failure = $dom->createElement('failure'); $failure->setAttribute('type', 'code_style'); $testcase->appendChild($failure); if ($shouldAddAppliedFixers) { $failureContent = "applied fixers:\n---------------\n"; foreach ($fixResult['appliedFixers'] as $appliedFixer) { $failureContent .= "* {$appliedFixer}\n"; } } else { $failureContent = "Wrong code style\n"; } if (!empty($fixResult['diff'])) { $failureContent .= "\nDiff:\n---------------\n\n".$fixResult['diff']; } $failure->appendChild($dom->createCDATASection(trim($failureContent))); return $testcase; } } type = $type; $this->content = $content; } public function getType() { return $this->type; } public function setType($type) { $this->type = $type; } public function getContent() { return $this->content; } public function setContent($content) { $this->content = $content; } public function isType($types) { if (!\is_array($types)) { $types = [$types]; } return \in_array($this->getType(), $types, true); } public function clear() { $this->setContent(''); } } isGivenKind(T_DOC_COMMENT)) { throw new \InvalidArgumentException('Input must be a T_DOC_COMMENT token.'); } $tokens = new self(); $content = $input->getContent(); $ignoredTextPosition = 0; $currentPosition = 0; while (false !== $nextAtPosition = strpos($content, '@', $currentPosition)) { if (0 !== $nextAtPosition && !Preg::match('/\s/', $content[$nextAtPosition - 1])) { $currentPosition = $nextAtPosition + 1; continue; } $lexer = new DocLexer(); $lexer->setInput(substr($content, $nextAtPosition)); $scannedTokens = []; $index = 0; $nbScannedTokensToUse = 0; $nbScopes = 0; while (null !== $token = $lexer->peek()) { if (0 === $index && DocLexer::T_AT !== $token['type']) { break; } if (1 === $index) { if (DocLexer::T_IDENTIFIER !== $token['type'] || \in_array($token['value'], $ignoredTags, true)) { break; } $nbScannedTokensToUse = 2; } if ($index >= 2 && 0 === $nbScopes && !\in_array($token['type'], [DocLexer::T_NONE, DocLexer::T_OPEN_PARENTHESIS], true)) { break; } $scannedTokens[] = $token; if (DocLexer::T_OPEN_PARENTHESIS === $token['type']) { ++$nbScopes; } elseif (DocLexer::T_CLOSE_PARENTHESIS === $token['type']) { if (0 === --$nbScopes) { $nbScannedTokensToUse = \count($scannedTokens); break; } } ++$index; } if (0 !== $nbScopes) { break; } if (0 !== $nbScannedTokensToUse) { $ignoredTextLength = $nextAtPosition - $ignoredTextPosition; if (0 !== $ignoredTextLength) { $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition, $ignoredTextLength)); } $lastTokenEndIndex = 0; foreach (\array_slice($scannedTokens, 0, $nbScannedTokensToUse) as $token) { if (DocLexer::T_STRING === $token['type']) { $token['value'] = '"'.str_replace('"', '""', $token['value']).'"'; } $missingTextLength = $token['position'] - $lastTokenEndIndex; if ($missingTextLength > 0) { $tokens[] = new Token(DocLexer::T_NONE, substr( $content, $nextAtPosition + $lastTokenEndIndex, $missingTextLength )); } $tokens[] = new Token($token['type'], $token['value']); $lastTokenEndIndex = $token['position'] + \strlen($token['value']); } $currentPosition = $ignoredTextPosition = $nextAtPosition + $token['position'] + \strlen($token['value']); } else { $currentPosition = $nextAtPosition + 1; } } if ($ignoredTextPosition < \strlen($content)) { $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition)); } return $tokens; } public function getNextMeaningfulToken($index) { return $this->getMeaningfulTokenSibling($index, 1); } public function getPreviousMeaningfulToken($index) { return $this->getMeaningfulTokenSibling($index, -1); } public function getNextTokenOfType($type, $index) { return $this->getTokenOfTypeSibling($index, $type, 1); } public function getPreviousTokenOfType($type, $index) { return $this->getTokenOfTypeSibling($index, $type, -1); } public function getAnnotationEnd($index) { $currentIndex = null; if (isset($this[$index + 2])) { if ($this[$index + 2]->isType(DocLexer::T_OPEN_PARENTHESIS)) { $currentIndex = $index + 2; } elseif ( isset($this[$index + 3]) && $this[$index + 2]->isType(DocLexer::T_NONE) && $this[$index + 3]->isType(DocLexer::T_OPEN_PARENTHESIS) && Preg::match('/^(\R\s*\*\s*)*\s*$/', $this[$index + 2]->getContent()) ) { $currentIndex = $index + 3; } } if (null !== $currentIndex) { $level = 0; for ($max = \count($this); $currentIndex < $max; ++$currentIndex) { if ($this[$currentIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { ++$level; } elseif ($this[$currentIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { --$level; } if (0 === $level) { return $currentIndex; } } return null; } return $index + 1; } public function getArrayEnd($index) { $level = 1; for (++$index, $max = \count($this); $index < $max; ++$index) { if ($this[$index]->isType(DocLexer::T_OPEN_CURLY_BRACES)) { ++$level; } elseif ($this[$index]->isType($index, DocLexer::T_CLOSE_CURLY_BRACES)) { --$level; } if (0 === $level) { return $index; } } return null; } public function getCode() { $code = ''; foreach ($this as $token) { $code .= $token->getContent(); } return $code; } public function insertAt($index, Token $token) { $this->setSize($this->getSize() + 1); for ($i = $this->getSize() - 1; $i > $index; --$i) { $this[$i] = isset($this[$i - 1]) ? $this[$i - 1] : new Token(); } $this[$index] = $token; } public function offsetSet($index, $token) { if (!$token instanceof Token) { $type = \gettype($token); if ('object' === $type) { $type = \get_class($token); } throw new \InvalidArgumentException(sprintf( 'Token must be an instance of PhpCsFixer\\Doctrine\\Annotation\\Token, %s given.', $type )); } if (null === $index) { $index = \count($this); $this->setSize($this->getSize() + 1); } parent::offsetSet($index, $token); } public function offsetUnset($index) { if (!isset($this[$index])) { throw new \OutOfBoundsException(sprintf('Index %s is invalid or does not exist.', $index)); } $max = \count($this) - 1; while ($index < $max) { $this[$index] = $this[$index + 1]; ++$index; } parent::offsetUnset($index); $this->setSize($max); } private function getMeaningfulTokenSibling($index, $direction) { while (true) { $index += $direction; if (!$this->offsetExists($index)) { break; } if (!$this[$index]->isType(DocLexer::T_NONE)) { return $index; } } return null; } private function getTokenOfTypeSibling($index, $type, $direction) { while (true) { $index += $direction; if (!$this->offsetExists($index)) { break; } if ($this[$index]->isType($type)) { return $index; } } return null; } } status = $status; } public function getStatus() { return $this->status; } } differ = new Differ(new UnifiedDiffOutputBuilder([ 'fromFile' => 'Original', 'toFile' => 'New', ])); $this->path = \dirname(__DIR__, 2).'/doc'; } public function getFixersDocumentationDirectoryPath() { return $this->path.'/rules'; } public function getFixersDocumentationIndexFilePath() { return $this->getFixersDocumentationDirectoryPath().'/index.rst'; } public function generateFixersDocumentationIndex(array $fixers) { $overrideGroups = [ 'PhpUnit' => 'PHPUnit', 'PhpTag' => 'PHP Tag', 'Phpdoc' => 'PHPDoc', ]; usort($fixers, function (FixerInterface $a, FixerInterface $b) { return strcmp(\get_class($a), \get_class($b)); }); $documentation = <<<'RST' ======================= List of Available Rules ======================= RST; $currentGroup = null; foreach ($fixers as $fixer) { $namespace = Preg::replace('/^.*\\\\(.+)\\\\.+Fixer$/', '$1', \get_class($fixer)); if (isset($overrideGroups[$namespace])) { $group = $overrideGroups[$namespace]; } else { $group = Preg::replace('/(?<=[[:lower:]])(?=[[:upper:]])/', ' ', $namespace); } if ($group !== $currentGroup) { $underline = str_repeat('-', \strlen($group)); $documentation .= "\n\n{$group}\n{$underline}\n"; $currentGroup = $group; } $summary = str_replace('`', '``', $fixer->getDefinition()->getSummary()); $attributes = []; if ($fixer instanceof DeprecatedFixerInterface) { $attributes[] = 'deprecated'; } if ($fixer->isRisky()) { $attributes[] = 'risky'; } if ([] !== $attributes) { $attributes = ' *('.implode(', ', $attributes).')*'; } else { $attributes = ''; } $path = './'.$this->getFixerDocumentationFileRelativePath($fixer); $documentation .= <<getName()} <{$path}>`_{$attributes} {$summary} RST; } return "{$documentation}\n"; } public function getFixerDocumentationFilePath(FixerInterface $fixer) { return $this->getFixersDocumentationDirectoryPath().'/'.Preg::replaceCallback( '/^.*\\\\(.+)\\\\(.+)Fixer$/', function (array $matches) { return Utils::camelCaseToUnderscore($matches[1]).'/'.Utils::camelCaseToUnderscore($matches[2]); }, \get_class($fixer) ).'.rst'; } public function getFixerDocumentationFileRelativePath(FixerInterface $fixer) { return Preg::replace( '#^'.preg_quote($this->getFixersDocumentationDirectoryPath(), '#').'/#', '', $this->getFixerDocumentationFilePath($fixer) ); } public function generateFixerDocumentation(FixerInterface $fixer) { $name = $fixer->getName(); $title = "Rule ``{$name}``"; $titleLine = str_repeat('=', \strlen($title)); $doc = "{$titleLine}\n{$title}\n{$titleLine}"; if ($fixer instanceof DeprecatedFixerInterface) { $doc .= "\n\n.. warning:: This rule is deprecated and will be removed on next major version."; $alternatives = $fixer->getSuccessorsNames(); if ([] !== $alternatives) { $doc .= $this->toRst(sprintf( "\n\nYou should use %s instead.", Utils::naturalLanguageJoinWithBackticks($alternatives) ), 3); } } $riskyDescription = null; $samples = []; if ($fixer instanceof DefinedFixerInterface) { $definition = $fixer->getDefinition(); $doc .= "\n\n".$this->toRst($definition->getSummary()); $description = $definition->getDescription(); if (null !== $description) { $description = $this->toRst($description); $doc .= <<getRiskyDescription(); $samples = $definition->getCodeSamples(); } elseif ($fixer->isRisky()) { $riskyDescription = 'Changes applied by the rule to your code might change its behavior.'; } if (null !== $riskyDescription) { $riskyDescription = $this->toRst($riskyDescription, 3); $doc .= <<getConfigurationDefinition(); foreach ($configurationDefinition->getOptions() as $option) { $optionInfo = "``{$option->getName()}``"; $optionInfo .= "\n".str_repeat('~', \strlen($optionInfo)); if ($option instanceof DeprecatedFixerOptionInterface) { $optionInfo .= "\n\n.. warning:: This option is deprecated and will be removed on next major version. {$this->toRst($option->getDeprecationMessage())}"; } $optionInfo .= "\n\n".$this->toRst($option->getDescription()); if ($option instanceof AliasedFixerOption) { $optionInfo .= "\n\n.. note:: The previous name of this option was ``{$option->getAlias()}`` but it is now deprecated and will be removed on next major version."; } $allowed = HelpCommand::getDisplayableAllowedValues($option); $allowedKind = 'Allowed values'; if (null !== $allowed) { foreach ($allowed as &$value) { if ($value instanceof AllowedValueSubset) { $value = 'a subset of ``'.HelpCommand::toString($value->getAllowedValues()).'``'; } else { $value = '``'.HelpCommand::toString($value).'``'; } } } else { $allowedKind = 'Allowed types'; $allowed = array_map(function ($value) { return '``'.$value.'``'; }, $option->getAllowedTypes()); } if (null !== $allowed) { $allowed = implode(', ', $allowed); $optionInfo .= "\n\n{$allowedKind}: {$allowed}"; } if ($option->hasDefault()) { $default = HelpCommand::toString($option->getDefault()); $optionInfo .= "\n\nDefault value: ``{$default}``"; } else { $optionInfo .= "\n\nThis option is required."; } $doc .= "\n\n{$optionInfo}"; } } elseif ($fixer instanceof ConfigurableFixerInterface) { $doc .= "\n\nThis rule is configurable."; } if (0 !== \count($samples)) { $doc .= <<<'RST' Examples -------- RST; foreach ($samples as $index => $sample) { $title = sprintf('Example #%d', $index + 1); $titleLine = str_repeat('~', \strlen($title)); $doc .= "\n\n{$title}\n{$titleLine}"; if ($fixer instanceof ConfigurableFixerInterface) { if (null === $sample->getConfiguration()) { $doc .= "\n\n*Default* configuration."; } else { $doc .= sprintf( "\n\nWith configuration: ``%s``.", HelpCommand::toString($sample->getConfiguration()) ); } } $doc .= "\n".$this->generateSampleDiff($fixer, $sample, $index + 1, $name); } } $ruleSetConfigs = []; foreach (RuleSets::getSetDefinitionNames() as $set) { $ruleSet = new RuleSet([$set => true]); if ($ruleSet->hasRule($name)) { $ruleSetConfigs[$set] = $ruleSet->getRuleConfiguration($name); } } if ([] !== $ruleSetConfigs) { $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; $doc .= << $config) { $ruleSetPath = $this->getRuleSetsDocumentationFilePath($set); $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); $doc .= <<`_ rule set will enable the ``{$name}`` rule RST; if (null !== $config) { $doc .= " with the config below:\n\n ``".HelpCommand::toString($config).'``'; } elseif ($fixer instanceof ConfigurationDefinitionFixerInterface) { $doc .= ' with the default config.'; } else { $doc .= '.'; } } } return "{$doc}\n"; } public function getRuleSetsDocumentationDirectoryPath() { return $this->path.'/ruleSets'; } public function getRuleSetsDocumentationIndexFilePath() { return $this->getRuleSetsDocumentationDirectoryPath().'/index.rst'; } public function generateRuleSetsDocumentation(RuleSetDescriptionInterface $definition, array $fixers) { $fixerNames = []; foreach ($fixers as $fixer) { $fixerNames[$fixer->getName()] = $fixer; } $title = "Rule set ``{$definition->getName()}``"; $titleLine = str_repeat('=', \strlen($title)); $doc = "{$titleLine}\n{$title}\n{$titleLine}\n\n".$definition->getDescription(); if ($definition->isRisky()) { $doc .= ' This set contains rules that are risky.'; } $doc .= "\n\n"; $rules = $definition->getRules(); if (\count($rules) < 1) { $doc .= 'This is an empty set.'; } else { $doc .= "Rules\n-----\n"; foreach ($rules as $rule => $config) { if ('@' === $rule[0]) { $ruleSetPath = $this->getRuleSetsDocumentationFilePath($rule); $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); $doc .= "\n- `{$rule} <.{$ruleSetPath}>`_"; } else { $path = Preg::replace( '#^'.preg_quote($this->getFixersDocumentationDirectoryPath(), '#').'/#', './../rules/', $this->getFixerDocumentationFilePath($fixerNames[$rule]) ); $doc .= "\n- `{$rule} <{$path}>`_"; } if (!\is_bool($config)) { $doc .= "\n config:\n ``".HelpCommand::toString($config).'``'; } } } return $doc."\n"; } public function getRuleSetsDocumentationFilePath($name) { return $this->getRuleSetsDocumentationDirectoryPath().'/'.str_replace(':risky', 'Risky', ucfirst(substr($name, 1))).'.rst'; } public function generateRuleSetsDocumentationIndex(array $setDefinitions) { $documentation = <<<'RST' =========================== List of Available Rule sets =========================== RST; foreach ($setDefinitions as $name => $path) { $path = substr($path, strrpos($path, '/')); $documentation .= "\n- `{$name} <.{$path}>`_"; } return $documentation."\n"; } private function generateSampleDiff(FixerInterface $fixer, CodeSampleInterface $sample, $sampleNumber, $ruleName) { if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) { $existingFile = @file_get_contents($this->getFixerDocumentationFilePath($fixer)); if (false !== $existingFile) { Preg::match("/\\RExample #{$sampleNumber}\\R.+?(?\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|$)/s", $existingFile, $matches); if (isset($matches['diff'])) { return $matches['diff']; } } $error = <<getCode(); $tokens = Tokens::fromCode($old); $file = $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : new StdinFileInfo() ; if ($fixer instanceof ConfigurableFixerInterface) { $configuration = $sample->getConfiguration(); if (null === $configuration) { $configuration = []; } if ($fixer instanceof Psr0Fixer && isset($configuration['dir']) && 0 === strpos($configuration['dir'], './')) { $configuration['dir'] = \dirname(__DIR__, 2).substr($configuration['dir'], 1); } $fixer->configure($configuration); } $fixer->fix($file, $tokens); $diff = $this->differ->diff($old, $tokens->generateCode()); $diff = Preg::replace('/\r/', '^M', $diff); $diff = Preg::replace('/^ $/m', '', $diff); $diff = Preg::replace('/\n$/', '', $diff); return <<indent($diff, 3)} RST; } private function toRst($string, $indent = 0) { $string = wordwrap(Preg::replace('/(?indent($string, $indent); } return $string; } private function indent($string, $indent) { return Preg::replace('/(\n)(?!\n|$)/', '$1'.str_repeat(' ', $indent), $string); } } toolInfo = new ToolInfo(); $this->add(new DescribeCommand()); $this->add(new FixCommand($this->toolInfo)); $this->add(new SelfUpdateCommand( new NewVersionChecker(new GithubClient()), $this->toolInfo, new PharChecker() )); } public static function getMajorVersion() { return (int) explode('.', self::VERSION)[0]; } public function doRun(InputInterface $input, OutputInterface $output) { $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ($input->hasParameterOption('--format', true) && 'txt' !== $input->getParameterOption('--format', null, true) ? null : $output) ; if (null !== $stdErr) { $warningsDetector = new WarningsDetector($this->toolInfo); $warningsDetector->detectOldVendor(); $warningsDetector->detectOldMajor(); foreach ($warningsDetector->getWarnings() as $warning) { $stdErr->writeln(sprintf($stdErr->isDecorated() ? '%s' : '%s', $warning)); } } return parent::doRun($input, $output); } public function getLongVersion() { $version = sprintf( '%s %s by Fabien Potencier and Dariusz Ruminski', parent::getLongVersion(), self::VERSION_CODENAME ); $commit = '3d0f843b8abe1b966156774bf4093ebbb77f92cc'; if ('@'.'git-commit@' !== $commit) { $version .= ' ('.substr($commit, 0, 7).')'; } return $version; } protected function getDefaultCommands() { return [new HelpCommand(), new ListCommand()]; } } toolInfo = $toolInfo; } public function detectOldMajor() { } public function detectOldVendor() { if ($this->toolInfo->isInstalledByComposer()) { $details = $this->toolInfo->getComposerInstallationDetails(); if (ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME === $details['name']) { $this->warnings[] = sprintf( 'You are running PHP CS Fixer installed with old vendor `%s`. Please update to `%s`.', ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME, ToolInfo::COMPOSER_PACKAGE_NAME ); } } } public function getWarnings() { if (!\count($this->warnings)) { return []; } return array_unique(array_merge( $this->warnings, ['If you need help while solving warnings, ask at https://gitter.im/PHP-CS-Fixer, we will help you!'] )); } } ['symbol' => '?', 'format' => '%s', 'description' => 'unknown'], FixerFileProcessedEvent::STATUS_INVALID => ['symbol' => 'I', 'format' => '%s', 'description' => 'invalid file syntax (file ignored)'], FixerFileProcessedEvent::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '%s', 'description' => 'skipped (cached or empty file)'], FixerFileProcessedEvent::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'], FixerFileProcessedEvent::STATUS_FIXED => ['symbol' => 'F', 'format' => '%s', 'description' => 'fixed'], FixerFileProcessedEvent::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], FixerFileProcessedEvent::STATUS_LINT => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], ]; private $eventDispatcher; private $output; private $files; private $processedFiles = 0; private $symbolsPerLine; public function __construct(OutputInterface $output, EventDispatcherInterface $dispatcher, $width, $nbFiles) { $this->output = $output; $this->eventDispatcher = $dispatcher; $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, [$this, 'onFixerFileProcessed']); $this->symbolsPerLine = $width; if (null !== $nbFiles) { $this->files = $nbFiles; $this->symbolsPerLine = max(1, ($width ?: 80) - \strlen((string) $this->files) * 2 - 11); } } public function __destruct() { $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, [$this, 'onFixerFileProcessed']); } public function onFixerFileProcessed(FixerFileProcessedEvent $event) { if ( null === $this->files && null !== $this->symbolsPerLine && 0 === $this->processedFiles % $this->symbolsPerLine && 0 !== $this->processedFiles ) { $this->output->writeln(''); } $status = self::$eventStatusMap[$event->getStatus()]; $this->output->write($this->output->isDecorated() ? sprintf($status['format'], $status['symbol']) : $status['symbol']); ++$this->processedFiles; if (null !== $this->files) { $symbolsOnCurrentLine = $this->processedFiles % $this->symbolsPerLine; $isLast = $this->processedFiles === $this->files; if (0 === $symbolsOnCurrentLine || $isLast) { $this->output->write(sprintf( '%s %'.\strlen((string) $this->files).'d / %d (%3d%%)', $isLast && 0 !== $symbolsOnCurrentLine ? str_repeat(' ', $this->symbolsPerLine - $symbolsOnCurrentLine) : '', $this->processedFiles, $this->files, round($this->processedFiles / $this->files * 100) )); if (!$isLast) { $this->output->writeln(''); } } } } public function printLegend() { $symbols = []; foreach (self::$eventStatusMap as $status) { $symbol = $status['symbol']; if ('' === $symbol || isset($symbols[$symbol])) { continue; } $symbols[$symbol] = sprintf('%s-%s', $this->output->isDecorated() ? sprintf($status['format'], $symbol) : $symbol, $status['description']); } $this->output->write(sprintf("\nLegend: %s\n", implode(', ', $symbols))); } } output = $output; $this->isDecorated = $output->isDecorated(); } public function listErrors($process, array $errors) { $this->output->writeln(['', sprintf( 'Files that were not fixed due to errors reported during %s:', $process )]); $showDetails = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE; $showTrace = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG; foreach ($errors as $i => $error) { $this->output->writeln(sprintf('%4d) %s', $i + 1, $error->getFilePath())); $e = $error->getSource(); if (!$showDetails || null === $e) { continue; } $class = sprintf('[%s]', \get_class($e)); $message = $e->getMessage(); $code = $e->getCode(); if (0 !== $code) { $message .= " ({$code})"; } $length = max(\strlen($class), \strlen($message)); $lines = [ '', $class, $message, '', ]; $this->output->writeln(''); foreach ($lines as $line) { if (\strlen($line) < $length) { $line .= str_repeat(' ', $length - \strlen($line)); } $this->output->writeln(sprintf(' %s ', $this->prepareOutput($line))); } if ($showTrace && !$e instanceof LintingException) { $this->output->writeln(''); $stackTrace = $e->getTrace(); foreach ($stackTrace as $trace) { if (isset($trace['class'], $trace['function']) && \Symfony\Component\Console\Command\Command::class === $trace['class'] && 'run' === $trace['function']) { $this->output->writeln(' [ ... ]'); break; } $this->outputTrace($trace); } } if (Error::TYPE_LINT === $error->getType() && 0 < \count($error->getAppliedFixers())) { $this->output->writeln(''); $this->output->writeln(sprintf(' Applied fixers: %s', implode(', ', $error->getAppliedFixers()))); $diff = $error->getDiff(); if (!empty($diff)) { $diffFormatter = new DiffConsoleFormatter( $this->isDecorated, sprintf( ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', PHP_EOL, PHP_EOL ) ); $this->output->writeln($diffFormatter->format($diff)); } } } } private function outputTrace(array $trace) { if (isset($trace['class'], $trace['type'], $trace['function'])) { $this->output->writeln(sprintf( ' %s%s%s()', $this->prepareOutput($trace['class']), $this->prepareOutput($trace['type']), $this->prepareOutput($trace['function']) )); } elseif (isset($trace['function'])) { $this->output->writeln(sprintf(' %s()', $this->prepareOutput($trace['function']))); } if (isset($trace['file'])) { $this->output->writeln(sprintf(' in %s at line %d', $this->prepareOutput($trace['file']), $trace['line'])); } } private function prepareOutput($string) { return $this->isDecorated ? OutputFormatter::escape($string) : $string ; } } null, 'cache-file' => null, 'config' => null, 'diff' => null, 'diff-format' => null, 'dry-run' => null, 'format' => null, 'path' => [], 'path-mode' => self::PATH_MODE_OVERRIDE, 'rules' => null, 'show-progress' => null, 'stop-on-violation' => null, 'using-cache' => null, 'verbosity' => null, ]; private $cacheFile; private $cacheManager; private $differ; private $directory; private $finder; private $format; private $linter; private $path; private $progress; private $ruleSet; private $usingCache; private $fixerFactory; public function __construct( ConfigInterface $config, array $options, $cwd, ToolInfoInterface $toolInfo ) { $this->cwd = $cwd; $this->defaultConfig = $config; $this->toolInfo = $toolInfo; foreach ($options as $name => $value) { $this->setOption($name, $value); } } public function getCacheFile() { if (!$this->getUsingCache()) { return null; } if (null === $this->cacheFile) { if (null === $this->options['cache-file']) { $this->cacheFile = $this->getConfig()->getCacheFile(); } else { $this->cacheFile = $this->options['cache-file']; } } return $this->cacheFile; } public function getCacheManager() { if (null === $this->cacheManager) { $cacheFile = $this->getCacheFile(); if (null === $cacheFile) { $this->cacheManager = new NullCacheManager(); } else { $this->cacheManager = new FileCacheManager( new FileHandler($cacheFile), new Signature( PHP_VERSION, $this->toolInfo->getVersion(), $this->getConfig()->getIndent(), $this->getConfig()->getLineEnding(), $this->getRules() ), $this->isDryRun(), $this->getDirectory() ); } } return $this->cacheManager; } public function getConfig() { if (null === $this->config) { foreach ($this->computeConfigFiles() as $configFile) { if (!file_exists($configFile)) { continue; } $config = self::separatedContextLessInclude($configFile); if (!$config instanceof ConfigInterface) { throw new InvalidConfigurationException(sprintf('The config file: "%s" does not return a "PhpCsFixer\ConfigInterface" instance. Got: "%s".', $configFile, \is_object($config) ? \get_class($config) : \gettype($config))); } $this->config = $config; $this->configFile = $configFile; break; } if (null === $this->config) { $this->config = $this->defaultConfig; } } return $this->config; } public function getConfigFile() { if (null === $this->configFile) { $this->getConfig(); } return $this->configFile; } public function getDiffer() { if (null === $this->differ) { $mapper = [ 'null' => static function () { return new NullDiffer(); }, 'sbd' => static function () { return new SebastianBergmannDiffer(); }, 'udiff' => static function () { return new UnifiedDiffer(); }, ]; if ($this->options['diff-format']) { $option = $this->options['diff-format']; if (!isset($mapper[$option])) { throw new InvalidConfigurationException(sprintf( '"diff-format" must be any of "%s", got "%s".', implode('", "', array_keys($mapper)), $option )); } } else { $default = 'sbd'; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { $default = 'udiff'; } $option = $this->options['diff'] ? $default : 'null'; } $this->differ = $mapper[$option](); } return $this->differ; } public function getDirectory() { if (null === $this->directory) { $path = $this->getCacheFile(); if (null === $path) { $absolutePath = $this->cwd; } else { $filesystem = new Filesystem(); $absolutePath = $filesystem->isAbsolutePath($path) ? $path : $this->cwd.\DIRECTORY_SEPARATOR.$path; } $this->directory = new Directory(\dirname($absolutePath)); } return $this->directory; } public function getFixers() { if (null === $this->fixers) { $this->fixers = $this->createFixerFactory() ->useRuleSet($this->getRuleSet()) ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding())) ->getFixers() ; if (false === $this->getRiskyAllowed()) { $riskyFixers = array_map( static function (FixerInterface $fixer) { return $fixer->getName(); }, array_filter( $this->fixers, static function (FixerInterface $fixer) { return $fixer->isRisky(); } ) ); if (\count($riskyFixers)) { throw new InvalidConfigurationException(sprintf('The rules contain risky fixers (%s), but they are not allowed to run. Perhaps you forget to use --allow-risky=yes option?', implode('", "', $riskyFixers))); } } } return $this->fixers; } public function getLinter() { if (null === $this->linter) { $this->linter = new Linter($this->getConfig()->getPhpExecutable()); } return $this->linter; } public function getPath() { if (null === $this->path) { $filesystem = new Filesystem(); $cwd = $this->cwd; if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) { $this->path = $this->options['path']; } else { $this->path = array_map( static function ($rawPath) use ($cwd, $filesystem) { $path = trim($rawPath); if ('' === $path) { throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\"."); } $absolutePath = $filesystem->isAbsolutePath($path) ? $path : $cwd.\DIRECTORY_SEPARATOR.$path; if (!file_exists($absolutePath)) { throw new InvalidConfigurationException(sprintf( 'The path "%s" is not readable.', $path )); } return $absolutePath; }, $this->options['path'] ); } } return $this->path; } public function getProgress() { if (null === $this->progress) { if (OutputInterface::VERBOSITY_VERBOSE <= $this->options['verbosity'] && 'txt' === $this->getFormat()) { $progressType = $this->options['show-progress']; $progressTypes = ['none', 'run-in', 'estimating', 'estimating-max', 'dots']; if (null === $progressType) { $default = 'run-in'; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { $default = 'dots'; } $progressType = $this->getConfig()->getHideProgress() ? 'none' : $default; } elseif (!\in_array($progressType, $progressTypes, true)) { throw new InvalidConfigurationException(sprintf( 'The progress type "%s" is not defined, supported are "%s".', $progressType, implode('", "', $progressTypes) )); } elseif (\in_array($progressType, ['estimating', 'estimating-max', 'run-in'], true)) { $message = 'Passing `estimating`, `estimating-max` or `run-in` is deprecated and will not be supported in 3.0, use `none` or `dots` instead.'; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new \InvalidArgumentException("{$message} This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); } $this->progress = $progressType; } else { $this->progress = 'none'; } } return $this->progress; } public function getReporter() { if (null === $this->reporter) { $reporterFactory = ReporterFactory::create(); $reporterFactory->registerBuiltInReporters(); $format = $this->getFormat(); try { $this->reporter = $reporterFactory->getReporter($format); } catch (\UnexpectedValueException $e) { $formats = $reporterFactory->getFormats(); sort($formats); throw new InvalidConfigurationException(sprintf('The format "%s" is not defined, supported are "%s".', $format, implode('", "', $formats))); } } return $this->reporter; } public function getRiskyAllowed() { if (null === $this->allowRisky) { if (null === $this->options['allow-risky']) { $this->allowRisky = $this->getConfig()->getRiskyAllowed(); } else { $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky'); } } return $this->allowRisky; } public function getRules() { return $this->getRuleSet()->getRules(); } public function getUsingCache() { if (null === $this->usingCache) { if (null === $this->options['using-cache']) { $this->usingCache = $this->getConfig()->getUsingCache(); } else { $this->usingCache = $this->resolveOptionBooleanValue('using-cache'); } } $this->usingCache = $this->usingCache && ($this->toolInfo->isInstalledAsPhar() || $this->toolInfo->isInstalledByComposer()); return $this->usingCache; } public function getFinder() { if (null === $this->finder) { $this->finder = $this->resolveFinder(); } return $this->finder; } public function isDryRun() { if (null === $this->isDryRun) { if ($this->isStdIn()) { $this->isDryRun = true; } else { $this->isDryRun = $this->options['dry-run']; } } return $this->isDryRun; } public function shouldStopOnViolation() { return $this->options['stop-on-violation']; } public function configFinderIsOverridden() { if (null === $this->configFinderIsOverridden) { $this->resolveFinder(); } return $this->configFinderIsOverridden; } private function computeConfigFiles() { $configFile = $this->options['config']; if (null !== $configFile) { if (false === file_exists($configFile) || false === is_readable($configFile)) { throw new InvalidConfigurationException(sprintf('Cannot read config file "%s".', $configFile)); } return [$configFile]; } $path = $this->getPath(); if ($this->isStdIn() || 0 === \count($path)) { $configDir = $this->cwd; } elseif (1 < \count($path)) { throw new InvalidConfigurationException('For multiple paths config parameter is required.'); } elseif (!is_file($path[0])) { $configDir = $path[0]; } else { $dirName = pathinfo($path[0], PATHINFO_DIRNAME); $configDir = $dirName ?: $path[0]; } $candidates = [ $configDir.\DIRECTORY_SEPARATOR.'.php_cs', $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', ]; if ($configDir !== $this->cwd) { $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs'; $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist'; } return $candidates; } private function createFixerFactory() { if (null === $this->fixerFactory) { $fixerFactory = new FixerFactory(); $fixerFactory->registerBuiltInFixers(); $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers()); $this->fixerFactory = $fixerFactory; } return $this->fixerFactory; } private function getFormat() { if (null === $this->format) { $this->format = null === $this->options['format'] ? $this->getConfig()->getFormat() : $this->options['format']; } return $this->format; } private function getRuleSet() { if (null === $this->ruleSet) { $rules = $this->parseRules(); $this->validateRules($rules); $this->ruleSet = new RuleSet($rules); } return $this->ruleSet; } private function isStdIn() { if (null === $this->isStdIn) { $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0]; } return $this->isStdIn; } private function iterableToTraversable($iterable) { return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable; } private function parseRules() { if (null === $this->options['rules']) { return $this->getConfig()->getRules(); } $rules = trim($this->options['rules']); if ('' === $rules) { throw new InvalidConfigurationException('Empty rules value is not allowed.'); } if ('{' === $rules[0]) { $rules = json_decode($rules, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new InvalidConfigurationException(sprintf('Invalid JSON rules input: "%s".', json_last_error_msg())); } return $rules; } $rules = []; foreach (explode(',', $this->options['rules']) as $rule) { $rule = trim($rule); if ('' === $rule) { throw new InvalidConfigurationException('Empty rule name is not allowed.'); } if ('-' === $rule[0]) { $rules[substr($rule, 1)] = false; } else { $rules[$rule] = true; } } return $rules; } private function validateRules(array $rules) { $ruleSet = []; foreach ($rules as $key => $value) { if (\is_int($key)) { throw new InvalidConfigurationException(sprintf('Missing value for "%s" rule/set.', $value)); } $ruleSet[$key] = true; } $ruleSet = new RuleSet($ruleSet); $configuredFixers = array_keys($ruleSet->getRules()); $fixers = $this->createFixerFactory()->getFixers(); $availableFixers = array_map(static function (FixerInterface $fixer) { return $fixer->getName(); }, $fixers); $unknownFixers = array_diff( $configuredFixers, $availableFixers ); if (\count($unknownFixers)) { $matcher = new WordMatcher($availableFixers); $message = 'The rules contain unknown fixers: '; foreach ($unknownFixers as $unknownFixer) { $alternative = $matcher->match($unknownFixer); $message .= sprintf( '"%s"%s, ', $unknownFixer, null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)' ); } throw new InvalidConfigurationException(substr($message, 0, -2).'.'); } foreach ($fixers as $fixer) { $fixerName = $fixer->getName(); if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) { $successors = $fixer->getSuccessorsNames(); $messageEnd = [] === $successors ? sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1) : sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors))); $message = "Rule \"{$fixerName}\" is deprecated{$messageEnd}"; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new \RuntimeException("{$message} This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); } } } private function resolveFinder() { $this->configFinderIsOverridden = false; if ($this->isStdIn()) { return new \ArrayIterator([new StdinFileInfo()]); } $modes = [self::PATH_MODE_OVERRIDE, self::PATH_MODE_INTERSECTION]; if (!\in_array( $this->options['path-mode'], $modes, true )) { throw new InvalidConfigurationException(sprintf( 'The path-mode "%s" is not defined, supported are "%s".', $this->options['path-mode'], implode('", "', $modes) )); } $isIntersectionPathMode = self::PATH_MODE_INTERSECTION === $this->options['path-mode']; $paths = array_filter(array_map( static function ($path) { return realpath($path); }, $this->getPath() )); if (!\count($paths)) { if ($isIntersectionPathMode) { return new \ArrayIterator([]); } return $this->iterableToTraversable($this->getConfig()->getFinder()); } $pathsByType = [ 'file' => [], 'dir' => [], ]; foreach ($paths as $path) { if (is_file($path)) { $pathsByType['file'][] = $path; } else { $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR; } } $nestedFinder = null; $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder()); try { $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder; } catch (\Exception $e) { } if ($isIntersectionPathMode) { if (null === $nestedFinder) { throw new InvalidConfigurationException( 'Cannot create intersection with not-fully defined Finder in configuration file.' ); } return new \CallbackFilterIterator( new \IteratorIterator($nestedFinder), static function (\SplFileInfo $current) use ($pathsByType) { $currentRealPath = $current->getRealPath(); if (\in_array($currentRealPath, $pathsByType['file'], true)) { return true; } foreach ($pathsByType['dir'] as $path) { if (0 === strpos($currentRealPath, $path)) { return true; } } return false; } ); } if (null !== $this->getConfigFile() && null !== $nestedFinder) { $this->configFinderIsOverridden = true; } if ($currentFinder instanceof SymfonyFinder && null === $nestedFinder) { return $currentFinder->in($pathsByType['dir'])->append($pathsByType['file']); } return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']); } private function setOption($name, $value) { if (!\array_key_exists($name, $this->options)) { throw new InvalidConfigurationException(sprintf('Unknown option name: "%s".', $name)); } $this->options[$name] = $value; } private function resolveOptionBooleanValue($optionName) { $value = $this->options[$optionName]; if (\is_bool($value)) { return $value; } if (!\is_string($value)) { throw new InvalidConfigurationException(sprintf('Expected boolean or string value for option "%s".', $optionName)); } if ('yes' === $value) { return true; } if ('no' === $value) { return false; } $message = sprintf('Expected "yes" or "no" for option "%s", other values are deprecated and support will be removed in 3.0. Got "%s", this implicitly set the option to "false".', $optionName, $value); if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new InvalidConfigurationException("{$message} This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); return false; } private static function separatedContextLessInclude($path) { return include $path; } } versionChecker = $versionChecker; $this->toolInfo = $toolInfo; $this->pharChecker = $pharChecker; } protected function configure() { $this ->setAliases(['selfupdate']) ->setDefinition( [ new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Force update to next major version if available.'), ] ) ->setDescription('Update php-cs-fixer.phar to the latest stable version.') ->setHelp( <<<'EOT' The %command.name% command replace your php-cs-fixer.phar by the latest version released on: https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases $ php php-cs-fixer.phar %command.name% EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { if (!$this->toolInfo->isInstalledAsPhar()) { $output->writeln('Self-update is available only for PHAR version.'); return 1; } $currentVersion = $this->getApplication()->getVersion(); Preg::match('/^v?(?\d+)\./', $currentVersion, $matches); $currentMajor = (int) $matches['major']; try { $latestVersion = $this->versionChecker->getLatestVersion(); $latestVersionOfCurrentMajor = $this->versionChecker->getLatestVersionOfMajor($currentMajor); } catch (\Exception $exception) { $output->writeln(sprintf( 'Unable to determine newest version: %s', $exception->getMessage() )); return 1; } if (1 !== $this->versionChecker->compareVersions($latestVersion, $currentVersion)) { $output->writeln('php-cs-fixer is already up to date.'); return 0; } $remoteTag = $latestVersion; if ( 0 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $latestVersion) && true !== $input->getOption('force') ) { $output->writeln(sprintf('A new major version of php-cs-fixer is available (%s)', $latestVersion)); $output->writeln(sprintf('Before upgrading please read https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/%s/UPGRADE.md', $latestVersion)); $output->writeln('If you are ready to upgrade run this command with -f'); $output->writeln('Checking for new minor/patch version...'); if (1 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $currentVersion)) { $output->writeln('No minor update for php-cs-fixer.'); return 0; } $remoteTag = $latestVersionOfCurrentMajor; } $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; if (!is_writable($localFilename)) { $output->writeln(sprintf('No permission to update %s file.', $localFilename)); return 1; } $tempFilename = \dirname($localFilename).'/'.basename($localFilename, '.phar').'-tmp.phar'; $remoteFilename = $this->toolInfo->getPharDownloadUri($remoteTag); if (false === @copy($remoteFilename, $tempFilename)) { $output->writeln(sprintf('Unable to download new version %s from the server.', $remoteTag)); return 1; } chmod($tempFilename, 0777 & ~umask()); $pharInvalidityReason = $this->pharChecker->checkFileValidity($tempFilename); if (null !== $pharInvalidityReason) { unlink($tempFilename); $output->writeln(sprintf('The download of %s is corrupt (%s).', $remoteTag, $pharInvalidityReason)); $output->writeln('Please re-run the self-update command to try again.'); return 1; } rename($tempFilename, $localFilename); $output->writeln(sprintf('php-cs-fixer updated (%s)', $remoteTag)); return 0; } } generator = new DocumentationGenerator(); } protected function configure() { $this ->setAliases(['doc']) ->setDescription('Dumps the documentation of the project into its /doc directory.') ; } protected function execute(InputInterface $input, OutputInterface $output) { $fixerFactory = new FixerFactory(); $fixerFactory->registerBuiltInFixers(); $fixers = $fixerFactory->getFixers(); $this->generateFixersDocs($fixers); $this->generateRuleSetsDocs($fixers); $output->writeln('Docs updated.'); return 0; } private function generateFixersDocs(array $fixers) { $filesystem = new Filesystem(); $docForFixerRelativePaths = []; foreach ($fixers as $fixer) { $docForFixerRelativePaths[] = $this->generator->getFixerDocumentationFileRelativePath($fixer); $filesystem->dumpFile( $this->generator->getFixerDocumentationFilePath($fixer), $this->generator->generateFixerDocumentation($fixer) ); } foreach ( (new Finder())->files() ->in($this->generator->getFixersDocumentationDirectoryPath()) ->notPath($docForFixerRelativePaths) as $file ) { $filesystem->remove($file->getPathname()); } $index = $this->generator->getFixersDocumentationIndexFilePath(); if (false === @file_put_contents($index, $this->generator->generateFixersDocumentationIndex($fixers))) { throw new \RuntimeException("Failed updating file {$index}."); } } private function generateRuleSetsDocs(array $fixers) { $filesystem = new Filesystem(); foreach ((new Finder())->files()->in($this->generator->getRuleSetsDocumentationDirectoryPath()) as $file) { $filesystem->remove($file->getPathname()); } $index = $this->generator->getRuleSetsDocumentationIndexFilePath(); $paths = []; foreach (RuleSets::getSetDefinitions() as $name => $definition) { $paths[$name] = $path = $this->generator->getRuleSetsDocumentationFilePath($name); $filesystem->dumpFile($path, $this->generator->generateRuleSetsDocumentation($definition, $fixers)); } if (false === @file_put_contents($index, $this->generator->generateRuleSetsDocumentationIndex($paths))) { throw new \RuntimeException("Failed updating file {$index}."); } } } %command.name% command tries to fix as much coding standards problems as possible on a given file or files in a given directory and its subdirectories: $ php %command.full_name% /path/to/dir $ php %command.full_name% /path/to/file By default --path-mode is set to `override`, which means, that if you specify the path to a file or a directory via command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use --path-mode=intersection to merge paths from the config file and from the argument: $ php %command.full_name% --path-mode=intersection /path/to/dir The --format option for the output format. Supported formats are `txt` (default one), `json`, `xml`, `checkstyle`, `junit` and `gitlab`. NOTE: the output for the following formats are generated in accordance with XML schemas * `checkstyle` follows the common `"checkstyle" xml schema `_ * `junit` follows the `JUnit xml schema from Jenkins `_ The --quiet Do not output any message. The --verbose option will show the applied rules. When using the `txt` format it will also display progress notifications. NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose * `-v`: verbose * `-vv`: very verbose * `-vvv`: debug The --rules option limits the rules to apply to the project: $ php %command.full_name% /path/to/project --rules=@PSR2 By default the PSR1 and PSR2 rules are used. The --rules option lets you choose the exact rules to apply (the rule names must be separated by a comma): $ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type You can also exclude the rules you don't want by placing a dash in front of the rule name, if this is more convenient, using -name_of_fixer: $ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type When using combinations of exact and exclude rules, applying exact rules along with above excluded results: $ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison Complete configuration for rules can be supplied using a `json` formatted string. $ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}' The --dry-run flag will run the fixer without making changes to your files. The --diff flag can be used to let the fixer output all the changes it makes. The --diff-format option allows to specify in which format the fixer should output the changes it makes: * udiff: unified diff format; * sbd: Sebastianbergmann/diff format (default when using `--diff` without specifying `diff-format`). The --allow-risky option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file. A rule is considered risky if it could change code behaviour. By default no risky rules are run. The --stop-on-violation flag stops the execution upon first file that needs to be fixed. The --show-progress option allows you to choose the way process progress is rendered: * none: disables progress output; * run-in: [deprecated] simple single-line progress output; * estimating: [deprecated] multiline progress output with number of files and percentage on each line. Note that with this option, the files list is evaluated before processing to get the total number of files and then kept in memory to avoid using the file iterator twice. This has an impact on memory usage so using this option is not recommended on very large projects; * estimating-max: [deprecated] same as dots; * dots: same as estimating but using all terminal columns instead of default 80. If the option is not provided, it defaults to run-in unless a config file that disables output is used, in which case it defaults to none. This option has no effect if the verbosity of the command is less than verbose. $ php %command.full_name% --verbose --show-progress=estimating The command can also read from standard input, in which case it won't automatically fix anything: $ cat foo.php | php %command.full_name% --diff - Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that would be default in next MAJOR release (unified differ, estimating, full-width progress indicator): $ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff Rules ----- Use the following command to quickly understand what a rule will do to your code: $ php php-cs-fixer.phar describe align_multiline_comment To visualize all the rules that belong to a ruleset: $ php php-cs-fixer.phar describe @PSR2 Choose from the list of available rules: %%%FIXERS_DETAILS%%% The --dry-run option displays the files that need to be fixed but without actually modifying them: $ php %command.full_name% /path/to/code --dry-run Config file ----------- Instead of using command line options to customize the rule, you can save the project configuration in a .php_cs.dist file in the root directory of your project. The file must return an instance of `PhpCsFixer\ConfigInterface` (%%%CONFIG_INTERFACE_URL%%%) which lets you configure the rules, the files and directories that need to be analyzed. You may also create .php_cs file, which is the local configuration that will be used instead of the project configuration. It is a good practice to add that file into your .gitignore file. With the --config option you can specify the path to the .php_cs file. The example below will add two rules to the default list of PSR2 set rules: exclude('somedir') ->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php') ->in(__DIR__) ; $config = new Config(); return $config ->setRules([ '@PSR2' => true, 'strict_param' => true, 'array_syntax' => ['syntax' => 'short'], ]) ->setFinder($finder) ; ?> **NOTE**: `exclude` will work only for directories, so if you need to exclude file, try `notPath`. Both `exclude` and `notPath` methods accept only relative paths to the ones defined with the `in` method. See `Symfony\Finder` (https://symfony.com/doc/current/components/finder.html) online documentation for other `Finder` methods. You may also use an exclude list for the rules instead of the above shown include approach. The following example shows how to use all `Symfony` rules but the `full_opening_tag` rule. exclude('somedir') ->in(__DIR__) ; $config = new Config(); return $config ->setRules([ '@Symfony' => true, 'full_opening_tag' => false, ]) ->setFinder($finder) ; ?> You may want to use non-linux whitespaces in your project. Then you need to configure them in your config file. setIndent("\t") ->setLineEnding("\r\n") ; ?> By using `--using-cache` option with `yes` or `no` you can set if the caching mechanism should be used. Caching ------- The caching mechanism is enabled by default. This will speed up further runs by fixing only files that were modified since the last run. The tool will fix all files if the tool version has changed or the list of rules has changed. Cache is supported only for tool downloaded as phar file or installed via composer. Cache can be disabled via `--using-cache` option or config file: setUsingCache(false); ?> Cache file can be specified via `--cache-file` option or config file: setCacheFile(__DIR__.'/.php_cs.cache'); ?> Using PHP CS Fixer on CI ------------------------ Require `friendsofphp/php-cs-fixer` as a `dev` dependency: $ ./composer.phar require --dev friendsofphp/php-cs-fixer Then, add the following command to your CI: %%%CI_INTEGRATION%%% Where `$COMMIT_RANGE` is your range of commits, e.g. `$TRAVIS_COMMIT_RANGE` or `HEAD~..HEAD`. Exit code --------- Exit code of the fix command is built using following bit flags: * 0 - OK. * 1 - General error (or PHP minimal requirement not matched). * 4 - Some files have invalid syntax (only in dry-run mode). * 8 - Some files need fixing (only in dry-run mode). * 16 - Configuration error of the application. * 32 - Configuration error of a Fixer. * 64 - Exception raised within the application. EOF ; return strtr($template, [ '%%%CONFIG_INTERFACE_URL%%%' => sprintf( 'https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/v%s/src/ConfigInterface.php', self::getLatestReleaseVersionFromChangeLog() ), '%%%CI_INTEGRATION%%%' => implode("\n", array_map( static function ($line) { return ' $ '.$line; }, \array_slice(file(__DIR__.'/../../../ci-integration.sh', FILE_IGNORE_NEW_LINES), 3) )), '%%%FIXERS_DETAILS%%%' => self::getFixersHelp(), ]); } public static function toString($value) { return \is_array($value) ? static::arrayToString($value) : static::scalarToString($value) ; } public static function getDisplayableAllowedValues(FixerOptionInterface $option) { $allowed = $option->getAllowedValues(); if (null !== $allowed) { $allowed = array_filter($allowed, static function ($value) { return !($value instanceof \Closure); }); usort($allowed, static function ($valueA, $valueB) { if ($valueA instanceof AllowedValueSubset) { return -1; } if ($valueB instanceof AllowedValueSubset) { return 1; } return strcasecmp( self::toString($valueA), self::toString($valueB) ); }); if (0 === \count($allowed)) { $allowed = null; } } return $allowed; } public static function getLatestReleaseVersionFromChangeLog() { static $version = null; if (null !== $version) { return $version; } $changelogFile = self::getChangeLogFile(); if (null === $changelogFile) { $version = Application::VERSION; return $version; } $changelog = @file_get_contents($changelogFile); if (false === $changelog) { $error = error_get_last(); throw new \RuntimeException(sprintf( 'Failed to read content of the changelog file "%s".%s', $changelogFile, $error ? ' '.$error['message'] : '' )); } for ($i = Application::getMajorVersion(); $i > 0; --$i) { if (1 === Preg::match('/Changelog for v('.$i.'.\d+.\d+)/', $changelog, $matches)) { $version = $matches[1]; break; } } if (null === $version) { throw new \RuntimeException(sprintf('Failed to parse changelog data of "%s".', $changelogFile)); } return $version; } protected function initialize(InputInterface $input, OutputInterface $output) { $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue')); } private static function getChangeLogFile() { $changelogFile = __DIR__.'/../../../CHANGELOG.md'; return is_file($changelogFile) ? $changelogFile : null; } private static function getFixersHelp() { $help = ''; $fixerFactory = new FixerFactory(); $fixers = $fixerFactory->registerBuiltInFixers()->getFixers(); usort( $fixers, static function (FixerInterface $a, FixerInterface $b) { return strcmp($a->getName(), $b->getName()); } ); $ruleSets = []; foreach (RuleSets::getSetDefinitionNames() as $setName) { $ruleSets[$setName] = new RuleSet([$setName => true]); } $getSetsWithRule = static function ($rule) use ($ruleSets) { $sets = []; foreach ($ruleSets as $setName => $ruleSet) { if ($ruleSet->hasRule($rule)) { $sets[] = $setName; } } return $sets; }; $count = \count($fixers) - 1; foreach ($fixers as $i => $fixer) { $sets = $getSetsWithRule($fixer->getName()); $description = $fixer->getDefinition()->getSummary(); if ($fixer instanceof DeprecatedFixerInterface) { $successors = $fixer->getSuccessorsNames(); $message = [] === $successors ? 'will be removed on next major version' : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors)); $description .= sprintf(' DEPRECATED: %s.', $message); } $description = implode("\n | ", self::wordwrap( Preg::replace('/(`.+?`)/', '$1', $description), 72 )); if (!empty($sets)) { $help .= sprintf(" * %s [%s]\n | %s\n", $fixer->getName(), implode(', ', $sets), $description); } else { $help .= sprintf(" * %s\n | %s\n", $fixer->getName(), $description); } if ($fixer->isRisky()) { $help .= sprintf( " | *Risky rule: %s.*\n", Preg::replace( '/(`.+?`)/', '$1', lcfirst(Preg::replace('/\.$/', '', $fixer->getDefinition()->getRiskyDescription())) ) ); } if ($fixer instanceof ConfigurationDefinitionFixerInterface) { $configurationDefinition = $fixer->getConfigurationDefinition(); $configurationDefinitionOptions = $configurationDefinition->getOptions(); if (\count($configurationDefinitionOptions)) { $help .= " |\n | Configuration options:\n"; usort( $configurationDefinitionOptions, static function (FixerOptionInterface $optionA, FixerOptionInterface $optionB) { return strcmp($optionA->getName(), $optionB->getName()); } ); foreach ($configurationDefinitionOptions as $option) { $line = ''.OutputFormatter::escape($option->getName()).''; $allowed = self::getDisplayableAllowedValues($option); if (null !== $allowed) { foreach ($allowed as &$value) { if ($value instanceof AllowedValueSubset) { $value = 'a subset of '.self::toString($value->getAllowedValues()).''; } else { $value = ''.self::toString($value).''; } } } else { $allowed = array_map( static function ($type) { return ''.$type.''; }, $option->getAllowedTypes() ); } if (null !== $allowed) { $line .= ' ('.implode(', ', $allowed).')'; } $line .= ': '.Preg::replace( '/(`.+?`)/', '$1', lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDescription()))) ).'; '; if ($option->hasDefault()) { $line .= 'defaults to '.self::toString($option->getDefault()).''; } else { $line .= 'required'; } if ($option instanceof DeprecatedFixerOption) { $line .= '. DEPRECATED: '.Preg::replace( '/(`.+?`)/', '$1', lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDeprecationMessage()))) ); } if ($option instanceof AliasedFixerOption) { $line .= '; DEPRECATED alias: '.$option->getAlias().''; } foreach (self::wordwrap($line, 72) as $index => $line) { $help .= (0 === $index ? ' | - ' : ' | ').$line."\n"; } } } } elseif ($fixer instanceof ConfigurableFixerInterface) { $help .= " | *Configurable rule.*\n"; } if ($count !== $i) { $help .= "\n"; } } return Preg::replace('#\\\\()#', '<<$1', $help); } private static function wordwrap($string, $width) { $result = []; $currentLine = 0; $lineLength = 0; foreach (explode(' ', $string) as $word) { $wordLength = \strlen(Preg::replace('~~', '', $word)); if (0 !== $lineLength) { ++$wordLength; } if ($lineLength + $wordLength > $width) { ++$currentLine; $lineLength = 0; } $result[$currentLine][] = $word; $lineLength += $wordLength; } return array_map(static function ($line) { return implode(' ', $line); }, $result); } private static function scalarToString($value) { $str = var_export($value, true); return Preg::replace('/\bNULL\b/', 'null', $str); } private static function arrayToString(array $value) { if (0 === \count($value)) { return '[]'; } $isHash = static::isHash($value); $str = '['; foreach ($value as $k => $v) { if ($isHash) { $str .= static::scalarToString($k).' => '; } $str .= \is_array($v) ? static::arrayToString($v).', ' : static::scalarToString($v).', ' ; } return substr($str, 0, -2).']'; } private static function isHash(array $array) { $i = 0; foreach ($array as $k => $v) { if ($k !== $i) { return true; } ++$i; } return false; } } defaultConfig = new Config(); $this->errorsManager = new ErrorsManager(); $this->eventDispatcher = new EventDispatcher(); $this->stopwatch = new Stopwatch(); $this->toolInfo = $toolInfo; } public function getHelp() { return HelpCommand::getHelpCopy(); } protected function configure() { $this ->setDefinition( [ new InputArgument('path', InputArgument::IS_ARRAY, 'The path.'), new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, 'Specify path mode (can be override or intersection).', 'override'), new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, 'Are risky fixers allowed (can be yes or no).'), new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php_cs file.'), new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'), new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'The rules.'), new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, 'Does cache should be used (can be yes or no).'), new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'), new InputOption('diff', '', InputOption::VALUE_NONE, 'Also produce diff for each file.'), new InputOption('diff-format', '', InputOption::VALUE_REQUIRED, 'Specify diff format.'), new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.'), new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'), new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, 'Type of progress indicator (none, run-in, estimating, estimating-max or dots).'), ] ) ->setDescription('Fixes a directory or a file.') ; } protected function execute(InputInterface $input, OutputInterface $output) { $verbosity = $output->getVerbosity(); $passedConfig = $input->getOption('config'); $passedRules = $input->getOption('rules'); $resolver = new ConfigurationResolver( $this->defaultConfig, [ 'allow-risky' => $input->getOption('allow-risky'), 'config' => $passedConfig, 'dry-run' => $input->getOption('dry-run'), 'rules' => $passedRules, 'path' => $input->getArgument('path'), 'path-mode' => $input->getOption('path-mode'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file'), 'format' => $input->getOption('format'), 'diff' => $input->getOption('diff'), 'diff-format' => $input->getOption('diff-format'), 'stop-on-violation' => $input->getOption('stop-on-violation'), 'verbosity' => $verbosity, 'show-progress' => $input->getOption('show-progress'), ], getcwd(), $this->toolInfo ); $reporter = $resolver->getReporter(); $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ('txt' === $reporter->getFormat() ? $output : null) ; if (null !== $stdErr) { if (null !== $passedConfig && null !== $passedRules) { if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new \RuntimeException('Passing both `config` and `rules` options is not possible. This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set.'); } $stdErr->writeln([ sprintf($stdErr->isDecorated() ? '%s' : '%s', 'When passing both "--config" and "--rules" the rules within the configuration file are not used.'), sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Passing both options is deprecated; version v3.0 PHP-CS-Fixer will exit with a configuration error code.'), ]); } $configFile = $resolver->getConfigFile(); $stdErr->writeln(sprintf('Loaded config %s%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"')); if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $stdErr->writeln(sprintf('Runtime: PHP %s', PHP_VERSION)); } if ($resolver->getUsingCache()) { $cacheFile = $resolver->getCacheFile(); if (is_file($cacheFile)) { $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile)); } } } $progressType = $resolver->getProgress(); $finder = $resolver->getFinder(); if (null !== $stdErr && $resolver->configFinderIsOverridden()) { $stdErr->writeln( sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.') ); } if ('none' === $progressType || null === $stdErr) { $progressOutput = new NullOutput(); } elseif ('run-in' === $progressType) { $progressOutput = new ProcessOutput($stdErr, $this->eventDispatcher, null, null); } else { $finder = new \ArrayIterator(iterator_to_array($finder)); $progressOutput = new ProcessOutput( $stdErr, $this->eventDispatcher, 'estimating' !== $progressType ? (new Terminal())->getWidth() : null, \count($finder) ); } $runner = new Runner( $finder, $resolver->getFixers(), $resolver->getDiffer(), 'none' !== $progressType ? $this->eventDispatcher : null, $this->errorsManager, $resolver->getLinter(), $resolver->isDryRun(), $resolver->getCacheManager(), $resolver->getDirectory(), $resolver->shouldStopOnViolation() ); $this->stopwatch->start('fixFiles'); $changed = $runner->fix(); $this->stopwatch->stop('fixFiles'); $progressOutput->printLegend(); $fixEvent = $this->stopwatch->getEvent('fixFiles'); $reportSummary = new ReportSummary( $changed, $fixEvent->getDuration(), $fixEvent->getMemory(), OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity(), $resolver->isDryRun(), $output->isDecorated() ); $output->isDecorated() ? $output->write($reporter->generate($reportSummary)) : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW) ; $invalidErrors = $this->errorsManager->getInvalidErrors(); $exceptionErrors = $this->errorsManager->getExceptionErrors(); $lintErrors = $this->errorsManager->getLintErrors(); if (null !== $stdErr) { $errorOutput = new ErrorOutput($stdErr); if (\count($invalidErrors) > 0) { $errorOutput->listErrors('linting before fixing', $invalidErrors); } if (\count($exceptionErrors) > 0) { $errorOutput->listErrors('fixing', $exceptionErrors); } if (\count($lintErrors) > 0) { $errorOutput->listErrors('linting after fixing', $lintErrors); } } $exitStatusCalculator = new FixCommandExitStatusCalculator(); return $exitStatusCalculator->calculate( $resolver->isDryRun(), \count($changed) > 0, \count($invalidErrors) > 0, \count($exceptionErrors) > 0, \count($lintErrors) > 0 ); } } name = $name; $this->type = $type; parent::__construct(); } public function getName() { return $this->name; } public function getType() { return $this->type; } } registerBuiltInFixers(); } $this->fixerFactory = $fixerFactory; } protected function configure() { $this ->setDefinition( [ new InputArgument('name', InputArgument::REQUIRED, 'Name of rule / set.'), ] ) ->setDescription('Describe rule / ruleset.') ; } protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); try { if ('@' === $name[0]) { $this->describeSet($output, $name); return 0; } $this->describeRule($output, $name); } catch (DescribeNameNotFoundException $e) { $matcher = new WordMatcher( 'set' === $e->getType() ? $this->getSetNames() : array_keys($this->getFixers()) ); $alternative = $matcher->match($name); $this->describeList($output, $e->getType()); throw new \InvalidArgumentException(sprintf( '%s "%s" not found.%s', ucfirst($e->getType()), $name, null === $alternative ? '' : ' Did you mean "'.$alternative.'"?' )); } return 0; } private function describeRule(OutputInterface $output, $name) { $fixers = $this->getFixers(); if (!isset($fixers[$name])) { throw new DescribeNameNotFoundException($name, 'rule'); } $fixer = $fixers[$name]; if ($fixer instanceof DefinedFixerInterface) { $definition = $fixer->getDefinition(); } else { $definition = new FixerDefinition('Description is not available.', []); } $description = $definition->getSummary(); if ($fixer instanceof DeprecatedFixerInterface) { $successors = $fixer->getSuccessorsNames(); $message = [] === $successors ? 'will be removed on next major version' : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors)); $message = Preg::replace('/(`.+?`)/', '$1', $message); $description .= sprintf(' DEPRECATED: %s.', $message); } $output->writeln(sprintf('Description of %s rule.', $name)); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln(sprintf('Fixer class: %s.', \get_class($fixer))); } $output->writeln($description); if ($definition->getDescription()) { $output->writeln($definition->getDescription()); } $output->writeln(''); if ($fixer->isRisky()) { $output->writeln('Fixer applying this rule is risky.'); if ($definition->getRiskyDescription()) { $output->writeln($definition->getRiskyDescription()); } $output->writeln(''); } if ($fixer instanceof ConfigurationDefinitionFixerInterface) { $configurationDefinition = $fixer->getConfigurationDefinition(); $options = $configurationDefinition->getOptions(); $output->writeln(sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's')); foreach ($options as $option) { $line = '* '.OutputFormatter::escape($option->getName()).''; $allowed = HelpCommand::getDisplayableAllowedValues($option); if (null !== $allowed) { foreach ($allowed as &$value) { if ($value instanceof AllowedValueSubset) { $value = 'a subset of '.HelpCommand::toString($value->getAllowedValues()).''; } else { $value = ''.HelpCommand::toString($value).''; } } } else { $allowed = array_map( static function ($type) { return ''.$type.''; }, $option->getAllowedTypes() ); } if (null !== $allowed) { $line .= ' ('.implode(', ', $allowed).')'; } $description = Preg::replace('/(`.+?`)/', '$1', OutputFormatter::escape($option->getDescription())); $line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; '; if ($option->hasDefault()) { $line .= sprintf( 'defaults to %s', HelpCommand::toString($option->getDefault()) ); } else { $line .= 'required'; } if ($option instanceof DeprecatedFixerOption) { $line .= '. DEPRECATED: '.Preg::replace( '/(`.+?`)/', '$1', OutputFormatter::escape(lcfirst($option->getDeprecationMessage())) ); } if ($option instanceof AliasedFixerOption) { $line .= '; DEPRECATED alias: '.$option->getAlias().''; } $output->writeln($line); } $output->writeln(''); } elseif ($fixer instanceof ConfigurableFixerInterface) { $output->writeln('Fixer is configurable.'); if ($definition->getConfigurationDescription()) { $output->writeln($definition->getConfigurationDescription()); } if ($definition->getDefaultConfiguration()) { $output->writeln(sprintf('Default configuration: %s.', HelpCommand::toString($definition->getDefaultConfiguration()))); } $output->writeln(''); } $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample) { if ($codeSample instanceof VersionSpecificCodeSampleInterface) { return $codeSample->isSuitableFor(\PHP_VERSION_ID); } return true; }); if (!\count($codeSamples)) { $output->writeln([ 'Fixing examples can not be demonstrated on the current PHP version.', '', ]); } else { $output->writeln('Fixing examples:'); $differ = new FullDiffer(); $diffFormatter = new DiffConsoleFormatter( $output->isDecorated(), sprintf( ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', PHP_EOL, PHP_EOL ) ); foreach ($codeSamples as $index => $codeSample) { $old = $codeSample->getCode(); $tokens = Tokens::fromCode($old); $configuration = $codeSample->getConfiguration(); if ($fixer instanceof ConfigurableFixerInterface) { $fixer->configure(null === $configuration ? [] : $configuration); } $file = $codeSample instanceof FileSpecificCodeSampleInterface ? $codeSample->getSplFileInfo() : new StdinFileInfo(); $fixer->fix($file, $tokens); $diff = $differ->diff($old, $tokens->generateCode()); if ($fixer instanceof ConfigurableFixerInterface) { if (null === $configuration) { $output->writeln(sprintf(' * Example #%d. Fixing with the default configuration.', $index + 1)); } else { $output->writeln(sprintf(' * Example #%d. Fixing with configuration: %s.', $index + 1, HelpCommand::toString($codeSample->getConfiguration()))); } } else { $output->writeln(sprintf(' * Example #%d.', $index + 1)); } $output->writeln($diffFormatter->format($diff, ' %s')); $output->writeln(''); } } } private function describeSet(OutputInterface $output, $name) { if (!\in_array($name, $this->getSetNames(), true)) { throw new DescribeNameNotFoundException($name, 'set'); } $ruleSetDefinitions = RuleSets::getSetDefinitions(); $fixers = $this->getFixers(); $output->writeln(sprintf('Description of the %s set.', $ruleSetDefinitions[$name]->getName())); $output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription())); if ($ruleSetDefinitions[$name]->isRisky()) { $output->writeln('This set contains risky rules.'); } $output->writeln(''); $help = ''; foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) { if ('@' === $rule[0]) { $set = $ruleSetDefinitions[$rule]; $help .= sprintf( " * %s%s\n | %s\n\n", $rule, $set->isRisky() ? ' risky' : '', $this->replaceRstLinks($set->getDescription()) ); continue; } $fixer = $fixers[$rule]; if (!$fixer instanceof DefinedFixerInterface) { throw new \RuntimeException(sprintf( 'Cannot describe rule %s, the fixer does not implement %s', $rule, DefinedFixerInterface::class )); } $definition = $fixer->getDefinition(); $help .= sprintf( " * %s%s\n | %s\n%s\n", $rule, $fixer->isRisky() ? ' risky' : '', $definition->getSummary(), true !== $config ? sprintf(" | Configuration: %s\n", HelpCommand::toString($config)) : '' ); } $output->write($help); } private function getFixers() { if (null !== $this->fixers) { return $this->fixers; } $fixers = []; foreach ($this->fixerFactory->getFixers() as $fixer) { $fixers[$fixer->getName()] = $fixer; } $this->fixers = $fixers; ksort($this->fixers); return $this->fixers; } private function getSetNames() { if (null !== $this->setNames) { return $this->setNames; } $this->setNames = RuleSets::getSetDefinitionNames(); return $this->setNames; } private function describeList(OutputInterface $output, $type) { if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $describe = [ 'set' => $this->getSetNames(), 'rules' => $this->getFixers(), ]; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $describe = 'set' === $type ? ['set' => $this->getSetNames()] : ['rules' => $this->getFixers()]; } else { return; } foreach ($describe as $list => $items) { $output->writeln(sprintf('Defined %s:', $list)); foreach ($items as $name => $item) { $output->writeln(sprintf('* %s', \is_string($name) ? $name : $item)); } } } private function replaceRstLinks($content) { return Preg::replaceCallback( '/(`[^<]+<[^>]+>`_)/', static function (array $matches) { return Preg::replaceCallback( '/`(.*)<(.*)>`_/', static function (array $matches) { return $matches[1].'('.$matches[2].')'; }, $matches[1] ); }, $content ); } } githubClient = $githubClient; $this->versionParser = new VersionParser(); } public function getLatestVersion() { $this->retrieveAvailableVersions(); return $this->availableVersions[0]; } public function getLatestVersionOfMajor($majorVersion) { $this->retrieveAvailableVersions(); $semverConstraint = '^'.$majorVersion; foreach ($this->availableVersions as $availableVersion) { if (Semver::satisfies($availableVersion, $semverConstraint)) { return $availableVersion; } } return null; } public function compareVersions($versionA, $versionB) { $versionA = $this->versionParser->normalize($versionA); $versionB = $this->versionParser->normalize($versionB); if (Comparator::lessThan($versionA, $versionB)) { return -1; } if (Comparator::greaterThan($versionA, $versionB)) { return 1; } return 0; } private function retrieveAvailableVersions() { if (null !== $this->availableVersions) { return; } foreach ($this->githubClient->getTags() as $tag) { $version = $tag['name']; try { $this->versionParser->normalize($version); if ('stable' === VersionParser::parseStability($version)) { $this->availableVersions[] = $version; } } catch (\UnexpectedValueException $exception) { } } $this->availableVersions = Semver::rsort($this->availableVersions); } } [ 'header' => 'User-Agent: FriendsOfPHP/PHP-CS-Fixer', ], ]) ); if (false === $result) { throw new \RuntimeException(sprintf('Failed to load tags at "%s".', $url)); } $result = json_decode($result, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new \RuntimeException(sprintf( 'Failed to read response from "%s" as JSON: %s.', $url, json_last_error_msg() )); } return $result; } } createProxyFixers()) as $proxyFixer) { $this->proxyFixers[$proxyFixer->getName()] = $proxyFixer; } parent::__construct(); } public function isCandidate(Tokens $tokens) { foreach ($this->proxyFixers as $fixer) { if ($fixer->isCandidate($tokens)) { return true; } } return false; } public function isRisky() { foreach ($this->proxyFixers as $fixer) { if ($fixer->isRisky()) { return true; } } return false; } public function getPriority() { if (\count($this->proxyFixers) > 1) { throw new \LogicException('You need to override this method to provide the priority of combined fixers.'); } return reset($this->proxyFixers)->getPriority(); } public function supports(\SplFileInfo $file) { foreach ($this->proxyFixers as $fixer) { if ($fixer->supports($file)) { return true; } } return false; } public function setWhitespacesConfig(WhitespacesFixerConfig $config) { parent::setWhitespacesConfig($config); foreach ($this->proxyFixers as $fixer) { if ($fixer instanceof WhitespacesAwareFixerInterface) { $fixer->setWhitespacesConfig($config); } } } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($this->proxyFixers as $fixer) { $fixer->fix($file, $tokens); } } abstract protected function createProxyFixers(); } nameValidator = new FixerNameValidator(); } public static function create() { return new self(); } public function setWhitespacesConfig(WhitespacesFixerConfig $config) { foreach ($this->fixers as $fixer) { if ($fixer instanceof WhitespacesAwareFixerInterface) { $fixer->setWhitespacesConfig($config); } } return $this; } public function getFixers() { $this->fixers = Utils::sortFixers($this->fixers); return $this->fixers; } public function registerBuiltInFixers() { static $builtInFixers = null; if (null === $builtInFixers) { $builtInFixers = []; foreach (SymfonyFinder::create()->files()->in(__DIR__.'/Fixer')->depth(1) as $file) { $relativeNamespace = $file->getRelativePath(); $fixerClass = 'PhpCsFixer\\Fixer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); if ('Fixer' === substr($fixerClass, -5)) { $builtInFixers[] = $fixerClass; } } } foreach ($builtInFixers as $class) { $this->registerFixer(new $class(), false); } return $this; } public function registerCustomFixers(array $fixers) { foreach ($fixers as $fixer) { $this->registerFixer($fixer, true); } return $this; } public function registerFixer(FixerInterface $fixer, $isCustom) { $name = $fixer->getName(); if (isset($this->fixersByName[$name])) { throw new \UnexpectedValueException(sprintf('Fixer named "%s" is already registered.', $name)); } if (!$this->nameValidator->isValid($name, $isCustom)) { throw new \UnexpectedValueException(sprintf('Fixer named "%s" has invalid name.', $name)); } $this->fixers[] = $fixer; $this->fixersByName[$name] = $fixer; return $this; } public function useRuleSet(RuleSetInterface $ruleSet) { $fixers = []; $fixersByName = []; $fixerConflicts = []; $fixerNames = array_keys($ruleSet->getRules()); foreach ($fixerNames as $name) { if (!\array_key_exists($name, $this->fixersByName)) { throw new \UnexpectedValueException(sprintf('Rule "%s" does not exist.', $name)); } $fixer = $this->fixersByName[$name]; $config = $ruleSet->getRuleConfiguration($name); if (null !== $config) { if ($fixer instanceof ConfigurableFixerInterface) { if (!\is_array($config) || !\count($config)) { throw new InvalidFixerConfigurationException($fixer->getName(), 'Configuration must be an array and may not be empty.'); } $fixer->configure($config); } else { throw new InvalidFixerConfigurationException($fixer->getName(), 'Is not configurable.'); } } $fixers[] = $fixer; $fixersByName[$name] = $fixer; $conflicts = array_intersect($this->getFixersConflicts($fixer), $fixerNames); if (\count($conflicts) > 0) { $fixerConflicts[$name] = $conflicts; } } if (\count($fixerConflicts) > 0) { throw new \UnexpectedValueException($this->generateConflictMessage($fixerConflicts)); } $this->fixers = $fixers; $this->fixersByName = $fixersByName; return $this; } public function hasRule($name) { return isset($this->fixersByName[$name]); } private function getFixersConflicts(FixerInterface $fixer) { static $conflictMap = [ 'no_blank_lines_before_namespace' => ['single_blank_line_before_namespace'], ]; $fixerName = $fixer->getName(); return \array_key_exists($fixerName, $conflictMap) ? $conflictMap[$fixerName] : []; } private function generateConflictMessage(array $fixerConflicts) { $message = 'Rule contains conflicting fixers:'; $report = []; foreach ($fixerConflicts as $fixer => $fixers) { $report[$fixer] = array_filter( $fixers, static function ($candidate) use ($report, $fixer) { return !\array_key_exists($candidate, $report) || !\in_array($fixer, $report[$candidate], true); } ); if (\count($report[$fixer]) > 0) { $message .= sprintf("\n- \"%s\" with \"%s\"", $fixer, implode('", "', $report[$fixer])); } } return $message; } } getMessage(); } return null; } } linter = $linter; } public function currentLintingResult() { return $this->currentResult; } public function next() { parent::next(); $this->currentResult = $this->nextResult; if ($this->hasNext()) { $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); } } public function rewind() { parent::rewind(); if ($this->valid()) { $this->currentResult = $this->handleItem($this->current()); } if ($this->hasNext()) { $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); } } private function handleItem(\SplFileInfo $file) { return $this->linter->lintFile($file->getRealPath()); } } finder = $finder; $this->fixers = $fixers; $this->differ = $differ; $this->eventDispatcher = $eventDispatcher; $this->errorsManager = $errorsManager; $this->linter = $linter; $this->isDryRun = $isDryRun; $this->cacheManager = $cacheManager; $this->directory = $directory ?: new Directory(''); $this->stopOnViolation = $stopOnViolation; } public function fix() { $changed = []; $finder = $this->finder; $finderIterator = $finder instanceof \IteratorAggregate ? $finder->getIterator() : $finder; $fileFilteredFileIterator = new FileFilterIterator( $finderIterator, $this->eventDispatcher, $this->cacheManager ); $collection = $this->linter->isAsync() ? new FileCachingLintingIterator($fileFilteredFileIterator, $this->linter) : new FileLintingIterator($fileFilteredFileIterator, $this->linter); foreach ($collection as $file) { $fixInfo = $this->fixFile($file, $collection->currentLintingResult()); Tokens::clearCache(); if ($fixInfo) { $name = $this->directory->getRelativePathTo($file); $changed[$name] = $fixInfo; if ($this->stopOnViolation) { break; } } } return $changed; } private function fixFile(\SplFileInfo $file, LintingResultInterface $lintingResult) { $name = $file->getPathname(); try { $lintingResult->check(); } catch (LintingException $e) { $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_INVALID) ); $this->errorsManager->report(new Error(Error::TYPE_INVALID, $name, $e)); return; } $old = FileReader::createSingleton()->read($file->getRealPath()); Tokens::setLegacyMode(false); $tokens = Tokens::fromCode($old); $oldHash = $tokens->getCodeHash(); $newHash = $oldHash; $new = $old; $appliedFixers = []; try { foreach ($this->fixers as $fixer) { if ( !$fixer instanceof AbstractFixer && (!$fixer->supports($file) || !$fixer->isCandidate($tokens)) ) { continue; } $fixer->fix($file, $tokens); if ($tokens->isChanged()) { $tokens->clearEmptyTokens(); $tokens->clearChanged(); $appliedFixers[] = $fixer->getName(); } } } catch (\Exception $e) { $this->processException($name, $e); return; } catch (\ParseError $e) { $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_LINT) ); $this->errorsManager->report(new Error(Error::TYPE_LINT, $name, $e)); return; } catch (\Throwable $e) { $this->processException($name, $e); return; } $fixInfo = null; if (!empty($appliedFixers)) { $new = $tokens->generateCode(); $newHash = $tokens->getCodeHash(); } if ($oldHash !== $newHash) { $fixInfo = [ 'appliedFixers' => $appliedFixers, 'diff' => $this->differ->diff($old, $new), ]; try { $this->linter->lintSource($new)->check(); } catch (LintingException $e) { $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_LINT) ); $this->errorsManager->report(new Error(Error::TYPE_LINT, $name, $e, $fixInfo['appliedFixers'], $fixInfo['diff'])); return; } if (!$this->isDryRun) { $fileName = $file->getRealPath(); if (!file_exists($fileName)) { throw new IOException( sprintf('Failed to write file "%s" (no longer) exists.', $file->getPathname()), 0, null, $file->getPathname() ); } if (is_dir($fileName)) { throw new IOException( sprintf('Cannot write file "%s" as the location exists as directory.', $fileName), 0, null, $fileName ); } if (!is_writable($fileName)) { throw new IOException( sprintf('Cannot write to file "%s" as it is not writable.', $fileName), 0, null, $fileName ); } if (false === @file_put_contents($fileName, $new)) { $error = error_get_last(); throw new IOException( sprintf('Failed to write file "%s", "%s".', $fileName, $error ? $error['message'] : 'no reason available'), 0, null, $file ); } } } $this->cacheManager->setFile($name, $new); $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent($fixInfo ? FixerFileProcessedEvent::STATUS_FIXED : FixerFileProcessedEvent::STATUS_NO_CHANGES) ); return $fixInfo; } private function processException($name, $e) { $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_EXCEPTION) ); $this->errorsManager->report(new Error(Error::TYPE_EXCEPTION, $name, $e)); } private function dispatchEvent($name, Event $event) { if (null === $this->eventDispatcher) { return; } if ( !$this->eventDispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface ) { $this->eventDispatcher->dispatch($name, $event); return; } $this->eventDispatcher->dispatch($event, $name); } } linter = $linter; } public function currentLintingResult() { return $this->currentResult; } public function next() { parent::next(); $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; } public function rewind() { parent::rewind(); $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; } private function handleItem(\SplFileInfo $file) { return $this->linter->lintFile($file->getRealPath()); } } eventDispatcher = $eventDispatcher; $this->cacheManager = $cacheManager; } public function accept() { $file = $this->current(); if (!$file instanceof \SplFileInfo) { throw new \RuntimeException( sprintf( 'Expected instance of "\SplFileInfo", got "%s".', \is_object($file) ? \get_class($file) : \gettype($file) ) ); } $path = $file->isLink() ? $file->getPathname() : $file->getRealPath(); if (isset($this->visitedElements[$path])) { return false; } $this->visitedElements[$path] = true; if (!$file->isFile() || $file->isLink()) { return false; } $content = FileReader::createSingleton()->read($path); if ( '' === $content || !$this->cacheManager->needFixing($file->getPathname(), $content) ) { $this->dispatchEvent( FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_SKIPPED) ); return false; } return true; } private function dispatchEvent($name, Event $event) { if (null === $this->eventDispatcher) { return; } if ( !$this->eventDispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface ) { $this->eventDispatcher->dispatch($name, $event); return; } $this->eventDispatcher->dispatch($event, $name); } } find(false); if (false === $executable) { throw new UnavailableLinterException('Cannot find PHP executable.'); } if ('phpdbg' === \PHP_SAPI) { if (false === strpos($executable, 'phpdbg')) { throw new UnavailableLinterException('Automatically found PHP executable is non-standard phpdbg. Could not find proper PHP executable.'); } $executable = str_replace('phpdbg', 'php', $executable); if (!is_executable($executable)) { throw new UnavailableLinterException('Automatically found PHP executable is phpdbg. Could not find proper PHP executable.'); } } } $this->processBuilder = new ProcessLinterProcessBuilder($executable); $this->fileRemoval = new FileRemoval(); } public function __destruct() { if (null !== $this->temporaryFile) { $this->fileRemoval->delete($this->temporaryFile); } } public function isAsync() { return true; } public function lintFile($path) { return new ProcessLintingResult($this->createProcessForFile($path), $path); } public function lintSource($source) { return new ProcessLintingResult($this->createProcessForSource($source), $this->temporaryFile); } private function createProcessForFile($path) { if (!is_file($path)) { return $this->createProcessForSource(FileReader::createSingleton()->read($path)); } $process = $this->processBuilder->build($path); $process->setTimeout(10); $process->start(); return $process; } private function createProcessForSource($source) { if (null === $this->temporaryFile) { $this->temporaryFile = tempnam(sys_get_temp_dir(), 'cs_fixer_tmp_'); $this->fileRemoval->observe($this->temporaryFile); } if (false === @file_put_contents($this->temporaryFile, $source)) { throw new IOException(sprintf('Failed to write file "%s".', $this->temporaryFile), 0, null, $this->temporaryFile); } return $this->createProcessForFile($this->temporaryFile); } } process = $process; $this->path = $path; } public function check() { if (!$this->isSuccessful()) { throw new LintingException($this->getProcessErrorMessage(), $this->process->getExitCode()); } } private function getProcessErrorMessage() { $output = strtok(ltrim($this->process->getErrorOutput() ?: $this->process->getOutput()), "\n"); if (false === $output) { return 'Fatal error: Unable to lint file.'; } if (null !== $this->path) { $needle = sprintf('in %s ', $this->path); $pos = strrpos($output, $needle); if (false !== $pos) { $output = sprintf('%s%s', substr($output, 0, $pos), substr($output, $pos + \strlen($needle))); } } $prefix = substr($output, 0, 18); if ('PHP Parse error: ' === $prefix) { return sprintf('Parse error: %s.', substr($output, 18)); } if ('PHP Fatal error: ' === $prefix) { return sprintf('Fatal error: %s.', substr($output, 18)); } return sprintf('%s.', $output); } private function isSuccessful() { if (null === $this->isSuccessful) { $this->process->wait(); $this->isSuccessful = $this->process->isSuccessful(); } return $this->isSuccessful; } } executable = $executable; } public function build($path) { return new Process([ $this->executable, '-l', $path, ]); } } lintSource(FileReader::createSingleton()->read($path)); } public function lintSource($source) { try { $codeHash = CodeHasher::calculateCodeHash($source); Tokens::clearCache($codeHash); Tokens::fromCode($source); return new TokenizerLintingResult(); } catch (\ParseError $e) { return new TokenizerLintingResult($e); } catch (\CompileError $e) { return new TokenizerLintingResult($e); } } } sublinter = new TokenizerLinter(); } catch (UnavailableLinterException $e) { $this->sublinter = new ProcessLinter($executable); } } public function isAsync() { return $this->sublinter->isAsync(); } public function lintFile($path) { return $this->sublinter->lintFile($path); } public function lintSource($source) { return $this->sublinter->lintSource($source); } } error = $error; } public function check() { if (null !== $this->error) { throw new LintingException( sprintf('%s: %s on line %d.', $this->getMessagePrefix(), $this->error->getMessage(), $this->error->getLine()), $this->error->getCode(), $this->error ); } } private function getMessagePrefix() { return $this->error instanceof \ParseError ? 'Parse error' : 'Fatal error'; } } sublinter = $linter; } public function isAsync() { return $this->sublinter->isAsync(); } public function lintFile($path) { $checksum = crc32(file_get_contents($path)); if (!isset($this->cache[$checksum])) { $this->cache[$checksum] = $this->sublinter->lintFile($path); } return $this->cache[$checksum]; } public function lintSource($source) { $checksum = crc32($source); if (!isset($this->cache[$checksum])) { $this->cache[$checksum] = $this->sublinter->lintSource($source); } return $this->cache[$checksum]; } } getPreviousBlock($tokens, $previousBlockStart); $previous = $previousBlockEnd; if ($tokens[$previous]->equals('}')) { $previous = $tokens->getPrevMeaningfulToken($previous); } if ( !$tokens[$previous]->equals(';') || $tokens[$tokens->getPrevMeaningfulToken($previous)]->equals('{') ) { return false; } $candidateIndex = $tokens->getPrevTokenOfKind( $previous, [ ';', [T_BREAK], [T_CLOSE_TAG], [T_CONTINUE], [T_EXIT], [T_GOTO], [T_IF], [T_RETURN], [T_THROW], ] ); if (null === $candidateIndex || $tokens[$candidateIndex]->equalsAny([';', [T_CLOSE_TAG], [T_IF]])) { return false; } if ($tokens[$candidateIndex]->equals([T_THROW])) { $previousIndex = $tokens->getPrevMeaningfulToken($candidateIndex); if (!$tokens[$previousIndex]->equalsAny([';', '{'])) { return false; } } if ($this->isInConditional($tokens, $candidateIndex, $previousBlockStart) || $this->isInConditionWithoutBraces($tokens, $candidateIndex, $previousBlockStart) ) { return false; } } while (!$tokens[$previousBlockStart]->isGivenKind(T_IF)); return true; } private function getPreviousBlock(Tokens $tokens, $index) { $close = $previous = $tokens->getPrevMeaningfulToken($index); if ($tokens[$close]->equals('}')) { $previous = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $close); } $open = $tokens->getPrevTokenOfKind($previous, [[T_IF], [T_ELSE], [T_ELSEIF]]); if ($tokens[$open]->isGivenKind(T_IF)) { $elseCandidate = $tokens->getPrevMeaningfulToken($open); if ($tokens[$elseCandidate]->isGivenKind(T_ELSE)) { $open = $elseCandidate; } } return [$open, $close]; } private function isInConditional(Tokens $tokens, $index, $lowerLimitIndex) { $candidateIndex = $tokens->getPrevTokenOfKind($index, [')', ';', ':']); if ($tokens[$candidateIndex]->equals(':')) { return true; } if (!$tokens[$candidateIndex]->equals(')')) { return false; } $open = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $candidateIndex); return $tokens->getPrevMeaningfulToken($open) > $lowerLimitIndex; } private function isInConditionWithoutBraces(Tokens $tokens, $index, $lowerLimitIndex) { do { if ($tokens[$index]->isComment() || $tokens[$index]->isWhitespace()) { $index = $tokens->getPrevMeaningfulToken($index); } $token = $tokens[$index]; if ($token->isGivenKind([T_IF, T_ELSEIF, T_ELSE])) { return true; } if ($token->equals(';')) { return false; } if ($token->equals('{')) { $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind(T_DO)) { --$index; continue; } if (!$tokens[$index]->equals(')')) { return false; } $index = $tokens->findBlockStart( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index ); $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind([T_IF, T_ELSEIF])) { return false; } } elseif ($token->equals(')')) { $type = Tokens::detectBlockType($token); $index = $tokens->findBlockStart( $type['type'], $index ); $index = $tokens->getPrevMeaningfulToken($index); } else { --$index; } } while ($index > $lowerLimitIndex); return false; } } lines[] = new Line($line); } } public function __toString() { return $this->getContent(); } public function getLines() { return $this->lines; } public function getLine($pos) { return isset($this->lines[$pos]) ? $this->lines[$pos] : null; } public function getAnnotations() { if (null !== $this->annotations) { return $this->annotations; } $this->annotations = []; $total = \count($this->lines); for ($index = 0; $index < $total; ++$index) { if ($this->lines[$index]->containsATag()) { $lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), true); $annotation = new Annotation($lines); $index = $annotation->getEnd(); $this->annotations[] = $annotation; } } return $this->annotations; } public function isMultiLine() { return 1 !== \count($this->lines); } public function makeMultiLine($indent, $lineEnd) { if ($this->isMultiLine()) { return; } $lineContent = $this->getSingleLineDocBlockEntry($this->lines[0]); if ('' === $lineContent) { $this->lines = [ new Line('/**'.$lineEnd), new Line($indent.' *'.$lineEnd), new Line($indent.' */'), ]; return; } $this->lines = [ new Line('/**'.$lineEnd), new Line($indent.' * '.$lineContent.$lineEnd), new Line($indent.' */'), ]; } public function makeSingleLine() { if (!$this->isMultiLine()) { return; } $usefulLines = array_filter( $this->lines, static function (Line $line) { return $line->containsUsefulContent(); } ); if (1 < \count($usefulLines)) { return; } $lineContent = ''; if (\count($usefulLines)) { $lineContent = $this->getSingleLineDocBlockEntry(array_shift($usefulLines)); } $this->lines = [new Line('/** '.$lineContent.' */')]; } public function getAnnotation($pos) { $annotations = $this->getAnnotations(); return isset($annotations[$pos]) ? $annotations[$pos] : null; } public function getAnnotationsOfType($types) { $annotations = []; $types = (array) $types; foreach ($this->getAnnotations() as $annotation) { $tag = $annotation->getTag()->getName(); foreach ($types as $type) { if ($type === $tag) { $annotations[] = $annotation; } } } return $annotations; } public function getContent() { return implode('', $this->lines); } private function findAnnotationLength($start) { $index = $start; while ($line = $this->getLine(++$index)) { if ($line->containsATag()) { break; } if (!$line->containsUsefulContent()) { $next = $this->getLine($index + 1); if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) { break; } } } return $index - $start; } private function getSingleLineDocBlockEntry(Line $line) { $lineString = $line->getContent(); if (0 === \strlen($lineString)) { return $lineString; } $lineString = str_replace('*/', '', $lineString); $lineString = trim($lineString); if ('/**' === substr($lineString, 0, 3)) { $lineString = substr($lineString, 3); } elseif ('*' === substr($lineString, 0, 1)) { $lineString = substr($lineString, 1); } return trim($lineString); } } getName(); $secondName = $second->getName(); if ($firstName === $secondName) { return true; } foreach (self::$groups as $group) { if (\in_array($firstName, $group, true) && \in_array($secondName, $group, true)) { return true; } } return false; } } content = $content; } public function __toString() { return $this->content; } public function getContent() { return $this->content; } public function containsUsefulContent() { return 0 !== Preg::match('/\\*\s*\S+/', $this->content) && '' !== trim(str_replace(['/', '*'], ' ', $this->content)); } public function containsATag() { return 0 !== Preg::match('/\\*\s*@/', $this->content); } public function isTheStart() { return false !== strpos($this->content, '/**'); } public function isTheEnd() { return false !== strpos($this->content, '*/'); } public function setContent($content) { $this->content = $content; } public function remove() { $this->content = ''; } public function addBlank() { $matched = Preg::match('/^(\h*\*)[^\r\n]*(\r?\n)$/', $this->content, $matches); if (1 !== $matched) { return; } $this->content .= $matches[1].$matches[2]; } } line = $line; } public function getName() { if (null === $this->name) { Preg::matchAll('/@[a-zA-Z0-9_-]+(?=\s|$)/', $this->line->getContent(), $matches); if (isset($matches[0][0])) { $this->name = ltrim($matches[0][0], '@'); } else { $this->name = 'other'; } } return $this->name; } public function setName($name) { $current = $this->getName(); if ('other' === $current) { throw new \RuntimeException('Cannot set name on unknown tag.'); } $this->line->setContent(Preg::replace("/@{$current}/", "@{$name}", $this->line->getContent(), 1)); $this->name = $name; } public function valid() { return \in_array($this->getName(), self::$tags, true); } } doc = $doc; } public function getEnd() { $reachedContent = false; foreach ($this->doc->getLines() as $index => $line) { if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) { return $index - 1; } if ($line->containsATag()) { return null; } if ($line->containsUsefulContent()) { $reachedContent = true; } } return null; } } is any non-array, non-generic, non-alternated type, eg `int` or `\Foo` # is array of , eg `int[]` or `\Foo[]` # is generic collection type, like `array`, `Collection` and more complex like `Collection>` # is , or type, like `int`, `bool[]` or `Collection` # is one or more types alternated via `|`, like `int|bool[]|Collection` (? (? (? (?&simple)(\[\])* ) | (? [@$?]?[\\\\\w]+ ) | (? (?&simple) < (?:(?&types),\s*)?(?:(?&types)|(?&generic)) > ) ) (?: \| (?:(?&simple)|(?&array)|(?&generic)) )* ) '; private static $tags = [ 'method', 'param', 'property', 'property-read', 'property-write', 'return', 'throws', 'type', 'var', ]; private $lines; private $start; private $end; private $tag; private $typesContent; private $types; public function __construct(array $lines) { $this->lines = array_values($lines); $keys = array_keys($lines); $this->start = $keys[0]; $this->end = end($keys); } public function __toString() { return $this->getContent(); } public static function getTagsWithTypes() { return self::$tags; } public function getStart() { return $this->start; } public function getEnd() { return $this->end; } public function getTag() { if (null === $this->tag) { $this->tag = new Tag($this->lines[0]); } return $this->tag; } public function getTypes() { if (null === $this->types) { $this->types = []; $content = $this->getTypesContent(); while ('' !== $content && false !== $content) { Preg::match( '{^'.self::REGEX_TYPES.'$}x', $content, $matches ); $this->types[] = $matches['type']; $content = substr($content, \strlen($matches['type']) + 1); } } return $this->types; } public function setTypes(array $types) { $pattern = '/'.preg_quote($this->getTypesContent(), '/').'/'; $this->lines[0]->setContent(Preg::replace($pattern, implode('|', $types), $this->lines[0]->getContent(), 1)); $this->clearCache(); } public function getNormalizedTypes() { $normalized = array_map(static function ($type) { return strtolower($type); }, $this->getTypes()); sort($normalized); return $normalized; } public function remove() { foreach ($this->lines as $line) { if ($line->isTheStart() && $line->isTheEnd()) { $line->remove(); } elseif ($line->isTheStart()) { $content = Preg::replace('#(\s*/\*\*).*#', '$1', $line->getContent()); $line->setContent($content); } elseif ($line->isTheEnd()) { $content = Preg::replace('#(\s*)\S.*(\*/.*)#', '$1$2', $line->getContent()); $line->setContent($content); } else { $line->remove(); } } $this->clearCache(); } public function getContent() { return implode('', $this->lines); } public function supportTypes() { return \in_array($this->getTag()->getName(), self::$tags, true); } private function getTypesContent() { if (null === $this->typesContent) { $name = $this->getTag()->getName(); if (!$this->supportTypes()) { throw new \RuntimeException('This tag does not support types.'); } $matchingResult = Preg::match( '{^(?:\s*\*|/\*\*)\s*@'.$name.'\s+'.self::REGEX_TYPES.'(?:[*\h\v].*)?\r?$}sx', $this->lines[0]->getContent(), $matches ); $this->typesContent = 1 === $matchingResult ? $matches['types'] : ''; } return $this->typesContent; } private function clearCache() { $this->types = null; $this->typesContent = null; } } isGivenKind(T_OPEN_TAG)) { $openingToken = $token; $openingTokenIndex = $index - $i; $newlineInOpening = false !== strpos($token->getContent(), "\n"); if ($newlineInOpening) { ++$precedingNewlines; } break; } if (false === $token->isGivenKind(T_WHITESPACE)) { break; } $precedingNewlines += substr_count($token->getContent(), "\n"); } } if ($precedingNewlines >= $expectedMin && $precedingNewlines <= $expectedMax) { return; } $previousIndex = $index - 1; $previous = $tokens[$previousIndex]; if (0 === $expectedMax) { if ($previous->isWhitespace()) { $tokens->clearAt($previousIndex); } if ($newlineInOpening) { $tokens[$openingTokenIndex] = new Token([T_OPEN_TAG, rtrim($openingToken->getContent()).' ']); } return; } $lineEnding = $this->whitespacesConfig->getLineEnding(); $newlinesForWhitespaceToken = $expectedMax; if (null !== $openingToken) { $content = rtrim($openingToken->getContent()); $newContent = $content.$lineEnding; $tokens[$openingTokenIndex] = new Token([T_OPEN_TAG, $newContent]); --$newlinesForWhitespaceToken; } if (0 === $newlinesForWhitespaceToken) { if ($previous->isWhitespace()) { $tokens->clearAt($previousIndex); } return; } if ($previous->isWhitespace()) { $tokens[$previousIndex] = new Token([T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken).substr($previous->getContent(), strrpos($previous->getContent(), "\n") + 1)]); } else { $tokens->insertAt($index, new Token([T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken)])); } } } resolver = new FixerConfigurationResolver($options); $this->fixerName = $fixerName; $names = array_map( static function (FixerOptionInterface $option) { return $option->getName(); }, $this->resolver->getOptions() ); if (!\in_array($root, $names, true)) { throw new \LogicException(sprintf('The "%s" option is not defined.', $root)); } $this->root = $root; } public function getOptions() { return $this->resolver->getOptions(); } public function resolve(array $options) { if (!empty($options) && !\array_key_exists($this->root, $options)) { $names = array_map( static function (FixerOptionInterface $option) { return $option->getName(); }, $this->resolver->getOptions() ); $passedNames = array_keys($options); if (!empty(array_diff($passedNames, $names))) { $message = "Passing \"{$this->root}\" at the root of the configuration for rule \"{$this->fixerName}\" is deprecated and will not be supported in 3.0, use \"{$this->root}\" => array(...) option instead."; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new \RuntimeException("{$message}. This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); $options = [$this->root => $options]; } } return $this->resolver->resolve($options); } } option = $option; $this->deprecationMessage = $deprecationMessage; } public function getName() { return $this->option->getName(); } public function getDescription() { return $this->option->getDescription(); } public function hasDefault() { return $this->option->hasDefault(); } public function getDefault() { return $this->option->getDefault(); } public function getAllowedTypes() { return $this->option->getAllowedTypes(); } public function getAllowedValues() { return $this->option->getAllowedValues(); } public function getNormalizer() { return $this->option->getNormalizer(); } public function getDeprecationMessage() { return $this->deprecationMessage; } } unbind($allowedValue); } } } $this->name = $name; $this->description = $description; $this->isRequired = $isRequired; $this->default = $default; $this->allowedTypes = $allowedTypes; $this->allowedValues = $allowedValues; if (null !== $normalizer) { $this->normalizer = $this->unbind($normalizer); } } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function hasDefault() { return !$this->isRequired; } public function getDefault() { if (!$this->hasDefault()) { throw new \LogicException('No default value defined.'); } return $this->default; } public function getAllowedTypes() { return $this->allowedTypes; } public function getAllowedValues() { return $this->allowedValues; } public function getNormalizer() { return $this->normalizer; } private function unbind(\Closure $closure) { return $closure->bindTo(null); } } name = $name; $this->description = $description; } public function setDefault($default) { $this->default = $default; $this->isRequired = false; return $this; } public function setAllowedTypes(array $allowedTypes) { $this->allowedTypes = $allowedTypes; return $this; } public function setAllowedValues(array $allowedValues) { $this->allowedValues = $allowedValues; return $this; } public function setNormalizer(\Closure $normalizer) { $this->normalizer = $normalizer; return $this; } public function setDeprecationMessage($deprecationMessage) { $this->deprecationMessage = $deprecationMessage; return $this; } public function getOption() { $option = new FixerOption( $this->name, $this->description, $this->isRequired, $this->default, $this->allowedTypes, $this->allowedValues, $this->normalizer ); if (null !== $this->deprecationMessage) { $option = new DeprecatedFixerOption($option, $this->deprecationMessage); } return $option; } } addOption($option); } if (empty($this->registeredNames)) { throw new \LogicException('Options cannot be empty.'); } } public function getOptions() { return $this->options; } public function resolve(array $options) { $resolver = new OptionsResolver(); foreach ($this->options as $option) { $name = $option->getName(); if ($option instanceof AliasedFixerOption) { $alias = $option->getAlias(); if (\array_key_exists($alias, $options)) { if (\array_key_exists($name, $options)) { throw new InvalidOptionsException(sprintf('Aliased option "%s"/"%s" is passed multiple times.', $name, $alias)); } @trigger_error(sprintf('Option "%s" is deprecated, use "%s" instead.', $alias, $name), E_USER_DEPRECATED); $options[$name] = $options[$alias]; unset($options[$alias]); } } if ($option->hasDefault()) { $resolver->setDefault($name, $option->getDefault()); } else { $resolver->setRequired($name); } $allowedValues = $option->getAllowedValues(); if (null !== $allowedValues) { foreach ($allowedValues as &$allowedValue) { if (\is_object($allowedValue) && \is_callable($allowedValue)) { $allowedValue = static function ($values) use ($allowedValue) { return $allowedValue($values); }; } } $resolver->setAllowedValues($name, $allowedValues); } $allowedTypes = $option->getAllowedTypes(); if (null !== $allowedTypes) { $resolver->setAllowedTypes($name, $allowedTypes); } $normalizer = $option->getNormalizer(); if (null !== $normalizer) { $resolver->setNormalizer($name, $normalizer); } } return $resolver->resolve($options); } private function addOption(FixerOptionInterface $option) { $name = $option->getName(); if (\in_array($name, $this->registeredNames, true)) { throw new \LogicException(sprintf('The "%s" option is defined multiple times.', $name)); } $this->options[] = $option; $this->registeredNames[] = $name; return $this; } } optionBuilder = $optionBuilder; $this->alias = $alias; } public function setDefault($default) { $this->optionBuilder->setDefault($default); return $this; } public function setAllowedTypes(array $allowedTypes) { $this->optionBuilder->setAllowedTypes($allowedTypes); return $this; } public function setAllowedValues(array $allowedValues) { $this->optionBuilder->setAllowedValues($allowedValues); return $this; } public function setNormalizer(\Closure $normalizer) { $this->optionBuilder->setNormalizer($normalizer); return $this; } public function getOption() { return new AliasedFixerOption( $this->optionBuilder->getOption(), $this->alias ); } } allowedValues = $allowedValues; } public function __invoke($values) { if (!\is_array($values)) { return false; } foreach ($values as $value) { if (!\in_array($value, $this->allowedValues, true)) { return false; } } return true; } public function getAllowedValues() { return $this->allowedValues; } } fixerOption = $fixerOption; $this->alias = $alias; } public function getAlias() { return $this->alias; } public function getName() { return $this->fixerOption->getName(); } public function getDescription() { return $this->fixerOption->getDescription(); } public function hasDefault() { return $this->fixerOption->hasDefault(); } public function getDefault() { return $this->fixerOption->getDefault(); } public function getAllowedTypes() { return $this->fixerOption->getAllowedTypes(); } public function getAllowedValues() { return $this->fixerOption->getAllowedValues(); } public function getNormalizer() { return $this->fixerOption->getNormalizer(); } } isAnyTokenKindsFound(Token::getClassyTokenKinds()); } public function isRisky() { return true; } public function getPriority() { return -10; } public function supports(\SplFileInfo $file) { if ($file instanceof StdinFileInfo) { return false; } $filenameParts = explode('.', $file->getBasename(), 2); if ( (!isset($filenameParts[1]) || 'php' !== $filenameParts[1]) || 0 === Preg::match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $filenameParts[0]) ) { return false; } try { $tokens = Tokens::fromCode(sprintf('isKeyword() || $tokens[3]->isMagicConstant()) { return false; } } catch (\ParseError $e) { return false; } return !Preg::match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath()); } } differ = new Differ(new StrictUnifiedDiffOutputBuilder([ 'fromFile' => 'Original', 'toFile' => 'New', ])); } public function diff($old, $new) { return $this->differ->diff($old, $new); } } differ = new Differ(new StrictUnifiedDiffOutputBuilder([ 'collapseRanges' => false, 'commonLineThreshold' => 100, 'contextLines' => 100, 'fromFile' => 'Original', 'toFile' => 'New', ])); } public function diff($old, $new) { return $this->differ->diff($old, $new); } } differ = new Differ(); } public function diff($old, $new) { return $this->differ->diff($old, $new); } } isDecoratedOutput = $isDecoratedOutput; $this->template = $template; } public function format($diff, $lineTemplate = '%s') { $isDecorated = $this->isDecoratedOutput; $template = $isDecorated ? $this->template : Preg::replace('/<[^<>]+>/', '', $this->template) ; return sprintf( $template, implode( PHP_EOL, array_map( static function ($line) use ($isDecorated, $lineTemplate) { if ($isDecorated) { $count = 0; $line = Preg::replaceCallback( [ '/^(\+.*)/', '/^(\-.*)/', '/^(@.*)/', ], static function ($matches) { if ('+' === $matches[0][0]) { $colour = 'green'; } elseif ('-' === $matches[0][0]) { $colour = 'red'; } else { $colour = 'cyan'; } return sprintf('%s', $colour, OutputFormatter::escape($matches[0]), $colour); }, $line, 1, $count ); if (0 === $count) { $line = OutputFormatter::escape($line); } } return sprintf($lineTemplate, $line); }, Preg::split('#\R#u', $diff) ) ) ); } } differ = new Differ("--- Original\n+++ New\n", false); } public function diff($old, $new) { return $this->differ->diff($old, $new); } } isInstalledByComposer()) { throw new \LogicException('Cannot get composer version for tool not installed by composer.'); } if (null === $this->composerInstallationDetails) { $composerInstalled = json_decode(file_get_contents($this->getComposerInstalledFile()), true); $packages = isset($composerInstalled['packages']) ? $composerInstalled['packages'] : $composerInstalled; foreach ($packages as $package) { if (\in_array($package['name'], [self::COMPOSER_PACKAGE_NAME, self::COMPOSER_LEGACY_PACKAGE_NAME], true)) { $this->composerInstallationDetails = $package; break; } } } return $this->composerInstallationDetails; } public function getComposerVersion() { $package = $this->getComposerInstallationDetails(); $versionSuffix = ''; if (isset($package['dist']['reference'])) { $versionSuffix = '#'.$package['dist']['reference']; } return $package['version'].$versionSuffix; } public function getVersion() { if ($this->isInstalledByComposer()) { return Application::VERSION.':'.$this->getComposerVersion(); } return Application::VERSION; } public function isInstalledAsPhar() { return 'phar://' === substr(__DIR__, 0, 7); } public function isInstalledByComposer() { if (null === $this->isInstalledByComposer) { $this->isInstalledByComposer = !$this->isInstalledAsPhar() && file_exists($this->getComposerInstalledFile()); } return $this->isInstalledByComposer; } public function getPharDownloadUri($version) { return sprintf( 'https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', $version ); } private function getComposerInstalledFile() { return __DIR__.'/../../../composer/installed.json'; } } injectAlignmentPlaceholders($tokensClone, 0, \count($tokens)); $content = $this->replacePlaceholder($tokensClone); $tokens->setCode($content); } abstract protected function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt); protected function replacePlaceholder(Tokens $tokens) { $tmpCode = $tokens->generateCode(); for ($j = 0; $j <= $this->deepestLevel; ++$j) { $placeholder = sprintf(self::ALIGNABLE_PLACEHOLDER, $j); if (false === strpos($tmpCode, $placeholder)) { continue; } $lines = explode("\n", $tmpCode); $linesWithPlaceholder = []; $blockSize = 0; $linesWithPlaceholder[$blockSize] = []; foreach ($lines as $index => $line) { if (substr_count($line, $placeholder) > 0) { $linesWithPlaceholder[$blockSize][] = $index; } else { ++$blockSize; $linesWithPlaceholder[$blockSize] = []; } } foreach ($linesWithPlaceholder as $group) { if (\count($group) < 1) { continue; } $rightmostSymbol = 0; foreach ($group as $index) { $rightmostSymbol = max($rightmostSymbol, strpos(utf8_decode($lines[$index]), $placeholder)); } foreach ($group as $index) { $line = $lines[$index]; $currentSymbol = strpos(utf8_decode($line), $placeholder); $delta = abs($rightmostSymbol - $currentSymbol); if ($delta > 0) { $line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line); $lines[$index] = $line; } } } $tmpCode = str_replace($placeholder, '', implode("\n", $lines)); } return $tmpCode; } } files() ->name('*.php') ->exclude('vendor') ; } } candidates = $candidates; } public function match($needle) { $word = null; $distance = ceil(\strlen($needle) * 0.35); foreach ($this->candidates as $candidate) { $candidateDistance = levenshtein($needle, $candidate); if ($candidateDistance < $distance) { $word = $candidate; $distance = $candidateDistance; } } return $word; } } isAllTokenKindsFound([T_STRING, T_CONSTANT_ENCAPSED_STRING]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $argumentsAnalyzer = new ArgumentsAnalyzer(); $index = 0; $end = $tokens->count() - 1; while (true) { $candidate = $this->find('fopen', $tokens, $index, $end); if (null === $candidate) { break; } $index = $candidate[1]; $arguments = $argumentsAnalyzer->getArguments( $tokens, $index, $candidate[2] ); $argumentsCount = \count($arguments); if ($argumentsCount < 2 || $argumentsCount > 4) { continue; } $argumentStartIndex = array_keys($arguments)[1]; $this->fixFopenFlagToken( $tokens, $argumentStartIndex, $arguments[$argumentStartIndex] ); } } abstract protected function fixFopenFlagToken(Tokens $tokens, $argumentStartIndex, $argumentEndIndex); protected function isValidModeString($mode) { $modeLength = \strlen($mode); if ($modeLength < 1 || $modeLength > 13) { return false; } $validFlags = [ 'a' => true, 'b' => true, 'c' => true, 'e' => true, 'r' => true, 't' => true, 'w' => true, 'x' => true, ]; if (!isset($validFlags[$mode[0]])) { return false; } unset($validFlags[$mode[0]]); for ($i = 1; $i < $modeLength; ++$i) { if (isset($validFlags[$mode[$i]])) { unset($validFlags[$mode[$i]]); continue; } if ('+' !== $mode[$i] || ( 'a' !== $mode[$i - 1] && 'c' !== $mode[$i - 1] && 'r' !== $mode[$i - 1] && 'w' !== $mode[$i - 1] && 'x' !== $mode[$i - 1] ) ) { return false; } } return true; } } getRealPath(); } public function getRealPath() { return 'php://stdin'; } public function getATime() { return 0; } public function getBasename($suffix = null) { return $this->getFilename(); } public function getCTime() { return 0; } public function getExtension() { return '.php'; } public function getFileInfo($className = null) { throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); } public function getFilename() { return 'stdin.php'; } public function getGroup() { return 0; } public function getInode() { return 0; } public function getLinkTarget() { return ''; } public function getMTime() { return 0; } public function getOwner() { return 0; } public function getPath() { return ''; } public function getPathInfo($className = null) { throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); } public function getPathname() { return $this->getFilename(); } public function getPerms() { return 0; } public function getSize() { return 0; } public function getType() { return 'file'; } public function isDir() { return false; } public function isExecutable() { return false; } public function isFile() { return true; } public function isLink() { return false; } public function isReadable() { return true; } public function isWritable() { return false; } public function openFile($openMode = 'r', $useIncludePath = false, $context = null) { throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); } public function setFileClass($className = null) { } public function setInfoClass($className = null) { } } errors, static function (Error $error) { return Error::TYPE_INVALID === $error->getType(); }); } public function getExceptionErrors() { return array_filter($this->errors, static function (Error $error) { return Error::TYPE_EXCEPTION === $error->getType(); }); } public function getLintErrors() { return array_filter($this->errors, static function (Error $error) { return Error::TYPE_LINT === $error->getType(); }); } public function isEmpty() { return empty($this->errors); } public function report(Error $error) { $this->errors[] = $error; } } type = $type; $this->filePath = $filePath; $this->source = $source; $this->appliedFixers = $appliedFixers; $this->diff = $diff; } public function getFilePath() { return $this->filePath; } public function getSource() { return $this->source; } public function getType() { return $this->type; } public function getAppliedFixers() { return $this->appliedFixers; } public function getDiff() { return $this->diff; } } clean(); } public function observe($path) { $this->files[$path] = true; } public function delete($path) { if (isset($this->files[$path])) { unset($this->files[$path]); } $this->unlink($path); } public function clean() { foreach ($this->files as $file => $value) { $this->unlink($file); } $this->files = []; } private function unlink($path) { @unlink($path); } } true]; private $usingCache = true; public function __construct($name = 'default') { $this->name = $name; } public static function create() { return new static(); } public function getCacheFile() { return $this->cacheFile; } public function getCustomFixers() { return $this->customFixers; } public function getFinder() { if (null === $this->finder) { $this->finder = new Finder(); } return $this->finder; } public function getFormat() { return $this->format; } public function getHideProgress() { return $this->hideProgress; } public function getIndent() { return $this->indent; } public function getLineEnding() { return $this->lineEnding; } public function getName() { return $this->name; } public function getPhpExecutable() { return $this->phpExecutable; } public function getRiskyAllowed() { return $this->isRiskyAllowed; } public function getRules() { return $this->rules; } public function getUsingCache() { return $this->usingCache; } public function registerCustomFixers($fixers) { if (false === \is_array($fixers) && false === $fixers instanceof \Traversable) { throw new \InvalidArgumentException(sprintf( 'Argument must be an array or a Traversable, got "%s".', \is_object($fixers) ? \get_class($fixers) : \gettype($fixers) )); } foreach ($fixers as $fixer) { $this->addCustomFixer($fixer); } return $this; } public function setCacheFile($cacheFile) { $this->cacheFile = $cacheFile; return $this; } public function setFinder($finder) { if (false === \is_array($finder) && false === $finder instanceof \Traversable) { throw new \InvalidArgumentException(sprintf( 'Argument must be an array or a Traversable, got "%s".', \is_object($finder) ? \get_class($finder) : \gettype($finder) )); } $this->finder = $finder; return $this; } public function setFormat($format) { $this->format = $format; return $this; } public function setHideProgress($hideProgress) { $this->hideProgress = $hideProgress; return $this; } public function setIndent($indent) { $this->indent = $indent; return $this; } public function setLineEnding($lineEnding) { $this->lineEnding = $lineEnding; return $this; } public function setPhpExecutable($phpExecutable) { $this->phpExecutable = $phpExecutable; return $this; } public function setRiskyAllowed($isRiskyAllowed) { $this->isRiskyAllowed = $isRiskyAllowed; return $this; } public function setRules(array $rules) { $this->rules = $rules; return $this; } public function setUsingCache($usingCache) { $this->usingCache = $usingCache; return $this; } private function addCustomFixer(FixerInterface $fixer) { $this->customFixers[] = $fixer; } } tags = Annotation::getTagsWithTypes(); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType($this->tags); if (empty($annotations)) { continue; } foreach ($annotations as $annotation) { $this->fixTypes($annotation); } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } abstract protected function normalize($type); private function fixTypes(Annotation $annotation) { $types = $annotation->getTypes(); $new = $this->normalizeTypes($types); if ($types !== $new) { $annotation->setTypes($new); } } private function normalizeTypes(array $types) { foreach ($types as $index => $type) { $types[$index] = $this->normalizeType($type); } return $types; } private function normalizeType($type) { if ('[]' === substr($type, -2)) { return $this->normalizeType(substr($type, 0, -2)).'[]'; } return $this->normalize($type); } } indent = $indent; $this->lineEnding = $lineEnding; } public function getIndent() { return $this->indent; } public function getLineEnding() { return $this->lineEnding; } } count() : $end; $candidateSequence = [[T_STRING, $functionNameToSearch], '(']; $matches = $tokens->findSequence($candidateSequence, $start, $end, false); if (null === $matches) { return null; } list($functionName, $openParenthesis) = array_keys($matches); $functionsAnalyzer = new FunctionsAnalyzer(); if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) { return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end); } return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)]; } } count(); if ($count && !$tokens[$count - 1]->isGivenKind([T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG])) { $tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding()); } } } ['inside']]), new CodeSample(" ['outside']]), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(['[', CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]])) { continue; } if (\in_array('inside', $this->configuration['positions'], true)) { if ($token->equals('[')) { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); } else { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $index); } if ($tokens[$index + 1]->isWhitespace(" \t")) { $tokens->clearAt($index + 1); } if ($tokens[$endIndex - 1]->isWhitespace(" \t")) { $tokens->clearAt($endIndex - 1); } } if (\in_array('outside', $this->configuration['positions'], true)) { $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($index); if ($tokens[$prevNonWhitespaceIndex]->isComment()) { continue; } $tokens->removeLeadingWhitespace($index); } } } protected function createConfigurationDefinition() { $values = ['inside', 'outside']; return new FixerConfigurationResolverRootless('positions', [ (new FixerOptionBuilder('positions', 'Whether spacing should be fixed inside and/or outside the offset braces.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($values)]) ->setDefault($values) ->getOption(), ], $this->getName()); } } setEmail('voff.web@gmail.com')\n ->setPassword('233434');\n")] ); } public function getPriority() { return -29; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_OBJECT_OPERATOR); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind(T_OBJECT_OPERATOR)) { continue; } if ($this->canBeMovedToNextLine($index, $tokens)) { $newline = new Token([T_WHITESPACE, $lineEnding]); if ($tokens[$index - 1]->isWhitespace()) { $tokens[$index - 1] = $newline; } else { $tokens->insertAt($index, $newline); ++$index; } } $currentIndent = $this->getIndentAt($tokens, $index - 1); if (null === $currentIndent) { continue; } $expectedIndent = $this->getExpectedIndentAt($tokens, $index); if ($currentIndent !== $expectedIndent) { $tokens[$index - 1] = new Token([T_WHITESPACE, $lineEnding.$expectedIndent]); } } } private function getExpectedIndentAt(Tokens $tokens, $index) { $index = $tokens->getPrevMeaningfulToken($index); $indent = $this->whitespacesConfig->getIndent(); for ($i = $index; $i >= 0; --$i) { if ($tokens[$i]->equals(')')) { $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); } $currentIndent = $this->getIndentAt($tokens, $i); if (null === $currentIndent) { continue; } if ($this->currentLineRequiresExtraIndentLevel($tokens, $i, $index)) { return $currentIndent.$indent; } return $currentIndent; } return $indent; } private function canBeMovedToNextLine($index, Tokens $tokens) { $prevMeaningful = $tokens->getPrevMeaningfulToken($index); $hasCommentBefore = false; for ($i = $index - 1; $i > $prevMeaningful; --$i) { if ($tokens[$i]->isComment()) { $hasCommentBefore = true; continue; } if ($tokens[$i]->isWhitespace() && 1 === Preg::match('/\R/', $tokens[$i]->getContent())) { return $hasCommentBefore; } } return false; } private function getIndentAt(Tokens $tokens, $index) { if (1 === Preg::match('/\R{1}(\h*)$/', $this->getIndentContentAt($tokens, $index), $matches)) { return $matches[1]; } return null; } private function getIndentContentAt(Tokens $tokens, $index) { if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) { return ''; } $content = $tokens[$index]->getContent(); if ($tokens[$index]->isWhitespace() && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG)) { $content = $tokens[$index - 1]->getContent().$content; } if (Preg::match('/\R/', $content)) { return $content; } return ''; } private function currentLineRequiresExtraIndentLevel(Tokens $tokens, $start, $end) { if ($tokens[$start + 1]->isGivenKind(T_OBJECT_OPERATOR)) { return false; } if ($tokens[$end]->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_CLOSE)) { return true; } return !$tokens[$end]->equals(')') || $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end) >= $start ; } } = 0; --$index) { $token = $tokens[$index]; if ( $token->isGivenKind(T_OPEN_TAG) && $tokens->offsetExists($index + 1) && $tokens[$index + 1]->isWhitespace() && 1 === Preg::match('/(.*)\h$/', $token->getContent(), $openTagMatches) && 1 === Preg::match('/^(\R)(.*)$/s', $tokens[$index + 1]->getContent(), $whitespaceMatches) ) { $tokens[$index] = new Token([T_OPEN_TAG, $openTagMatches[1].$whitespaceMatches[1]]); if ('' === $whitespaceMatches[2]) { $tokens->clearAt($index + 1); } else { $tokens[$index + 1] = new Token([T_WHITESPACE, $whitespaceMatches[2]]); } continue; } if (!$token->isWhitespace()) { continue; } $lines = Preg::split('/(\\R+)/', $token->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE); $linesSize = \count($lines); if ($linesSize > 1 || !isset($tokens[$index + 1])) { if (!$tokens[$index - 1]->isGivenKind(T_OPEN_TAG) || 1 !== Preg::match('/(.*)\R$/', $tokens[$index - 1]->getContent())) { $lines[0] = rtrim($lines[0], " \t"); } for ($i = 1; $i < $linesSize; ++$i) { $trimmedLine = rtrim($lines[$i], " \t"); if ('' !== $trimmedLine) { $lines[$i] = $trimmedLine; } } $content = implode('', $lines); if ('' !== $content) { $tokens[$index] = new Token([$token->getId(), $content]); } else { $tokens->clearAt($index); } } } } } isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT, T_WHITESPACE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->indent = $this->whitespacesConfig->getIndent(); foreach ($tokens as $index => $token) { if ($token->isComment()) { $tokens[$index] = $this->fixIndentInComment($tokens, $index); continue; } if ($token->isWhitespace()) { $tokens[$index] = $this->fixIndentToken($tokens, $index); continue; } } } private function fixIndentInComment(Tokens $tokens, $index) { $content = Preg::replace('/^(?:(?getContent(), -1, $count); while (0 !== $count) { $content = Preg::replace('/^(\ +)?\t/m', '\1 ', $content, -1, $count); } $indent = $this->indent; $content = Preg::replaceCallback('/^(?: )+/m', function ($matches) use ($indent) { return $this->getExpectedIndent($matches[0], $indent); }, $content); return new Token([$tokens[$index]->getId(), $content]); } private function fixIndentToken(Tokens $tokens, $index) { $content = $tokens[$index]->getContent(); $previousTokenHasTrailingLinebreak = false; if (false !== strpos($tokens[$index - 1]->getContent(), "\n")) { $content = "\n".$content; $previousTokenHasTrailingLinebreak = true; } $indent = $this->indent; $newContent = Preg::replaceCallback( '/(\R)(\h+)/', function (array $matches) use ($indent) { $content = Preg::replace('/(?:(?getExpectedIndent($content, $indent); }, $content ); if ($previousTokenHasTrailingLinebreak) { $newContent = substr($newContent, 1); } return new Token([T_WHITESPACE, $newContent]); } private function getExpectedIndent($content, $indent) { if ("\t" === $indent) { $content = str_replace(' ', $indent, $content); } return $content; } } T_BREAK, 'case' => T_CASE, 'continue' => T_CONTINUE, 'declare' => T_DECLARE, 'default' => T_DEFAULT, 'die' => T_EXIT, 'do' => T_DO, 'exit' => T_EXIT, 'for' => T_FOR, 'foreach' => T_FOREACH, 'goto' => T_GOTO, 'if' => T_IF, 'include' => T_INCLUDE, 'include_once' => T_INCLUDE_ONCE, 'require' => T_REQUIRE, 'require_once' => T_REQUIRE_ONCE, 'return' => T_RETURN, 'switch' => T_SWITCH, 'throw' => T_THROW, 'try' => T_TRY, 'while' => T_WHILE, 'yield' => T_YIELD, ]; private $fixTokenMap = []; public function configure(array $configuration = null) { parent::configure($configuration); $this->fixTokenMap = []; foreach ($this->configuration['statements'] as $key) { $this->fixTokenMap[$key] = self::$tokenMap[$key]; } $this->fixTokenMap = array_values($this->fixTokenMap); } public function getDefinition() { return new FixerDefinition( 'An empty line feed must precede any configured statement.', [ new CodeSample( 'process(); break; case 44: break; } ', [ 'statements' => ['break'], ] ), new CodeSample( 'isTired()) { $bar->sleep(); continue; } } ', [ 'statements' => ['continue'], ] ), new CodeSample( ' ['die'], ] ), new CodeSample( ' 0); ', [ 'statements' => ['do'], ] ), new CodeSample( ' ['exit'], ] ), new CodeSample( ' ['goto'], ] ), new CodeSample( ' ['if'], ] ), new CodeSample( ' ['return'], ] ), new CodeSample( ' ['switch'], ] ), new CodeSample( 'bar(); throw new \UnexpectedValueException("A cannot be null."); } ', [ 'statements' => ['throw'], ] ), new CodeSample( 'bar(); } catch (\Exception $exception) { $a = -1; } ', [ 'statements' => ['try'], ] ), new CodeSample( ' ['yield'], ] ), ] ); } public function getPriority() { return -21; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound($this->fixTokenMap); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $analyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind($this->fixTokenMap)) { continue; } if ($token->isGivenKind(T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { continue; } $prevNonWhitespace = $tokens->getPrevNonWhitespace($index); if ($this->shouldAddBlankLine($tokens, $prevNonWhitespace)) { $this->insertBlankLine($tokens, $index); } $index = $prevNonWhitespace; } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(array_keys(self::$tokenMap))]) ->setDefault([ 'break', 'continue', 'declare', 'return', 'throw', 'try', ]) ->getOption(), ]); } private function shouldAddBlankLine(Tokens $tokens, $prevNonWhitespace) { $prevNonWhitespaceToken = $tokens[$prevNonWhitespace]; if ($prevNonWhitespaceToken->isComment()) { for ($j = $prevNonWhitespace - 1; $j >= 0; --$j) { if (false !== strpos($tokens[$j]->getContent(), "\n")) { return false; } if ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) { continue; } return $tokens[$j]->equalsAny([';', '}']); } } return $prevNonWhitespaceToken->equalsAny([';', '}']); } private function insertBlankLine(Tokens $tokens, $index) { $prevIndex = $index - 1; $prevToken = $tokens[$prevIndex]; $lineEnding = $this->whitespacesConfig->getLineEnding(); if ($prevToken->isWhitespace()) { $newlinesCount = substr_count($prevToken->getContent(), "\n"); if (0 === $newlinesCount) { $tokens[$prevIndex] = new Token([T_WHITESPACE, rtrim($prevToken->getContent(), " \t").$lineEnding.$lineEnding]); } elseif (1 === $newlinesCount) { $tokens[$prevIndex] = new Token([T_WHITESPACE, $lineEnding.$prevToken->getContent()]); } } else { $tokens->insertAt($index, new Token([T_WHITESPACE, $lineEnding.$lineEnding])); } } } isTokenKindFound('('); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->equals('(')) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ARRAY)) { continue; } $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); if (!$tokens[$tokens->getNextNonWhitespace($index)]->isComment()) { $this->removeSpaceAroundToken($tokens, $index + 1); } if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) { $this->removeSpaceAroundToken($tokens, $endIndex - 1); } } } private function removeSpaceAroundToken(Tokens $tokens, $index) { $token = $tokens[$index]; if ($token->isWhitespace() && false === strpos($token->getContent(), "\n")) { $tokens->clearAt($index); } } } = 70100 && $tokens->isTokenKindFound(CT::T_NULLABLE_TYPE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $typehintKinds = [ CT::T_ARRAY_TYPEHINT, T_CALLABLE, T_NS_SEPARATOR, T_STRING, ]; for ($index = $tokens->count() - 1; $index >= 0; --$index) { if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { continue; } if ( $tokens[$index + 1]->isWhitespace() && $tokens[$index + 2]->isGivenKind($typehintKinds) ) { $tokens->removeTrailingWhitespace($index); } } } } getFixer()->getDefinition(); } public function configure(array $configuration = null) { $this->getFixer()->configure($configuration); $this->configuration = $configuration; } public function getConfigurationDefinition() { return $this->getFixer()->getConfigurationDefinition(); } public function getSuccessorsNames() { return array_keys($this->proxyFixers); } protected function createProxyFixers() { return [$this->getFixer()]; } private function getFixer() { if (null === $this->fixer) { $this->fixer = new NoExtraBlankLinesFixer(); } return $this->fixer; } } T_BREAK, 'case' => T_CASE, 'continue' => T_CONTINUE, 'curly_brace_block' => '{', 'default' => T_DEFAULT, 'extra' => T_WHITESPACE, 'parenthesis_brace_block' => '(', 'return' => T_RETURN, 'square_brace_block' => CT::T_ARRAY_SQUARE_BRACE_OPEN, 'switch' => T_SWITCH, 'throw' => T_THROW, 'use' => T_USE, 'use_trait' => CT::T_USE_TRAIT, ]; static $tokenKindCallbackMap = [ T_BREAK => 'fixAfterToken', T_CASE => 'fixAfterToken', T_CONTINUE => 'fixAfterToken', T_DEFAULT => 'fixAfterToken', T_RETURN => 'fixAfterToken', T_SWITCH => 'fixAfterToken', T_THROW => 'fixAfterToken', T_USE => 'removeBetweenUse', T_WHITESPACE => 'removeMultipleBlankLines', CT::T_USE_TRAIT => 'removeBetweenUse', CT::T_ARRAY_SQUARE_BRACE_OPEN => 'fixStructureOpenCloseIfMultiLine', ]; static $tokenEqualsMap = [ '{' => 'fixStructureOpenCloseIfMultiLine', '(' => 'fixStructureOpenCloseIfMultiLine', ]; $tokensAssoc = array_flip(array_intersect_key($reprToTokenMap, array_flip($this->configuration['tokens']))); $this->tokenKindCallbackMap = array_intersect_key($tokenKindCallbackMap, $tokensAssoc); $this->tokenEqualsMap = array_intersect_key($tokenEqualsMap, $tokensAssoc); } public function getDefinition() { return new FixerDefinition( 'Removes extra blank lines and/or blank lines following configuration.', [ new CodeSample( ' ['break']] ), new CodeSample( ' ['continue']] ), new CodeSample( ' ['curly_brace_block']] ), new CodeSample( ' ['extra']] ), new CodeSample( ' ['parenthesis_brace_block']] ), new CodeSample( ' ['return']] ), new CodeSample( ' ['square_brace_block']] ), new CodeSample( ' ['throw']] ), new CodeSample( ' ['use']] ), new CodeSample( ' ['use_trait']] ), new CodeSample( ' ['switch', 'case', 'default']] ), ] ); } public function getPriority() { return -20; } public function isCandidate(Tokens $tokens) { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->tokens = $tokens; $this->tokensAnalyzer = new TokensAnalyzer($this->tokens); for ($index = $tokens->getSize() - 1; $index > 0; --$index) { $this->fixByToken($tokens[$index], $index); } } protected function createConfigurationDefinition() { $that = $this; return new FixerConfigurationResolverRootless('tokens', [ (new FixerOptionBuilder('tokens', 'List of tokens to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(self::$availableTokens)]) ->setNormalizer(static function (Options $options, $tokens) use ($that) { foreach ($tokens as &$token) { if ('useTrait' === $token) { $message = "Token \"useTrait\" in option \"tokens\" for rule \"{$that->getName()}\" is deprecated and will be removed in 3.0, use \"use_trait\" instead."; if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new InvalidConfigurationException("{$message} This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); $token = 'use_trait'; break; } } return $tokens; }) ->setDefault(['extra']) ->getOption(), ], $this->getName()); } private function fixByToken(Token $token, $index) { foreach ($this->tokenKindCallbackMap as $kind => $callback) { if (!$token->isGivenKind($kind)) { continue; } $this->{$callback}($index); return; } foreach ($this->tokenEqualsMap as $equals => $callback) { if (!$token->equals($equals)) { continue; } $this->{$callback}($index); return; } } private function removeBetweenUse($index) { $next = $this->tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); if (null === $next || $this->tokens[$next]->isGivenKind(T_CLOSE_TAG)) { return; } $nextUseCandidate = $this->tokens->getNextMeaningfulToken($next); if (null === $nextUseCandidate || !$this->tokens[$nextUseCandidate]->isGivenKind($this->tokens[$index]->getId()) || !$this->containsLinebreak($index, $nextUseCandidate)) { return; } return $this->removeEmptyLinesAfterLineWithTokenAt($next); } private function removeMultipleBlankLines($index) { $expected = $this->tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && 1 === Preg::match('/\R$/', $this->tokens[$index - 1]->getContent()) ? 1 : 2; $parts = Preg::split('/(.*\R)/', $this->tokens[$index]->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $count = \count($parts); if ($count > $expected) { $this->tokens[$index] = new Token([T_WHITESPACE, implode('', \array_slice($parts, 0, $expected)).rtrim($parts[$count - 1], "\r\n")]); } } private function fixAfterToken($index) { for ($i = $index - 1; $i > 0; --$i) { if ($this->tokens[$i]->isGivenKind(T_FUNCTION) && $this->tokensAnalyzer->isLambda($i)) { return; } if ($this->tokens[$i]->isGivenKind(T_CLASS) && $this->tokensAnalyzer->isAnonymousClass($i)) { return; } if ($this->tokens[$i]->isWhitespace() && false !== strpos($this->tokens[$i]->getContent(), "\n")) { break; } } $this->removeEmptyLinesAfterLineWithTokenAt($index); } private function fixStructureOpenCloseIfMultiLine($index) { $blockTypeInfo = Tokens::detectBlockType($this->tokens[$index]); $bodyEnd = $this->tokens->findBlockEnd($blockTypeInfo['type'], $index); for ($i = $bodyEnd - 1; $i >= $index; --$i) { if (false !== strpos($this->tokens[$i]->getContent(), "\n")) { $this->removeEmptyLinesAfterLineWithTokenAt($i); $this->removeEmptyLinesAfterLineWithTokenAt($index); break; } } } private function removeEmptyLinesAfterLineWithTokenAt($index) { $tokenCount = \count($this->tokens); for ($end = $index; $end < $tokenCount; ++$end) { if ( $this->tokens[$end]->equals('}') || false !== strpos($this->tokens[$end]->getContent(), "\n") ) { break; } } if ($end === $tokenCount) { return; } $ending = $this->whitespacesConfig->getLineEnding(); for ($i = $end; $i < $tokenCount && $this->tokens[$i]->isWhitespace(); ++$i) { $content = $this->tokens[$i]->getContent(); if (substr_count($content, "\n") < 1) { continue; } $pos = strrpos($content, "\n"); if ($pos + 2 <= \strlen($content)) { $newContent = $ending.substr($content, $pos + 1); } else { $newContent = $ending; } $this->tokens[$i] = new Token([T_WHITESPACE, $newContent]); } } private function containsLinebreak($startIndex, $endIndex) { for ($i = $endIndex; $i > $startIndex; --$i) { if (Preg::match('/\R/', $this->tokens[$i]->getContent())) { return true; } } return false; } } whitespacesConfig->getLineEnding(); for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_END_HEREDOC)) { $tokens[$index] = new Token([ $token->getId(), Preg::replace( '#\R#', $ending, $token->getContent() ), ]); } continue; } if ($token->isGivenKind([T_CLOSE_TAG, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_START_HEREDOC, T_WHITESPACE])) { $tokens[$index] = new Token([ $token->getId(), Preg::replace( '#\R#', $ending, $token->getContent() ), ]); } } } } isWhitespace()) { $this->fixWhitespaceToken($tokens, $i); } } } private function fixWhitespaceToken(Tokens $tokens, $index) { $content = $tokens[$index]->getContent(); $lines = Preg::split("/(\r\n|\n)/", $content); $lineCount = \count($lines); if ( $lineCount > 2 || ($lineCount > 0 && (!isset($tokens[$index + 1]) || $tokens[$index - 1]->isGivenKind(T_OPEN_TAG))) ) { $lMax = isset($tokens[$index + 1]) ? $lineCount - 1 : $lineCount; $lStart = 1; if ($tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) { $lStart = 0; } for ($l = $lStart; $l < $lMax; ++$l) { $lines[$l] = Preg::replace('/^\h+$/', '', $lines[$l]); } $content = implode($this->whitespacesConfig->getLineEnding(), $lines); if ('' !== $content) { $tokens[$index] = new Token([T_WHITESPACE, $content]); } else { $tokens->clearAt($index); } } } } = 7.3.', [ new VersionSpecificCodeSample( <<<'SAMPLE' = 70300 && $tokens->isTokenKindFound(T_START_HEREDOC); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; 0 <= $index; --$index) { if (!$tokens[$index]->isGivenKind(T_END_HEREDOC)) { continue; } $end = $index; $index = $tokens->getPrevTokenOfKind($index, [[T_START_HEREDOC]]); $this->fixIndentation($tokens, $index, $end); } } private function fixIndentation(Tokens $tokens, $start, $end) { $indent = $this->getIndentAt($tokens, $start).$this->whitespacesConfig->getIndent(); Preg::match('/^\h*/', $tokens[$end]->getContent(), $matches); $currentIndent = $matches[0]; $currentIndentLength = \strlen($currentIndent); $content = $indent.substr($tokens[$end]->getContent(), $currentIndentLength); $tokens[$end] = new Token([T_END_HEREDOC, $content]); if ($end === $start + 1) { return; } for ($index = $end - 1, $last = true; $index > $start; --$index, $last = false) { if (!$tokens[$index]->isGivenKind([T_ENCAPSED_AND_WHITESPACE, T_WHITESPACE])) { continue; } $content = $tokens[$index]->getContent(); if ('' !== $currentIndent) { $content = Preg::replace('/(?<=\v)(?!'.$currentIndent.')\h+/', '', $content); } $regexEnd = $last && !$currentIndent ? '(?!\v|$)' : '(?!\v)'; $content = Preg::replace('/(?<=\v)'.$currentIndent.$regexEnd.'/', $indent, $content); $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); } ++$index; if (!$tokens[$index]->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { $tokens->insertAt($index, new Token([T_ENCAPSED_AND_WHITESPACE, $indent])); return; } $content = $tokens[$index]->getContent(); if (!\in_array($content[0], ["\r", "\n"], true) && (!$currentIndent || $currentIndent === substr($content, 0, $currentIndentLength))) { $content = $indent.substr($content, $currentIndentLength); } elseif ($currentIndent) { $content = Preg::replace('/^(?!'.$currentIndent.')\h+/', '', $content); } $tokens[$index] = new Token([T_ENCAPSED_AND_WHITESPACE, $content]); } private function getIndentAt(Tokens $tokens, $index) { for (; $index >= 0; --$index) { if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML, T_OPEN_TAG])) { continue; } $content = $tokens[$index]->getContent(); if ($tokens[$index]->isWhitespace() && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG)) { $content = $tokens[$index - 1]->getContent().$content; } if (1 === Preg::match('/\R(\h*)$/', $content, $matches)) { return $matches[1]; } } return ''; } } [\n 'baz' => true,\n ],\n];\n"), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } public function getPriority() { return -31; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $scopes = []; $previousLineInitialIndent = ''; $previousLineNewIndent = ''; foreach ($tokens as $index => $token) { $currentScope = [] !== $scopes ? \count($scopes) - 1 : null; if ($token->isComment()) { continue; } if ( $token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN) || ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_ARRAY)) ) { $endIndex = $tokens->findBlockEnd( $token->equals('(') ? Tokens::BLOCK_TYPE_PARENTHESIS_BRACE : Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index ); $scopes[] = [ 'type' => 'array', 'end_index' => $endIndex, 'initial_indent' => $this->getLineIndentation($tokens, $index), ]; continue; } if (null === $currentScope) { continue; } if ($token->isWhitespace()) { if (!Preg::match('/\R/', $token->getContent())) { continue; } if ('array' === $scopes[$currentScope]['type']) { $indent = false; for ($searchEndIndex = $index + 1; $searchEndIndex < $scopes[$currentScope]['end_index']; ++$searchEndIndex) { $searchEndToken = $tokens[$searchEndIndex]; if ( (!$searchEndToken->isWhitespace() && !$searchEndToken->isComment()) || ($searchEndToken->isWhitespace() && Preg::match('/\R/', $searchEndToken->getContent())) ) { $indent = true; break; } } $content = Preg::replace( '/(\R+)\h*$/', '$1'.$scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''), $token->getContent() ); $previousLineInitialIndent = $this->extractIndent($token->getContent()); $previousLineNewIndent = $this->extractIndent($content); } else { $content = Preg::replace( '/(\R)'.preg_quote($scopes[$currentScope]['initial_indent'], '/').'(\h*)$/', '$1'.$scopes[$currentScope]['new_indent'].'$2', $token->getContent() ); } $tokens[$index] = new Token([T_WHITESPACE, $content]); continue; } if ($index === $scopes[$currentScope]['end_index']) { while ([] !== $scopes && $index === $scopes[$currentScope]['end_index']) { array_pop($scopes); --$currentScope; } continue; } if ($token->equals(',')) { continue; } if ('expression' !== $scopes[$currentScope]['type']) { $endIndex = $this->findExpressionEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); if ($endIndex === $index) { continue; } $scopes[] = [ 'type' => 'expression', 'end_index' => $endIndex, 'initial_indent' => $previousLineInitialIndent, 'new_indent' => $previousLineNewIndent, ]; } } } private function findExpressionEndIndex(Tokens $tokens, $index, $parentScopeEndIndex) { $endIndex = null; for ($searchEndIndex = $index + 1; $searchEndIndex < $parentScopeEndIndex; ++$searchEndIndex) { $searchEndToken = $tokens[$searchEndIndex]; if ($searchEndToken->equalsAny(['(', '{']) || $searchEndToken->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $type = Tokens::detectBlockType($searchEndToken); $searchEndIndex = $tokens->findBlockEnd( $type['type'], $searchEndIndex ); continue; } if ($searchEndToken->equals(',')) { $endIndex = $tokens->getPrevMeaningfulToken($searchEndIndex); break; } } if (null !== $endIndex) { return $endIndex; } return $tokens->getPrevMeaningfulToken($parentScopeEndIndex); } private function getLineIndentation(Tokens $tokens, $index) { $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index); if (null === $newlineTokenIndex) { return ''; } return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex)); } private function extractIndent($content) { if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) { return $matches[1]; } return ''; } private function getPreviousNewlineTokenIndex(Tokens $tokens, $index) { while ($index > 0) { $index = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE], [T_INLINE_HTML]]); if (null === $index) { break; } if ($this->isNewLineToken($tokens, $index)) { return $index; } } return null; } private function isNewLineToken(Tokens $tokens, $index) { if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) { return false; } return (bool) Preg::match('/\R/', $this->computeNewLineContent($tokens, $index)); } private function computeNewLineContent(Tokens $tokens, $index) { $content = $tokens[$index]->getContent(); if (0 !== $index && $tokens[$index - 1]->equalsAny([[T_OPEN_TAG], [T_CLOSE_TAG]])) { $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content; } return $content; } } isTokenKindFound(T_STRING); } public function isRisky() { return true; } public function getPriority() { return 11; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $map = null; if (null === $map) { $trueToken = new Token([T_STRING, 'true']); $map = [ 'array_keys' => [null, null, $trueToken], 'array_search' => [null, null, $trueToken], 'base64_decode' => [null, $trueToken], 'in_array' => [null, null, $trueToken], 'mb_detect_encoding' => [null, [new Token([T_STRING, 'mb_detect_order']), new Token('('), new Token(')')], $trueToken], ]; } for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; $nextIndex = $tokens->getNextMeaningfulToken($index); if (null !== $nextIndex && !$tokens[$nextIndex]->equals('(')) { continue; } $lowercaseContent = strtolower($token->getContent()); if ($token->isGivenKind(T_STRING) && isset($map[$lowercaseContent])) { $this->fixFunction($tokens, $index, $map[$lowercaseContent]); } } } private function fixFunction(Tokens $tokens, $functionIndex, array $functionParams) { $startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['(']); $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex); $paramsQuantity = 0; $expectParam = true; for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) { $token = $tokens[$index]; if ($expectParam && !$token->isWhitespace() && !$token->isComment()) { ++$paramsQuantity; $expectParam = false; } if ($token->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } if ($token->equals(',')) { $expectParam = true; continue; } } $functionParamsQuantity = \count($functionParams); if ($paramsQuantity === $functionParamsQuantity) { return; } $tokensToInsert = []; for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) { if (!$functionParams[$i]) { return; } $tokensToInsert[] = new Token(','); $tokensToInsert[] = new Token([T_WHITESPACE, ' ']); if (!\is_array($functionParams[$i])) { $tokensToInsert[] = clone $functionParams[$i]; continue; } foreach ($functionParams[$i] as $param) { $tokensToInsert[] = clone $param; } } $beforeEndBraceIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); if ($tokens[$beforeEndBraceIndex]->equals(',')) { array_shift($tokensToInsert); $tokensToInsert[] = new Token(','); } $tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert); } } isAnyTokenKindsFound([T_IS_EQUAL, T_IS_NOT_EQUAL]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $map = [ T_IS_EQUAL => [ 'id' => T_IS_IDENTICAL, 'content' => '===', ], T_IS_NOT_EQUAL => [ 'id' => T_IS_NOT_IDENTICAL, 'content' => '!==', ], ]; foreach ($tokens as $index => $token) { $tokenId = $token->getId(); if (isset($map[$tokenId])) { $tokens[$index] = new Token([$map[$tokenId]['id'], $map[$tokenId]['content']]); } } } } = 7.0.', [ new VersionSpecificCodeSample( "= 70000 && isset($tokens[0]) && $tokens[0]->isGivenKind(T_OPEN_TAG); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $searchIndex = $tokens->getNextMeaningfulToken(0); if (null === $searchIndex) { $this->insertSequence($tokens); return; } $sequenceLocation = $tokens->findSequence([[T_DECLARE, 'declare'], '(', [T_STRING, 'strict_types'], '=', [T_LNUMBER], ')'], $searchIndex, null, false); if (null === $sequenceLocation) { $this->insertSequence($tokens); return; } $this->fixStrictTypesCasingAndValue($tokens, $sequenceLocation); } private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence) { foreach ($sequence as $index => $token) { if ($token->isGivenKind(T_STRING)) { $tokens[$index] = new Token([T_STRING, strtolower($token->getContent())]); continue; } if ($token->isGivenKind(T_LNUMBER)) { $tokens[$index] = new Token([T_LNUMBER, '1']); break; } } } private function insertSequence(Tokens $tokens) { $sequence = [ new Token([T_DECLARE, 'declare']), new Token('('), new Token([T_STRING, 'strict_types']), new Token('='), new Token([T_LNUMBER, '1']), new Token(')'), new Token(';'), ]; $endIndex = \count($sequence); $tokens->insertAt(1, $sequence); if (false !== strpos($tokens[0]->getContent(), "\n")) { $tokens[0] = new Token([$tokens[0]->getId(), trim($tokens[0]->getContent()).' ']); } if ($endIndex === \count($tokens) - 1) { return; } $lineEnding = $this->whitespacesConfig->getLineEnding(); if (!$tokens[1 + $endIndex]->isWhitespace()) { $tokens->insertAt(1 + $endIndex, new Token([T_WHITESPACE, $lineEnding])); return; } $content = $tokens[1 + $endIndex]->getContent(); $tokens[1 + $endIndex] = new Token([T_WHITESPACE, $lineEnding.ltrim($content, " \t")]); } } false, 'before_array_assignments_equals' => false] ), ], 'There must not be any space around parentheses; commas must be preceded by no space and followed by one space; there must be no space around named arguments assignment operator; there must be one space around array assignment operator.' ); } public function getPriority() { return 0; } public function configure(array $configuration = null) { parent::configure($configuration); if (!$this->configuration['around_argument_assignments']) { foreach ([ 'before_argument_assignments', 'after_argument_assignments', ] as $newOption) { if (!\array_key_exists($newOption, $configuration)) { $this->configuration[$newOption] = null; } } } if (!$this->configuration['around_array_assignments']) { foreach ([ 'before_array_assignments_equals', 'after_array_assignments_equals', 'before_array_assignments_colon', 'after_array_assignments_colon', ] as $newOption) { if (!\array_key_exists($newOption, $configuration)) { $this->configuration[$newOption] = null; } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver(array_merge( parent::createConfigurationDefinition()->getOptions(), [ (new FixerOptionBuilder('around_parentheses', 'Whether to fix spaces around parentheses.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('around_commas', 'Whether to fix spaces around commas.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('around_argument_assignments', 'Whether to fix spaces around argument assignment operator.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->setDeprecationMessage('Use options `before_argument_assignments` and `after_argument_assignments` instead.') ->getOption(), (new FixerOptionBuilder('before_argument_assignments', 'Whether to add, remove or ignore spaces before argument assignment operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('after_argument_assignments', 'Whether to add, remove or ignore spaces after argument assignment operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('around_array_assignments', 'Whether to fix spaces around array assignment operators.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->setDeprecationMessage('Use options `before_array_assignments_equals`, `after_array_assignments_equals`, `before_array_assignments_colon` and `after_array_assignments_colon` instead.') ->getOption(), (new FixerOptionBuilder('before_array_assignments_equals', 'Whether to add, remove or ignore spaces before array `=` assignment operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('after_array_assignments_equals', 'Whether to add, remove or ignore spaces after array assignment `=` operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('before_array_assignments_colon', 'Whether to add, remove or ignore spaces before array `:` assignment operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('after_array_assignments_colon', 'Whether to add, remove or ignore spaces after array assignment `:` operator.')) ->setAllowedTypes(['null', 'bool']) ->setDefault(true) ->getOption(), ] )); } protected function fixAnnotations(Tokens $tokens) { if ($this->configuration['around_parentheses']) { $this->fixSpacesAroundParentheses($tokens); } if ($this->configuration['around_commas']) { $this->fixSpacesAroundCommas($tokens); } if ( null !== $this->configuration['before_argument_assignments'] || null !== $this->configuration['after_argument_assignments'] || null !== $this->configuration['before_array_assignments_equals'] || null !== $this->configuration['after_array_assignments_equals'] || null !== $this->configuration['before_array_assignments_colon'] || null !== $this->configuration['after_array_assignments_colon'] ) { $this->fixAroundAssignments($tokens); } } private function fixSpacesAroundParentheses(Tokens $tokens) { $inAnnotationUntilIndex = null; foreach ($tokens as $index => $token) { if (null !== $inAnnotationUntilIndex) { if ($index === $inAnnotationUntilIndex) { $inAnnotationUntilIndex = null; continue; } } elseif ($tokens[$index]->isType(DocLexer::T_AT)) { $endIndex = $tokens->getAnnotationEnd($index); if (null !== $endIndex) { $inAnnotationUntilIndex = $endIndex + 1; } continue; } if (null === $inAnnotationUntilIndex) { continue; } if (!$token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_CLOSE_PARENTHESIS])) { continue; } if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { $token = $tokens[$index - 1]; if ($token->isType(DocLexer::T_NONE)) { $token->clear(); } $token = $tokens[$index + 1]; } else { $token = $tokens[$index - 1]; } if ($token->isType(DocLexer::T_NONE)) { if (false !== strpos($token->getContent(), "\n")) { continue; } $token->clear(); } } } private function fixSpacesAroundCommas(Tokens $tokens) { $inAnnotationUntilIndex = null; foreach ($tokens as $index => $token) { if (null !== $inAnnotationUntilIndex) { if ($index === $inAnnotationUntilIndex) { $inAnnotationUntilIndex = null; continue; } } elseif ($tokens[$index]->isType(DocLexer::T_AT)) { $endIndex = $tokens->getAnnotationEnd($index); if (null !== $endIndex) { $inAnnotationUntilIndex = $endIndex; } continue; } if (null === $inAnnotationUntilIndex) { continue; } if (!$token->isType(DocLexer::T_COMMA)) { continue; } $token = $tokens[$index - 1]; if ($token->isType(DocLexer::T_NONE)) { $token->clear(); } if ($index < \count($tokens) - 1 && !Preg::match('/^\s/', $tokens[$index + 1]->getContent())) { $tokens->insertAt($index + 1, new Token(DocLexer::T_NONE, ' ')); } } } private function fixAroundAssignments(Tokens $tokens) { $beforeArguments = $this->configuration['before_argument_assignments']; $afterArguments = $this->configuration['after_argument_assignments']; $beforeArraysEquals = $this->configuration['before_array_assignments_equals']; $afterArraysEquals = $this->configuration['after_array_assignments_equals']; $beforeArraysColon = $this->configuration['before_array_assignments_colon']; $afterArraysColon = $this->configuration['after_array_assignments_colon']; $scopes = []; foreach ($tokens as $index => $token) { $endScopeType = end($scopes); if (false !== $endScopeType && $token->isType($endScopeType)) { array_pop($scopes); continue; } if ($tokens[$index]->isType(DocLexer::T_AT)) { $scopes[] = DocLexer::T_CLOSE_PARENTHESIS; continue; } if ($tokens[$index]->isType(DocLexer::T_OPEN_CURLY_BRACES)) { $scopes[] = DocLexer::T_CLOSE_CURLY_BRACES; continue; } if (DocLexer::T_CLOSE_PARENTHESIS === $endScopeType && $token->isType(DocLexer::T_EQUALS)) { $this->updateSpacesAfter($tokens, $index, $afterArguments); $this->updateSpacesBefore($tokens, $index, $beforeArguments); continue; } if (DocLexer::T_CLOSE_CURLY_BRACES === $endScopeType) { if ($token->isType(DocLexer::T_EQUALS)) { $this->updateSpacesAfter($tokens, $index, $afterArraysEquals); $this->updateSpacesBefore($tokens, $index, $beforeArraysEquals); continue; } if ($token->isType(DocLexer::T_COLON)) { $this->updateSpacesAfter($tokens, $index, $afterArraysColon); $this->updateSpacesBefore($tokens, $index, $beforeArraysColon); } } } } private function updateSpacesAfter(Tokens $tokens, $index, $insert) { $this->updateSpacesAt($tokens, $index + 1, $index + 1, $insert); } private function updateSpacesBefore(Tokens $tokens, $index, $insert) { $this->updateSpacesAt($tokens, $index - 1, $index, $insert); } private function updateSpacesAt(Tokens $tokens, $index, $insertIndex, $insert) { if (null === $insert) { return; } $token = $tokens[$index]; if ($insert) { if (!$token->isType(DocLexer::T_NONE)) { $tokens->insertAt($insertIndex, $token = new Token()); } $token->setContent(' '); } elseif ($token->isType(DocLexer::T_NONE)) { $token->clear(); } } } ':'] ), ] ); } public function getPriority() { return 1; } protected function createConfigurationDefinition() { $options = parent::createConfigurationDefinition()->getOptions(); $operator = new FixerOptionBuilder('operator', 'The operator to use.'); $options[] = $operator ->setAllowedValues(['=', ':']) ->setDefault('=') ->getOption() ; return new FixerConfigurationResolver($options); } protected function fixAnnotations(Tokens $tokens) { $scopes = []; foreach ($tokens as $token) { if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { $scopes[] = 'annotation'; continue; } if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) { $scopes[] = 'array'; continue; } if ($token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { array_pop($scopes); continue; } if ('array' === end($scopes) && $token->isType([DocLexer::T_EQUALS, DocLexer::T_COLON])) { $token->setContent($this->configuration['operator']); } } } } true] ), ] ); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver(array_merge( parent::createConfigurationDefinition()->getOptions(), [ (new FixerOptionBuilder('indent_mixed_lines', 'Whether to indent lines that have content before closing parenthesis.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ] )); } protected function fixAnnotations(Tokens $tokens) { $annotationPositions = []; for ($index = 0, $max = \count($tokens); $index < $max; ++$index) { if (!$tokens[$index]->isType(DocLexer::T_AT)) { continue; } $annotationEndIndex = $tokens->getAnnotationEnd($index); if (null === $annotationEndIndex) { return; } $annotationPositions[] = [$index, $annotationEndIndex]; $index = $annotationEndIndex; } $indentLevel = 0; foreach ($tokens as $index => $token) { if (!$token->isType(DocLexer::T_NONE) || false === strpos($token->getContent(), "\n")) { continue; } if (!$this->indentationCanBeFixed($tokens, $index, $annotationPositions)) { continue; } $braces = $this->getLineBracesCount($tokens, $index); $delta = $braces[0] - $braces[1]; $mixedBraces = 0 === $delta && $braces[0] > 0; $extraIndentLevel = 0; if ($indentLevel > 0 && ($delta < 0 || $mixedBraces)) { --$indentLevel; if ($this->configuration['indent_mixed_lines'] && $this->isClosingLineWithMeaningfulContent($tokens, $index)) { $extraIndentLevel = 1; } } $token->setContent(Preg::replace( '/(\n( +\*)?) *$/', '$1'.str_repeat(' ', 4 * ($indentLevel + $extraIndentLevel) + 1), $token->getContent() )); if ($delta > 0 || $mixedBraces) { ++$indentLevel; } } } private function getLineBracesCount(Tokens $tokens, $index) { $opening = 0; $closing = 0; while (isset($tokens[++$index])) { $token = $tokens[$index]; if ($token->isType(DocLexer::T_NONE) && false !== strpos($token->getContent(), "\n")) { break; } if ($token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_OPEN_CURLY_BRACES])) { ++$opening; continue; } if (!$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { continue; } if ($opening > 0) { --$opening; } else { ++$closing; } } return [$opening, $closing]; } private function isClosingLineWithMeaningfulContent(Tokens $tokens, $index) { while (isset($tokens[++$index])) { $token = $tokens[$index]; if ($token->isType(DocLexer::T_NONE)) { if (false !== strpos($token->getContent(), "\n")) { return false; } continue; } return !$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES]); } return false; } private function indentationCanBeFixed(Tokens $tokens, $newLineTokenIndex, array $annotationPositions) { foreach ($annotationPositions as $position) { if ($newLineTokenIndex >= $position[0] && $newLineTokenIndex <= $position[1]) { return true; } } for ($index = $newLineTokenIndex + 1, $max = \count($tokens); $index < $max; ++$index) { $token = $tokens[$index]; if (false !== strpos($token->getContent(), "\n")) { return false; } return $tokens[$index]->isType(DocLexer::T_AT); } return false; } } 'with_braces'] ), ] ); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver(array_merge( parent::createConfigurationDefinition()->getOptions(), [ (new FixerOptionBuilder('syntax', 'Whether to add or remove braces.')) ->setAllowedValues(['with_braces', 'without_braces']) ->setDefault('without_braces') ->getOption(), ] )); } protected function fixAnnotations(Tokens $tokens) { if ('without_braces' === $this->configuration['syntax']) { $this->removesBracesFromAnnotations($tokens); } else { $this->addBracesToAnnotations($tokens); } } private function addBracesToAnnotations(Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$tokens[$index]->isType(DocLexer::T_AT)) { continue; } $braceIndex = $tokens->getNextMeaningfulToken($index + 1); if (null !== $braceIndex && $tokens[$braceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { continue; } $tokens->insertAt($index + 2, new Token(DocLexer::T_OPEN_PARENTHESIS, '(')); $tokens->insertAt($index + 3, new Token(DocLexer::T_CLOSE_PARENTHESIS, ')')); } } private function removesBracesFromAnnotations(Tokens $tokens) { for ($index = 0, $max = \count($tokens); $index < $max; ++$index) { if (!$tokens[$index]->isType(DocLexer::T_AT)) { continue; } $openBraceIndex = $tokens->getNextMeaningfulToken($index + 1); if (null === $openBraceIndex) { continue; } if (!$tokens[$openBraceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { continue; } $closeBraceIndex = $tokens->getNextMeaningfulToken($openBraceIndex); if (null === $closeBraceIndex) { continue; } if (!$tokens[$closeBraceIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { continue; } for ($currentIndex = $index + 2; $currentIndex <= $closeBraceIndex; ++$currentIndex) { $tokens[$currentIndex]->clear(); } } } } true, 'import_constants' => true, 'import_functions' => true] ), new CodeSample( ' false, 'import_constants' => false, 'import_functions' => false] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_DOC_COMMENT, T_NS_SEPARATOR, T_USE]) && $tokens->isTokenKindFound(T_NAMESPACE) && (Tokens::isLegacyMode() || 1 === $tokens->countTokenKind(T_NAMESPACE)) && $tokens->isMonolithicPhp(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $namespaceAnalyses = (new NamespacesAnalyzer())->getDeclarations($tokens); if (1 !== \count($namespaceAnalyses) || '' === $namespaceAnalyses[0]->getFullName()) { return; } $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); $newImports = []; if (true === $this->configuration['import_constants']) { $newImports['const'] = $this->importConstants($tokens, $useDeclarations); } elseif (false === $this->configuration['import_constants']) { $this->fullyQualifyConstants($tokens, $useDeclarations); } if (true === $this->configuration['import_functions']) { $newImports['function'] = $this->importFunctions($tokens, $useDeclarations); } elseif (false === $this->configuration['import_functions']) { $this->fullyQualifyFunctions($tokens, $useDeclarations); } if (true === $this->configuration['import_classes']) { $newImports['class'] = $this->importClasses($tokens, $useDeclarations); } elseif (false === $this->configuration['import_classes']) { $this->fullyQualifyClasses($tokens, $useDeclarations); } $newImports = array_filter($newImports); if ($newImports) { $this->insertImports($tokens, $newImports, $useDeclarations); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('import_constants', 'Whether to import, not import or ignore global constants.')) ->setDefault(null) ->setAllowedValues([true, false, null]) ->getOption(), (new FixerOptionBuilder('import_functions', 'Whether to import, not import or ignore global functions.')) ->setDefault(null) ->setAllowedValues([true, false, null]) ->getOption(), (new FixerOptionBuilder('import_classes', 'Whether to import, not import or ignore global classes.')) ->setDefault(true) ->setAllowedValues([true, false, null]) ->getOption(), ]); } private function importConstants(Tokens $tokens, array $useDeclarations) { list($global, $other) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isConstant(); }, true); for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { $token = $tokens[$index]; if ($token->isClassy()) { $index = $tokens->getNextTokenOfKind($index, ['{']); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if (!$token->isGivenKind(T_CONST)) { continue; } $index = $tokens->getNextMeaningfulToken($index); $other[$tokens[$index]->getContent()] = true; } $analyzer = new TokensAnalyzer($tokens); $indexes = []; for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } $name = $token->getContent(); if (isset($other[$name])) { continue; } if (!$analyzer->isConstantInvocation($index)) { continue; } $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { if (!isset($global[$name])) { $other[$name] = true; } continue; } $prevIndex = $tokens->getPrevMeaningfulToken($nsSeparatorIndex); if ($tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_STRING])) { continue; } $indexes[] = $index; } return $this->prepareImports($tokens, $indexes, $global, $other, true); } private function importFunctions(Tokens $tokens, array $useDeclarations) { list($global, $other) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isFunction(); }, false); foreach ($this->findFunctionDeclarations($tokens, 0, $tokens->count() - 1) as $name) { $other[strtolower($name)] = true; } $analyzer = new FunctionsAnalyzer(); $indexes = []; for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } $name = strtolower($token->getContent()); if (isset($other[$name])) { continue; } if (!$analyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { if (!isset($global[$name])) { $other[$name] = true; } continue; } $indexes[] = $index; } return $this->prepareImports($tokens, $indexes, $global, $other, false); } private function importClasses(Tokens $tokens, array $useDeclarations) { list($global, $other) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isClass(); }, false); $docBlocks = []; for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_DOC_COMMENT)) { $docBlocks[$index] = new DocBlock($token->getContent()); $this->traverseDocBlockTypes($docBlocks[$index], static function ($type) use ($global, &$other) { if (false !== strpos($type, '\\')) { return; } $name = strtolower($type); if (!isset($global[$name])) { $other[$name] = true; } }); } if (!$token->isClassy()) { continue; } $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->isGivenKind(T_STRING)) { $other[strtolower($tokens[$index]->getContent())] = true; } } $analyzer = new ClassyAnalyzer(); $indexes = []; for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } $name = strtolower($token->getContent()); if (isset($other[$name])) { continue; } if (!$analyzer->isClassyInvocation($tokens, $index)) { continue; } $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { if (!isset($global[$name])) { $other[$name] = true; } continue; } if ($tokens[$tokens->getPrevMeaningfulToken($nsSeparatorIndex)]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_STRING])) { continue; } $indexes[] = $index; } $imports = []; foreach ($docBlocks as $index => $docBlock) { $changed = $this->traverseDocBlockTypes($docBlock, static function ($type) use ($global, $other, &$imports) { if ('\\' !== $type[0]) { return $type; } $name = substr($type, 1); $checkName = strtolower($name); if (false !== strpos($checkName, '\\') || isset($other[$checkName])) { return $type; } if (isset($global[$checkName])) { return \is_string($global[$checkName]) ? $global[$checkName] : $name; } $imports[$checkName] = $name; return $name; }); if ($changed) { $tokens[$index] = new Token([T_DOC_COMMENT, $docBlock->getContent()]); } } return $imports + $this->prepareImports($tokens, $indexes, $global, $other, false); } private function prepareImports(Tokens $tokens, array $indexes, array $global, array $other, $caseSensitive) { $imports = []; foreach ($indexes as $index) { $name = $tokens[$index]->getContent(); $checkName = $caseSensitive ? $name : strtolower($name); if (isset($other[$checkName])) { continue; } if (!isset($global[$checkName])) { $imports[$checkName] = $name; } elseif (\is_string($global[$checkName])) { $tokens[$index] = new Token([T_STRING, $global[$checkName]]); } $tokens->clearAt($tokens->getPrevMeaningfulToken($index)); } return $imports; } private function insertImports(Tokens $tokens, array $imports, array $useDeclarations) { if ($useDeclarations) { $useDeclaration = end($useDeclarations); $index = $useDeclaration->getEndIndex() + 1; } else { $namespace = (new NamespacesAnalyzer())->getDeclarations($tokens)[0]; $index = $namespace->getEndIndex() + 1; } $lineEnding = $this->whitespacesConfig->getLineEnding(); if (!$tokens[$index]->isWhitespace() || false === strpos($tokens[$index]->getContent(), "\n")) { $tokens->insertAt($index, new Token([T_WHITESPACE, $lineEnding])); } foreach ($imports as $type => $typeImports) { foreach ($typeImports as $name) { $items = [ new Token([T_WHITESPACE, $lineEnding]), new Token([T_USE, 'use']), new Token([T_WHITESPACE, ' ']), ]; if ('const' === $type) { $items[] = new Token([CT::T_CONST_IMPORT, 'const']); $items[] = new Token([T_WHITESPACE, ' ']); } elseif ('function' === $type) { $items[] = new Token([CT::T_FUNCTION_IMPORT, 'function']); $items[] = new Token([T_WHITESPACE, ' ']); } $items[] = new Token([T_STRING, $name]); $items[] = new Token(';'); $tokens->insertAt($index, $items); } } } private function fullyQualifyConstants(Tokens $tokens, array $useDeclarations) { if (!$tokens->isTokenKindFound(CT::T_CONST_IMPORT)) { return; } list($global) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isConstant() && !$declaration->isAliased(); }, true); if (!$global) { return; } $analyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } if (!isset($global[$token->getContent()])) { continue; } if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { continue; } if (!$analyzer->isConstantInvocation($index)) { continue; } $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } private function fullyQualifyFunctions(Tokens $tokens, array $useDeclarations) { if (!$tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { return; } list($global) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isFunction() && !$declaration->isAliased(); }, false); if (!$global) { return; } $analyzer = new FunctionsAnalyzer(); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } if (!isset($global[strtolower($token->getContent())])) { continue; } if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { continue; } if (!$analyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } private function fullyQualifyClasses(Tokens $tokens, array $useDeclarations) { if (!$tokens->isTokenKindFound(T_USE)) { return; } list($global) = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) { return $declaration->isClass() && !$declaration->isAliased(); }, false); if (!$global) { return; } $analyzer = new ClassyAnalyzer(); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_DOC_COMMENT)) { $doc = new DocBlock($token->getContent()); $changed = $this->traverseDocBlockTypes($doc, static function ($type) use ($global) { if (!isset($global[strtolower($type)])) { return $type; } return '\\'.$type; }); if ($changed) { $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } continue; } if (!$token->isGivenKind(T_STRING)) { continue; } if (!isset($global[strtolower($token->getContent())])) { continue; } if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { continue; } if (!$analyzer->isClassyInvocation($tokens, $index)) { continue; } $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } private function filterUseDeclarations(array $declarations, callable $callback, $caseSensitive) { $global = []; $other = []; foreach ($declarations as $declaration) { if (!$callback($declaration)) { continue; } $fullName = ltrim($declaration->getFullName(), '\\'); if (false !== strpos($fullName, '\\')) { $name = $caseSensitive ? $declaration->getShortName() : strtolower($declaration->getShortName()); $other[$name] = true; continue; } $checkName = $caseSensitive ? $fullName : strtolower($fullName); $alias = $declaration->getShortName(); $global[$checkName] = $alias === $fullName ? true : $alias; } return [$global, $other]; } private function findFunctionDeclarations(Tokens $tokens, $start, $end) { for ($index = $start; $index <= $end; ++$index) { $token = $tokens[$index]; if ($token->isClassy()) { $classStart = $tokens->getNextTokenOfKind($index, ['{']); $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart); for ($index = $classStart; $index <= $classEnd; ++$index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $methodStart = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$methodStart]->equals(';')) { $index = $methodStart; continue; } $methodEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStart); foreach ($this->findFunctionDeclarations($tokens, $methodStart, $methodEnd) as $function) { yield $function; } $index = $methodEnd; } continue; } if (!$token->isGivenKind(T_FUNCTION)) { continue; } $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { $index = $tokens->getNextMeaningfulToken($index); } if ($tokens[$index]->isGivenKind(T_STRING)) { yield $tokens[$index]->getContent(); } } } private function traverseDocBlockTypes(DocBlock $doc, callable $callback) { $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); if (!$annotations) { return false; } $changed = false; foreach ($annotations as $annotation) { $types = $new = $annotation->getTypes(); foreach ($types as $i => $fullType) { $newFullType = $fullType; Preg::matchAll('/[\\\\\w]+/', $fullType, $matches, PREG_OFFSET_CAPTURE); foreach (array_reverse($matches[0]) as list($type, $offset)) { $newType = $callback($type); if (null !== $newType && $type !== $newType) { $newFullType = substr_replace($newFullType, $newType, $offset, \strlen($type)); } } $new[$i] = $newFullType; } if ($types !== $new) { $annotation->setTypes($new); $changed = true; } } return $changed; } } isTokenKindFound(T_USE); } public function supports(\SplFileInfo $file) { $path = $file->getPathname(); if (false !== strpos($path, \DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR) && false === strpos($path, \DIRECTORY_SEPARATOR.'tests'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR) ) { return false; } return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); if (0 === \count($useDeclarations)) { return; } foreach ((new NamespacesAnalyzer())->getDeclarations($tokens) as $namespace) { $currentNamespaceUseDeclarations = array_filter( $useDeclarations, static function (NamespaceUseAnalysis $useDeclaration) use ($namespace) { return $useDeclaration->getStartIndex() >= $namespace->getScopeStartIndex() && $useDeclaration->getEndIndex() <= $namespace->getScopeEndIndex() ; } ); $usagesSearchIgnoredIndexes = []; foreach ($currentNamespaceUseDeclarations as $useDeclaration) { $usagesSearchIgnoredIndexes[$useDeclaration->getStartIndex()] = $useDeclaration->getEndIndex(); } foreach ($currentNamespaceUseDeclarations as $useDeclaration) { if (!$this->isImportUsed($tokens, $namespace, $usagesSearchIgnoredIndexes, $useDeclaration->getShortName())) { $this->removeUseDeclaration($tokens, $useDeclaration); } } $this->removeUsesInSameNamespace($tokens, $currentNamespaceUseDeclarations, $namespace); } } private function isImportUsed(Tokens $tokens, NamespaceAnalysis $namespace, array $ignoredIndexes, $shortName) { $namespaceEndIndex = $namespace->getScopeEndIndex(); for ($index = $namespace->getScopeStartIndex(); $index <= $namespaceEndIndex; ++$index) { if (isset($ignoredIndexes[$index])) { $index = $ignoredIndexes[$index]; continue; } $token = $tokens[$index]; if ($token->isGivenKind(T_STRING)) { $prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ($prevMeaningfulToken->isGivenKind(T_NAMESPACE)) { $index = $tokens->getNextTokenOfKind($index, [';', '{', [T_CLOSE_TAG]]); continue; } if ( 0 === strcasecmp($shortName, $token->getContent()) && !$prevMeaningfulToken->isGivenKind([T_NS_SEPARATOR, T_CONST, T_OBJECT_OPERATOR, T_DOUBLE_COLON]) ) { return true; } continue; } if ($token->isComment() && Preg::match( '/(?getContent() ) ) { return true; } } return false; } private function removeUseDeclaration(Tokens $tokens, NamespaceUseAnalysis $useDeclaration) { for ($index = $useDeclaration->getEndIndex() - 1; $index >= $useDeclaration->getStartIndex(); --$index) { if ($tokens[$index]->isComment()) { continue; } if (!$tokens[$index]->isWhitespace() || false === strpos($tokens[$index]->getContent(), "\n")) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); continue; } $prevIndex = $tokens->getPrevNonWhitespace($index); if ($tokens[$prevIndex]->isComment()) { $content = $tokens[$index]->getContent(); $tokens[$index] = new Token([T_WHITESPACE, substr($content, strrpos($content, "\n"))]); } else { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } if ($tokens[$useDeclaration->getEndIndex()]->equals(';')) { $tokens->clearAt($useDeclaration->getEndIndex()); } $prevIndex = $useDeclaration->getStartIndex() - 1; $prevToken = $tokens[$prevIndex]; if ($prevToken->isWhitespace()) { $content = rtrim($prevToken->getContent(), " \t"); if ('' === $content) { $tokens->clearAt($prevIndex); } else { $tokens[$prevIndex] = new Token([T_WHITESPACE, $content]); } $prevToken = $tokens[$prevIndex]; } if (!isset($tokens[$useDeclaration->getEndIndex() + 1])) { return; } $nextIndex = $tokens->getNonEmptySibling($useDeclaration->getEndIndex(), 1); if (null === $nextIndex) { return; } $nextToken = $tokens[$nextIndex]; if ($nextToken->isWhitespace()) { $content = Preg::replace( "#^\r\n|^\n#", '', ltrim($nextToken->getContent(), " \t"), 1 ); if ('' !== $content) { $tokens[$nextIndex] = new Token([T_WHITESPACE, $content]); } else { $tokens->clearAt($nextIndex); } $nextToken = $tokens[$nextIndex]; } if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) { $content = $prevToken->getContent().$nextToken->getContent(); if ('' !== $content) { $tokens[$nextIndex] = new Token([T_WHITESPACE, $content]); } else { $tokens->clearAt($nextIndex); } $tokens->clearAt($prevIndex); } } private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, NamespaceAnalysis $namespaceDeclaration) { $namespace = $namespaceDeclaration->getFullName(); $nsLength = \strlen($namespace.'\\'); foreach ($useDeclarations as $useDeclaration) { if ($useDeclaration->isAliased()) { continue; } $useDeclarationFullName = ltrim($useDeclaration->getFullName(), '\\'); if (0 !== strpos($useDeclarationFullName, $namespace.'\\')) { continue; } $partName = substr($useDeclarationFullName, $nsLength); if (false === strpos($partName, '\\')) { $this->removeUseDeclaration($tokens, $useDeclaration); } } } } isTokenKindFound(T_FUNCTION) && ( \count((new NamespacesAnalyzer())->getDeclarations($tokens)) || \count((new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens)) ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $lastIndex = $tokens->count() - 1; for ($index = $lastIndex; $index >= 0; --$index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $this->fixFunctionReturnType($tokens, $index); $this->fixFunctionArguments($tokens, $index); } } private function fixFunctionArguments(Tokens $tokens, $index) { $arguments = (new FunctionsAnalyzer())->getFunctionArguments($tokens, $index); foreach ($arguments as $argument) { if (!$argument->hasTypeAnalysis()) { continue; } $this->detectAndReplaceTypeWithShortType($tokens, $argument->getTypeAnalysis()); } } private function fixFunctionReturnType(Tokens $tokens, $index) { if (\PHP_VERSION_ID < 70000) { return; } $returnType = (new FunctionsAnalyzer())->getFunctionReturnType($tokens, $index); if (!$returnType) { return; } $this->detectAndReplaceTypeWithShortType($tokens, $returnType); } private function detectAndReplaceTypeWithShortType( Tokens $tokens, TypeAnalysis $type ) { if ($type->isReservedType()) { return; } $typeName = $type->getName(); if (0 !== strpos($typeName, '\\')) { return; } $shortType = (new TypeShortNameResolver())->resolve($tokens, $typeName); if ($shortType === $typeName) { return; } $shortType = (new NamespacedStringTokenGenerator())->generate($shortType); if (true === $type->isNullable()) { array_unshift($shortType, new Token([CT::T_NULLABLE_TYPE, '?'])); } $tokens->overrideRange( $type->getStartIndex(), $type->getEndIndex(), $shortType ); } } isTokenKindFound(T_USE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $usesIndexes = $tokensAnalyzer->getImportUseIndexes(); foreach ($usesIndexes as $idx) { $nextTokenIdx = $tokens->getNextMeaningfulToken($idx); $nextToken = $tokens[$nextTokenIdx]; if ($nextToken->isGivenKind(T_NS_SEPARATOR)) { $this->removeLeadingImportSlash($tokens, $nextTokenIdx); } elseif ($nextToken->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { $nextTokenIdx = $tokens->getNextMeaningfulToken($nextTokenIdx); if ($tokens[$nextTokenIdx]->isGivenKind(T_NS_SEPARATOR)) { $this->removeLeadingImportSlash($tokens, $nextTokenIdx); } } } } private function removeLeadingImportSlash(Tokens $tokens, $index) { $previousIndex = $tokens->getPrevNonWhitespace($index); if ( $previousIndex < $index - 1 || $tokens[$previousIndex]->isComment() ) { $tokens->clearAt($index); return; } $tokens[$index] = new Token([T_WHITESPACE, ' ']); } } isTokenKindFound(T_USE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $uses = array_reverse($tokensAnalyzer->getImportUseIndexes()); foreach ($uses as $index) { $endIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); $groupClose = $tokens->getPrevMeaningfulToken($endIndex); if ($tokens[$groupClose]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { $this->fixGroupUse($tokens, $index, $endIndex); } else { $this->fixMultipleUse($tokens, $index, $endIndex); } } } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode("\n", $tokens[$index - 1]->getContent()); return end($explodedContent); } private function getGroupDeclaration(Tokens $tokens, $index) { $groupPrefix = ''; $comment = ''; $groupOpenIndex = null; for ($i = $index + 1;; ++$i) { if ($tokens[$i]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { $groupOpenIndex = $i; break; } if ($tokens[$i]->isComment()) { $comment .= $tokens[$i]->getContent(); if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i + 1]->isWhitespace()) { $groupPrefix .= ' '; } continue; } if ($tokens[$i]->isWhitespace()) { $groupPrefix .= ' '; continue; } $groupPrefix .= $tokens[$i]->getContent(); } return [ rtrim($groupPrefix), $groupOpenIndex, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupOpenIndex), $comment, ]; } private function getGroupStatements(Tokens $tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment) { $statements = []; $statement = $groupPrefix; for ($i = $groupOpenIndex + 1; $i <= $groupCloseIndex; ++$i) { $token = $tokens[$i]; if ($token->equals(',') && $tokens[$tokens->getNextMeaningfulToken($i)]->equals([CT::T_GROUP_IMPORT_BRACE_CLOSE])) { continue; } if ($token->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { $statements[] = 'use'.$statement.';'; $statement = $groupPrefix; continue; } if ($token->isWhitespace()) { $j = $tokens->getNextMeaningfulToken($i); if ($tokens[$j]->equals([T_AS])) { $statement .= ' as '; $i += 2; } elseif ($tokens[$j]->equals([T_FUNCTION])) { $statement = ' function'.$statement; $i += 2; } elseif ($tokens[$j]->equals([T_CONST])) { $statement = ' const'.$statement; $i += 2; } if ($token->isWhitespace(" \t") || '//' !== substr($tokens[$i - 1]->getContent(), 0, 2)) { continue; } } $statement .= $token->getContent(); } if ('' !== $comment) { $statements[0] .= ' '.$comment; } return $statements; } private function fixGroupUse(Tokens $tokens, $index, $endIndex) { list($groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment) = $this->getGroupDeclaration($tokens, $index); $statements = $this->getGroupStatements($tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment); if (\count($statements) < 2) { return; } $tokens->clearRange($index, $groupCloseIndex); if ($tokens[$endIndex]->equals(';')) { $tokens->clearAt($endIndex); } $ending = $this->whitespacesConfig->getLineEnding(); $importTokens = Tokens::fromCode('clearAt(0); $importTokens->clearEmptyTokens(); $tokens->insertAt($index, $importTokens); } private function fixMultipleUse(Tokens $tokens, $index, $endIndex) { $ending = $this->whitespacesConfig->getLineEnding(); for ($i = $endIndex - 1; $i > $index; --$i) { if (!$tokens[$i]->equals(',')) { continue; } $tokens[$i] = new Token(';'); $i = $tokens->getNextMeaningfulToken($i); $tokens->insertAt($i, new Token([T_USE, 'use'])); $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); $indent = $this->detectIndent($tokens, $index); if ($tokens[$i - 1]->isWhitespace()) { $tokens[$i - 1] = new Token([T_WHITESPACE, $ending.$indent]); continue; } if (false === strpos($tokens[$i - 1]->getContent(), "\n")) { $tokens->insertAt($i, new Token([T_WHITESPACE, $ending.$indent])); } } } } self::SORT_LENGTH] ), new VersionSpecificCodeSample( " self::SORT_LENGTH, 'imports_order' => [ self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION, ], ] ), new VersionSpecificCodeSample( ' self::SORT_ALPHA, 'imports_order' => [ self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION, ], ] ), new VersionSpecificCodeSample( ' self::SORT_NONE, 'imports_order' => [ self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION, ], ] ), ] ); } public function getPriority() { return -30; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_USE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); if (0 === \count($namespacesImports)) { return; } $usesOrder = []; foreach ($namespacesImports as $uses) { $usesOrder[] = $this->getNewOrder(array_reverse($uses), $tokens); } $usesOrder = array_replace(...$usesOrder); $usesOrder = array_reverse($usesOrder, true); $mapStartToEnd = []; foreach ($usesOrder as $use) { $mapStartToEnd[$use['startIndex']] = $use['endIndex']; } foreach ($usesOrder as $index => $use) { $declarationTokens = Tokens::fromCode( sprintf( 'clearRange(0, 2); $declarationTokens->clearAt(\count($declarationTokens) - 1); $declarationTokens->clearEmptyTokens(); $tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens); if ($use['group']) { $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->equals(',')) { $tokens[$prev] = new Token(';'); $tokens->insertAt($prev + 1, new Token([T_USE, 'use'])); if (!$tokens[$prev + 2]->isWhitespace()) { $tokens->insertAt($prev + 2, new Token([T_WHITESPACE, ' '])); } } } } } protected function createConfigurationDefinition() { $supportedSortTypes = $this->supportedSortTypes; return new FixerConfigurationResolver([ (new AliasedFixerOptionBuilder( new FixerOptionBuilder('sort_algorithm', 'whether the statements should be sorted alphabetically or by length, or not sorted'), 'sortAlgorithm' )) ->setAllowedValues($this->supportedSortAlgorithms) ->setDefault(self::SORT_ALPHA) ->getOption(), (new AliasedFixerOptionBuilder( new FixerOptionBuilder('imports_order', 'Defines the order of import types.'), 'importsOrder' )) ->setAllowedTypes(['array', 'null']) ->setAllowedValues([static function ($value) use ($supportedSortTypes) { if (null !== $value) { $missing = array_diff($supportedSortTypes, $value); if (\count($missing)) { throw new InvalidOptionsException(sprintf( 'Missing sort %s "%s".', 1 === \count($missing) ? 'type' : 'types', implode('", "', $missing) )); } $unknown = array_diff($value, $supportedSortTypes); if (\count($unknown)) { throw new InvalidOptionsException(sprintf( 'Unknown sort %s "%s".', 1 === \count($unknown) ? 'type' : 'types', implode('", "', $unknown) )); } } return true; }]) ->setDefault(null) ->getOption(), ]); } private function sortAlphabetically(array $first, array $second) { $firstNamespace = str_replace('\\', ' ', $this->prepareNamespace($first['namespace'])); $secondNamespace = str_replace('\\', ' ', $this->prepareNamespace($second['namespace'])); return strcasecmp($firstNamespace, $secondNamespace); } private function sortByLength(array $first, array $second) { $firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']); $secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']); $firstNamespaceLength = \strlen($firstNamespace); $secondNamespaceLength = \strlen($secondNamespace); if ($firstNamespaceLength === $secondNamespaceLength) { $sortResult = strcasecmp($firstNamespace, $secondNamespace); } else { $sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1; } return $sortResult; } private function prepareNamespace($namespace) { return trim(Preg::replace('%/\*(.*)\*/%s', '', $namespace)); } private function getNewOrder(array $uses, Tokens $tokens) { $indexes = []; $originalIndexes = []; $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($i = \count($uses) - 1; $i >= 0; --$i) { $index = $uses[$i]; $startIndex = $tokens->getTokenNotOfKindsSibling($index + 1, 1, [T_WHITESPACE]); $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [T_CLOSE_TAG]]); $previous = $tokens->getPrevMeaningfulToken($endIndex); $group = $tokens[$previous]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE); if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { $type = self::IMPORT_TYPE_CONST; $index = $tokens->getNextNonWhitespace($startIndex); } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { $type = self::IMPORT_TYPE_FUNCTION; $index = $tokens->getNextNonWhitespace($startIndex); } else { $type = self::IMPORT_TYPE_CLASS; $index = $startIndex; } $namespaceTokens = []; while ($index <= $endIndex) { $token = $tokens[$index]; if ($index === $endIndex || (!$group && $token->equals(','))) { if ($group && self::SORT_NONE !== $this->configuration['sort_algorithm']) { $namespaceTokensCount = \count($namespaceTokens) - 1; $namespace = ''; for ($k = 0; $k < $namespaceTokensCount; ++$k) { if ($namespaceTokens[$k]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { $namespace .= '{'; break; } $namespace .= $namespaceTokens[$k]->getContent(); } $parts = []; $firstIndent = ''; $separator = ', '; $lastIndent = ''; $hasGroupTrailingComma = false; for ($k1 = $k + 1; $k1 < $namespaceTokensCount; ++$k1) { $comment = ''; $namespacePart = ''; for ($k2 = $k1;; ++$k2) { if ($namespaceTokens[$k2]->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { break; } if ($namespaceTokens[$k2]->isComment()) { $comment .= $namespaceTokens[$k2]->getContent(); continue; } if ( '' === $firstIndent && $namespaceTokens[$k2]->isWhitespace() && false !== strpos($namespaceTokens[$k2]->getContent(), $lineEnding) ) { $lastIndent = $lineEnding; $firstIndent = $lineEnding.$this->whitespacesConfig->getIndent(); $separator = ','.$firstIndent; } $namespacePart .= $namespaceTokens[$k2]->getContent(); } $namespacePart = trim($namespacePart); if ('' === $namespacePart) { $hasGroupTrailingComma = true; continue; } $comment = trim($comment); if ('' !== $comment) { $namespacePart .= ' '.$comment; } $parts[] = $namespacePart; $k1 = $k2; } $sortedParts = $parts; sort($parts); if ($sortedParts === $parts) { $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); } else { $namespace .= $firstIndent.implode($separator, $parts).($hasGroupTrailingComma ? ',' : '').$lastIndent.'}'; } } else { $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); } $indexes[$startIndex] = [ 'namespace' => $namespace, 'startIndex' => $startIndex, 'endIndex' => $index - 1, 'importType' => $type, 'group' => $group, ]; $originalIndexes[] = $startIndex; if ($index === $endIndex) { break; } $namespaceTokens = []; $nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, [[','], [T_WHITESPACE]]); $startIndex = $nextPartIndex; $index = $nextPartIndex; continue; } $namespaceTokens[] = $token; ++$index; } } if (null !== $this->configuration['imports_order']) { $groupedByTypes = []; foreach ($indexes as $startIndex => $item) { $groupedByTypes[$item['importType']][$startIndex] = $item; } foreach ($groupedByTypes as $type => $indexes) { $groupedByTypes[$type] = $this->sortByAlgorithm($indexes); } $sortedGroups = []; foreach ($this->configuration['imports_order'] as $type) { if (isset($groupedByTypes[$type]) && !empty($groupedByTypes[$type])) { foreach ($groupedByTypes[$type] as $startIndex => $item) { $sortedGroups[$startIndex] = $item; } } } $indexes = $sortedGroups; } else { $indexes = $this->sortByAlgorithm($indexes); } $index = -1; $usesOrder = []; foreach ($indexes as $v) { $usesOrder[$originalIndexes[++$index]] = $v; } return $usesOrder; } private function sortByAlgorithm(array $indexes) { if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { uasort($indexes, [$this, 'sortAlphabetically']); } elseif (self::SORT_LENGTH === $this->configuration['sort_algorithm']) { uasort($indexes, [$this, 'sortByLength']); } return $indexes; } } isTokenKindFound(T_USE); } public function getDefinition() { return new FixerDefinition( 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.', [ new CodeSample( 'whitespacesConfig->getLineEnding(); $tokensAnalyzer = new TokensAnalyzer($tokens); $added = 0; foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { $index += $added; $indent = ''; if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(T_COMMENT)) { $indent = $tokens[$index - 1]->getContent(); } elseif ($tokens[$index - 1]->isWhitespace()) { $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]); } $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); $insertIndex = $semicolonIndex; if ($tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG)) { if ($tokens[$insertIndex - 1]->isWhitespace()) { --$insertIndex; } $tokens->insertAt($insertIndex, new Token(';')); ++$added; } if ($semicolonIndex === \count($tokens) - 1) { $tokens->insertAt($insertIndex + 1, new Token([T_WHITESPACE, $ending.$ending.$indent])); ++$added; } else { $newline = $ending; $tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex; if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) { ++$insertIndex; } if ($tokens[$insertIndex]->isComment()) { ++$insertIndex; } $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex); if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(T_USE)) { $newline .= $ending; } if ($tokens[$insertIndex]->isWhitespace()) { $nextToken = $tokens[$insertIndex]; if (2 === substr_count($nextToken->getContent(), "\n")) { continue; } $nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex); if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(T_USE)) { if (substr_count($nextToken->getContent(), "\n") < 1) { $tokens[$insertIndex] = new Token([T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); } } else { $tokens[$insertIndex] = new Token([T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); } } else { $tokens->insertAt($insertIndex, new Token([T_WHITESPACE, $newline.$indent])); ++$added; } } } } } ` tag MUST be omitted from files containing only PHP.', [new CodeSample("\n")] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_CLOSE_TAG); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if (\count($tokens) < 2 || !$tokens->isMonolithicPhp() || !$tokens->isTokenKindFound(T_CLOSE_TAG)) { return; } $closeTags = $tokens->findGivenKind(T_CLOSE_TAG); $index = key($closeTags); if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isWhitespace()) { $tokens->clearAt($index - 1); } $tokens->clearAt($index); $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->equalsAny([';', '}', [T_OPEN_TAG]])) { $tokens->insertAt($prevIndex + 1, new Token(';')); } } } isTokenKindFound(T_OPEN_TAG); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { return; } if (false !== strpos($tokens[0]->getContent(), "\n")) { return; } $newlineFound = false; foreach ($tokens as $token) { if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) { $newlineFound = true; break; } } if (!$newlineFound) { return; } $tokens[0] = new Token([T_OPEN_TAG, rtrim($tokens[0]->getContent()).$this->whitespacesConfig->getLineEnding()]); } } isTokenKindFound(T_OPEN_TAG); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $lineEnding = $this->whitespacesConfig->getLineEnding(); if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { return; } $newlineFound = false; foreach ($tokens as $token) { if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) { $newlineFound = true; break; } } if (!$newlineFound) { return; } $token = $tokens[0]; if (false === strpos($token->getContent(), "\n")) { $tokens[0] = new Token([$token->getId(), rtrim($token->getContent()).$lineEnding]); } if (false === strpos($tokens[1]->getContent(), "\n")) { if ($tokens[1]->isWhitespace()) { $tokens[1] = new Token([T_WHITESPACE, $lineEnding.$tokens[1]->getContent()]); } else { $tokens->insertAt(1, new Token([T_WHITESPACE, $lineEnding])); } } } } isTokenKindFound(T_OPEN_TAG_WITH_ECHO); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $i = \count($tokens); while ($i--) { $token = $tokens[$i]; if (!$token->isGivenKind(T_OPEN_TAG_WITH_ECHO)) { continue; } $nextIndex = $i + 1; $tokens[$i] = new Token([T_OPEN_TAG, 'isWhitespace()) { $tokens->insertAt($nextIndex, new Token([T_WHITESPACE, ' '])); } $tokens->insertAt($nextIndex, new Token([T_ECHO, 'echo'])); } } } generateCode(); $newContent = Preg::replace('/<\?(?:phP|pHp|pHP|Php|PhP|PHp|PHP)?(\s|$)/', ' $token) { if ($token->isGivenKind(T_OPEN_TAG)) { $tokenContent = $token->getContent(); if ('isGivenKind([T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_STRING])) { $tokenContent = ''; $tokenContentLength = 0; $parts = explode('getContent()); $iLast = \count($parts) - 1; foreach ($parts as $i => $part) { $tokenContent .= $part; $tokenContentLength += \strlen($part); if ($i !== $iLast) { $originalTokenContent = substr($content, $tokensOldContentLength + $tokenContentLength, 5); if ('getId(), $tokenContent]); $token = $tokens[$index]; } $tokensOldContentLength += \strlen($token->getContent()); } $tokensOrg->overrideRange(0, $tokensOrg->count() - 1, $tokens); } } candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : T_LIST; } public function getDefinition() { return new FixerDefinition( 'List (`array` destructuring) assignment should be declared using the configured syntax. Requires PHP >= 7.1.', [ new VersionSpecificCodeSample( " 'short'] ), ] ); } public function getPriority() { return 1; } public function isCandidate(Tokens $tokens) { return \PHP_VERSION_ID >= 70100 && $tokens->isTokenKindFound($this->candidateTokenKind); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { if (T_LIST === $this->candidateTokenKind) { $this->fixToShortSyntax($tokens, $index); } else { $this->fixToLongSyntax($tokens, $index); } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` `list` syntax.')) ->setAllowedValues(['long', 'short']) ->setDefault('long') ->getOption(), ]); } private function fixToLongSyntax(Tokens $tokens, $index) { static $typesOfInterest = [ [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE], '[', ]; $closeIndex = $tokens->getNextTokenOfKind($index, $typesOfInterest); if (!$tokens[$closeIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE)) { return; } $tokens[$index] = new Token('('); $tokens[$closeIndex] = new Token(')'); $tokens->insertAt($index, new Token([T_LIST, 'list'])); } private function fixToShortSyntax(Tokens $tokens, $index) { $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $tokens[$openIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); $tokens[$closeIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } isTokenKindFound(T_RETURN); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_RETURN)) { continue; } if ($this->needFixing($tokens, $index)) { $this->clear($tokens, $index); } } } private function clear(Tokens $tokens, $index) { while (!$tokens[++$index]->equals(';')) { if ($this->shouldClearToken($tokens, $index)) { $tokens->clearAt($index); } } } private function needFixing(Tokens $tokens, $index) { if ($this->isStrictOrNullableReturnTypeFunction($tokens, $index)) { return false; } $content = ''; while (!$tokens[$index]->equals(';')) { $index = $tokens->getNextMeaningfulToken($index); $content .= $tokens[$index]->getContent(); } $content = ltrim($content, '('); $content = rtrim($content, ');'); return 'null' === strtolower($content); } private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, $returnIndex) { $functionIndex = $returnIndex; do { $functionIndex = $tokens->getPrevTokenOfKind($functionIndex, [[T_FUNCTION]]); if (null === $functionIndex) { return false; } $openingCurlyBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['{']); $closingCurlyBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingCurlyBraceIndex); } while ($closingCurlyBraceIndex < $returnIndex); $possibleVoidIndex = $tokens->getPrevMeaningfulToken($openingCurlyBraceIndex); $isStrictReturnType = $tokens[$possibleVoidIndex]->isGivenKind(T_STRING) && 'void' !== $tokens[$possibleVoidIndex]->getContent(); $nullableTypeIndex = $tokens->getNextTokenOfKind($functionIndex, [[CT::T_NULLABLE_TYPE]]); $isNullableReturnType = null !== $nullableTypeIndex && $nullableTypeIndex < $openingCurlyBraceIndex; return $isStrictReturnType || $isNullableReturnType; } private function shouldClearToken(Tokens $tokens, $index) { $token = $tokens[$index]; return !$token->isComment() && !($token->isWhitespace() && $tokens[$index + 1]->isComment()); } } proxyFixers); } protected function createProxyFixers() { $fixer = new BlankLineBeforeStatementFixer(); $fixer->configure(['statements' => ['return']]); return [$fixer]; } } isAllTokenKindsFound([T_FUNCTION, T_RETURN, T_VARIABLE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokenCount = \count($tokens); for ($index = 1; $index < $tokenCount; ++$index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $functionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$functionOpenIndex]->equals(';')) { $index = $functionOpenIndex - 1; continue; } $functionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionOpenIndex); $totalTokensAdded = 0; do { $tokensAdded = $this->fixFunction( $tokens, $index, $functionOpenIndex, $functionCloseIndex ); $totalTokensAdded += $tokensAdded; } while ($tokensAdded > 0); $index = $functionCloseIndex + $totalTokensAdded; $tokenCount += $totalTokensAdded; } } private function fixFunction(Tokens $tokens, $functionIndex, $functionOpenIndex, $functionCloseIndex) { static $riskyKinds = [ CT::T_DYNAMIC_VAR_BRACE_OPEN, T_EVAL, T_GLOBAL, T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE, T_STATIC, ]; $inserted = 0; $candidates = []; $isRisky = false; for ($index = $functionIndex + 1; $index < $functionOpenIndex; ++$index) { if ($tokens[$index]->equals('&')) { $isRisky = true; break; } } for ($index = $functionOpenIndex + 1; $index < $functionCloseIndex; ++$index) { if ($tokens[$index]->isGivenKind(T_FUNCTION)) { $nestedFunctionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$nestedFunctionOpenIndex]->equals(';')) { $index = $nestedFunctionOpenIndex - 1; continue; } $nestedFunctionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nestedFunctionOpenIndex); $tokensAdded = $this->fixFunction( $tokens, $index, $nestedFunctionOpenIndex, $nestedFunctionCloseIndex ); $index = $nestedFunctionCloseIndex + $tokensAdded; $functionCloseIndex += $tokensAdded; $inserted += $tokensAdded; } if ($isRisky) { continue; } if ($tokens[$index]->equals('&')) { $isRisky = true; continue; } if ($tokens[$index]->isGivenKind(T_RETURN)) { $candidates[] = $index; continue; } if ($tokens[$index]->isGivenKind($riskyKinds)) { $isRisky = true; continue; } if ($tokens[$index]->equals('$')) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { $isRisky = true; continue; } } if ($this->isSuperGlobal($tokens[$index])) { $isRisky = true; continue; } } if ($isRisky) { return $inserted; } for ($i = \count($candidates) - 1; $i >= 0; --$i) { $index = $candidates[$i]; $returnVarIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$returnVarIndex]->isGivenKind(T_VARIABLE)) { continue; } $endReturnVarIndex = $tokens->getNextMeaningfulToken($returnVarIndex); if (!$tokens[$endReturnVarIndex]->equalsAny([';', [T_CLOSE_TAG]])) { continue; } $assignVarEndIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$assignVarEndIndex]->equals(';')) { continue; } do { $prevMeaningFul = $tokens->getPrevMeaningfulToken($assignVarEndIndex); if (!$tokens[$prevMeaningFul]->equals(')')) { break; } $assignVarEndIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningFul); } while (true); $assignVarOperatorIndex = $tokens->getPrevTokenOfKind( $assignVarEndIndex, ['=', ';', '{', [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]] ); if (null === $assignVarOperatorIndex || !$tokens[$assignVarOperatorIndex]->equals('=')) { continue; } $assignVarIndex = $tokens->getPrevMeaningfulToken($assignVarOperatorIndex); if (!$tokens[$assignVarIndex]->equals($tokens[$returnVarIndex], false)) { continue; } $beforeAssignVarIndex = $tokens->getPrevMeaningfulToken($assignVarIndex); if (!$tokens[$beforeAssignVarIndex]->equalsAny([';', '{', '}'])) { continue; } $inserted += $this->simplifyReturnStatement( $tokens, $assignVarIndex, $assignVarOperatorIndex, $index, $endReturnVarIndex ); } return $inserted; } private function simplifyReturnStatement( Tokens $tokens, $assignVarIndex, $assignVarOperatorIndex, $returnIndex, $returnVarEndIndex ) { $inserted = 0; $originalIndent = $tokens[$assignVarIndex - 1]->isWhitespace() ? $tokens[$assignVarIndex - 1]->getContent() : null ; if ($tokens[$returnVarEndIndex]->equals(';')) { $tokens->clearTokenAndMergeSurroundingWhitespace($returnVarEndIndex); } for ($i = $returnIndex; $i <= $returnVarEndIndex - 1; ++$i) { $this->clearIfSave($tokens, $i); } if ($tokens[$returnIndex - 1]->isWhitespace()) { $content = $tokens[$returnIndex - 1]->getContent(); $fistLinebreakPos = strrpos($content, "\n"); $content = false === $fistLinebreakPos ? ' ' : substr($content, $fistLinebreakPos) ; $tokens[$returnIndex - 1] = new Token([T_WHITESPACE, $content]); } for ($i = $assignVarIndex; $i <= $assignVarOperatorIndex; ++$i) { $this->clearIfSave($tokens, $i); } $tokens->insertAt($assignVarIndex, new Token([T_RETURN, 'return'])); ++$inserted; if ( null !== $originalIndent && $tokens[$assignVarIndex - 1]->isWhitespace() && $originalIndent !== $tokens[$assignVarIndex - 1]->getContent() ) { $tokens[$assignVarIndex - 1] = new Token([T_WHITESPACE, $originalIndent]); } $nextIndex = $tokens->getNonEmptySibling($assignVarIndex, 1); if (!$tokens[$nextIndex]->isWhitespace()) { $tokens->insertAt($nextIndex, new Token([T_WHITESPACE, ' '])); ++$inserted; } return $inserted; } private function clearIfSave(Tokens $tokens, $index) { if ($tokens[$index]->isComment()) { return; } if ($tokens[$index]->isWhitespace() && $tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { return; } $tokens->clearTokenAndMergeSurroundingWhitespace($index); } private function isSuperGlobal(Token $token) { static $superNames = [ '$_COOKIE' => true, '$_ENV' => true, '$_FILES' => true, '$_GET' => true, '$_POST' => true, '$_REQUEST' => true, '$_SERVER' => true, '$_SESSION' => true, '$GLOBALS' => true, ]; if (!$token->isGivenKind(T_VARIABLE)) { return false; } return isset($superNames[strtoupper($token->getContent())]); } } isAllTokenKindsFound([T_FUNCTION, T_RETURN]); } public function getDefinition() { return new FixerDefinition( 'There should not be an empty `return` statement at the end of a function.', [ new CodeSample( ' $token) { if (!$token->isGivenKind(T_FUNCTION)) { continue; } $index = $tokens->getNextTokenOfKind($index, [';', '{']); if ($tokens[$index]->equals('{')) { $this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); } } } private function fixFunction(Tokens $tokens, $start, $end) { for ($index = $end; $index > $start; --$index) { if (!$tokens[$index]->isGivenKind(T_RETURN)) { continue; } $nextAt = $tokens->getNextMeaningfulToken($index); if (!$tokens[$nextAt]->equals(';')) { continue; } if ($tokens->getNextMeaningfulToken($nextAt) !== $end) { continue; } $previous = $tokens->getPrevMeaningfulToken($index); if ($tokens[$previous]->equalsAny([[T_ELSE], ')'])) { continue; } $tokens->clearTokenAndMergeSurroundingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($nextAt); } } } proxyFixers); } protected function createProxyFixers() { $fixer = new SingleLineCommentStyleFixer(); $fixer->configure(['comment_types' => ['hash']]); return [$fixer]; } } isTokenKindFound(T_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind(T_COMMENT)) { continue; } list($blockStart, $index, $isEmpty) = $this->getCommentBlock($tokens, $index); if (false === $isEmpty) { continue; } for ($i = $blockStart; $i <= $index; ++$i) { $tokens->clearTokenAndMergeSurroundingWhitespace($i); } } } private function getCommentBlock(Tokens $tokens, $index) { $commentType = $this->getCommentType($tokens[$index]->getContent()); $empty = $this->isEmptyComment($tokens[$index]->getContent()); if (self::TYPE_SLASH_ASTERISK === $commentType) { return [$index, $index, $empty]; } $start = $index; $count = \count($tokens); ++$index; for (; $index < $count; ++$index) { if ($tokens[$index]->isComment()) { if ($commentType !== $this->getCommentType($tokens[$index]->getContent())) { break; } if ($empty) { $empty = $this->isEmptyComment($tokens[$index]->getContent()); } continue; } if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { break; } } return [$start, $index - 1, $empty]; } private function getCommentType($content) { if ('#' === $content[0]) { return self::TYPE_HASH; } if ('*' === $content[1]) { return self::TYPE_SLASH_ASTERISK; } return self::TYPE_DOUBLE_SLASH; } private function getLineBreakCount(Tokens $tokens, $whiteStart, $whiteEnd) { $lineCount = 0; for ($i = $whiteStart; $i < $whiteEnd; ++$i) { $lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent(), $matches); } return $lineCount; } private function isEmptyComment($content) { static $mapper = [ self::TYPE_HASH => '|^#\s*$|', self::TYPE_SLASH_ASTERISK => '|^/\*[\s\*]*\*+/$|', self::TYPE_DOUBLE_SLASH => '|^//\s*$|', ]; $type = $this->getCommentType($content); return 1 === Preg::match($mapper[$type], $content); } } isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { $originalContent = $token->getContent(); if ( !$token->isGivenKind(T_DOC_COMMENT) && !($token->isGivenKind(T_COMMENT) && 0 === strpos($originalContent, '/*')) ) { continue; } $newContent = $originalContent; if ($token->isGivenKind(T_COMMENT)) { $newContent = Preg::replace('/^\\/\\*{2,}(?!\\/)/', '/*', $newContent); } $newContent = Preg::replace('/(?getId(), $newContent]); } } } } isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isGivenKind(T_DOC_COMMENT)) { $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); continue; } if ($token->isGivenKind(T_COMMENT)) { if ('/*' === substr($token->getContent(), 0, 2)) { $tokens[$index] = new Token([T_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); } elseif (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { $trimmedContent = ltrim($tokens[$index + 1]->getContent(), " \t"); if ('' !== $trimmedContent) { $tokens[$index + 1] = new Token([T_WHITESPACE, $trimmedContent]); } else { $tokens->clearAt($index + 1); } } } } } } isTokenKindFound(T_COMMENT); } public function isRisky() { return true; } public function getPriority() { return 26; } public function getDefinition() { return new FixerDefinition( 'Comments with annotation should be docblock when used on structural elements.', [ new CodeSample(" ['todo']]), ], null, 'Risky as new docblocks might mean more, e.g. a Doctrine entity might have a new column in database.' ); } public function configure(array $configuration = null) { parent::configure($configuration); $this->ignoredTags = array_map( static function ($tag) { return strtolower($tag); }, $this->configuration['ignored_tags'] ); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('ignored_tags', sprintf('List of ignored tags'))) ->setAllowedTypes(['array']) ->setDefault([]) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $commentsAnalyzer = new CommentsAnalyzer(); for ($index = 0, $limit = \count($tokens); $index < $limit; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_COMMENT)) { continue; } if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { continue; } if (!$commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { continue; } $commentIndices = $commentsAnalyzer->getCommentBlockIndices($tokens, $index); if ($this->isCommentCandidate($tokens, $commentIndices)) { $this->fixComment($tokens, $commentIndices); } $index = max($commentIndices); } } private function isCommentCandidate(Tokens $tokens, array $indices) { return array_reduce( $indices, function ($carry, $index) use ($tokens) { if ($carry) { return true; } if (1 !== Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@([a-zA-Z0-9_\\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent(), $matches)) { return false; } return !\in_array(strtolower($matches[1]), $this->ignoredTags, true); }, false ); } private function fixComment(Tokens $tokens, $indices) { if (1 === \count($indices)) { $this->fixCommentSingleLine($tokens, reset($indices)); } else { $this->fixCommentMultiLine($tokens, $indices); } } private function fixCommentSingleLine(Tokens $tokens, $index) { $message = $this->getMessage($tokens[$index]->getContent()); if ('' !== trim(substr($message, 0, 1))) { $message = ' '.$message; } if ('' !== trim(substr($message, -1))) { $message .= ' '; } $tokens[$index] = new Token([T_DOC_COMMENT, '/**'.$message.'*/']); } private function fixCommentMultiLine(Tokens $tokens, array $indices) { $startIndex = reset($indices); $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$startIndex - 1]); $newContent = '/**'.$this->whitespacesConfig->getLineEnding(); $count = max($indices); for ($index = $startIndex; $index <= $count; ++$index) { if (!$tokens[$index]->isComment()) { continue; } if (false !== strpos($tokens[$index]->getContent(), '*/')) { return; } $newContent .= $indent.' *'.$this->getMessage($tokens[$index]->getContent()).$this->whitespacesConfig->getLineEnding(); } for ($index = $startIndex; $index <= $count; ++$index) { $tokens->clearAt($index); } $newContent .= $indent.' */'; $tokens->insertAt($startIndex, new Token([T_DOC_COMMENT, $newContent])); } private function getMessage($content) { if (0 === strpos($content, '#')) { return substr($content, 1); } if (0 === strpos($content, '//')) { return substr($content, 2); } return rtrim(ltrim($content, '/*'), '*/'); } } asteriskEnabled = \in_array('asterisk', $this->configuration['comment_types'], true); $this->hashEnabled = \in_array('hash', $this->configuration['comment_types'], true); } public function getDefinition() { return new FixerDefinition( 'Single-line comments and multi-line comments with only one line of actual content should use the `//` syntax.', [ new CodeSample( ' ['asterisk']] ), new CodeSample( " ['hash']] ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_COMMENT)) { continue; } $content = $token->getContent(); $commentContent = substr($content, 2, -2) ?: ''; if ($this->hashEnabled && '#' === $content[0]) { if (isset($content[1]) && '[' === $content[1]) { continue; } $tokens[$index] = new Token([$token->getId(), '//'.substr($content, 1)]); continue; } if ( !$this->asteriskEnabled || false !== strpos($commentContent, '?>') || '/*' !== substr($content, 0, 2) || 1 === Preg::match('/[^\s\*].*\R.*[^\s\*]/s', $commentContent) ) { continue; } $nextTokenIndex = $index + 1; if (isset($tokens[$nextTokenIndex])) { $nextToken = $tokens[$nextTokenIndex]; if (!$nextToken->isWhitespace() || 1 !== Preg::match('/\R/', $nextToken->getContent())) { continue; } $tokens[$nextTokenIndex] = new Token([$nextToken->getId(), ltrim($nextToken->getContent(), " \t")]); } $content = '//'; if (1 === Preg::match('/[^\s\*]/', $commentContent)) { $content = '// '.Preg::replace('/[\s\*]*([^\s\*](?:.+[^\s\*])?)[\s\*]*/', '\1', $commentContent); } $tokens[$index] = new Token([$token->getId(), $content]); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('comment_types', 'List of comment types to fix')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(['asterisk', 'hash'])]) ->setDefault(['asterisk', 'hash']) ->getOption(), ]); } } 'Made with love.', ] ), new CodeSample( ' 'Made with love.', 'comment_type' => 'PHPDoc', 'location' => 'after_open', 'separate' => 'bottom', ] ), new CodeSample( ' 'Made with love.', 'comment_type' => 'comment', 'location' => 'after_declare_strict', ] ), ] ); } public function isCandidate(Tokens $tokens) { return isset($tokens[0]) && $tokens[0]->isGivenKind(T_OPEN_TAG) && $tokens->isMonolithicPhp(); } public function getPriority() { return -30; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $location = $this->configuration['location']; $locationIndexes = []; foreach (['after_open', 'after_declare_strict'] as $possibleLocation) { $locationIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); if (!isset($locationIndexes[$locationIndex]) || $possibleLocation === $location) { $locationIndexes[$locationIndex] = $possibleLocation; continue; } } foreach (array_values($locationIndexes) as $possibleLocation) { $headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); $headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerNewIndex - 1); if (null === $headerCurrentIndex) { if ('' === $this->configuration['header'] || $possibleLocation !== $location) { continue; } $this->insertHeader($tokens, $headerNewIndex); continue; } $sameComment = $this->getHeaderAsComment() === $tokens[$headerCurrentIndex]->getContent(); $expectedLocation = $possibleLocation === $location; if (!$sameComment || !$expectedLocation) { if ($expectedLocation ^ $sameComment) { $this->removeHeader($tokens, $headerCurrentIndex); } if ('' === $this->configuration['header']) { continue; } if ($possibleLocation === $location) { $this->insertHeader($tokens, $headerNewIndex); } continue; } $this->fixWhiteSpaceAroundHeader($tokens, $headerCurrentIndex); } } protected function createConfigurationDefinition() { $fixerName = $this->getName(); return new FixerConfigurationResolver([ (new FixerOptionBuilder('header', 'Proper header content.')) ->setAllowedTypes(['string']) ->setNormalizer(static function (Options $options, $value) use ($fixerName) { if ('' === trim($value)) { return ''; } if (false !== strpos($value, '*/')) { throw new InvalidFixerConfigurationException($fixerName, 'Cannot use \'*/\' in header.'); } return $value; }) ->getOption(), (new AliasedFixerOptionBuilder( new FixerOptionBuilder('comment_type', 'Comment syntax type.'), 'commentType' )) ->setAllowedValues([self::HEADER_PHPDOC, self::HEADER_COMMENT]) ->setDefault(self::HEADER_COMMENT) ->getOption(), (new FixerOptionBuilder('location', 'The location of the inserted header.')) ->setAllowedValues(['after_open', 'after_declare_strict']) ->setDefault('after_declare_strict') ->getOption(), (new FixerOptionBuilder('separate', 'Whether the header should be separated from the file content with a new line.')) ->setAllowedValues(['both', 'top', 'bottom', 'none']) ->setDefault('both') ->getOption(), ]); } private function getHeaderAsComment() { $lineEnding = $this->whitespacesConfig->getLineEnding(); $comment = (self::HEADER_COMMENT === $this->configuration['comment_type'] ? '/*' : '/**').$lineEnding; $lines = explode("\n", str_replace("\r", '', $this->configuration['header'])); foreach ($lines as $line) { $comment .= rtrim(' * '.$line).$lineEnding; } return $comment.' */'; } private function findHeaderCommentCurrentIndex(Tokens $tokens, $headerNewIndex) { $index = $tokens->getNextNonWhitespace($headerNewIndex); if (null === $index || !$tokens[$index]->isComment()) { return null; } $next = $index + 1; if (!isset($tokens[$next]) || \in_array($this->configuration['separate'], ['top', 'none'], true) || !$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { return $index; } if ($tokens[$next]->isWhitespace()) { if (!Preg::match('/^\h*\R\h*$/D', $tokens[$next]->getContent())) { return $index; } ++$next; } if (!isset($tokens[$next]) || !$tokens[$next]->isClassy() && !$tokens[$next]->isGivenKind(T_FUNCTION)) { return $index; } return $this->getHeaderAsComment() === $tokens[$index]->getContent() ? $index : null; } private function findHeaderCommentInsertionIndex(Tokens $tokens, $location) { if ('after_open' === $location) { return 1; } $index = $tokens->getNextMeaningfulToken(0); if (null === $index) { return 1; } if (!$tokens[$index]->isGivenKind(T_DECLARE)) { return 1; } $next = $tokens->getNextMeaningfulToken($index); if (null === $next || !$tokens[$next]->equals('(')) { return 1; } $next = $tokens->getNextMeaningfulToken($next); if (null === $next || !$tokens[$next]->equals([T_STRING, 'strict_types'], false)) { return 1; } $next = $tokens->getNextMeaningfulToken($next); if (null === $next || !$tokens[$next]->equals('=')) { return 1; } $next = $tokens->getNextMeaningfulToken($next); if (null === $next || !$tokens[$next]->isGivenKind(T_LNUMBER)) { return 1; } $next = $tokens->getNextMeaningfulToken($next); if (null === $next || !$tokens[$next]->equals(')')) { return 1; } $next = $tokens->getNextMeaningfulToken($next); if (null === $next || !$tokens[$next]->equals(';')) { return 1; } return $next + 1; } private function fixWhiteSpaceAroundHeader(Tokens $tokens, $headerIndex) { $lineEnding = $this->whitespacesConfig->getLineEnding(); if ( ('both' === $this->configuration['separate'] || 'bottom' === $this->configuration['separate']) && null !== $tokens->getNextMeaningfulToken($headerIndex) ) { $expectedLineCount = 2; } else { $expectedLineCount = 1; } if ($headerIndex === \count($tokens) - 1) { $tokens->insertAt($headerIndex + 1, new Token([T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount)])); } else { $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, 1); if ($lineBreakCount < $expectedLineCount) { $missing = str_repeat($lineEnding, $expectedLineCount - $lineBreakCount); if ($tokens[$headerIndex + 1]->isWhitespace()) { $tokens[$headerIndex + 1] = new Token([T_WHITESPACE, $missing.$tokens[$headerIndex + 1]->getContent()]); } else { $tokens->insertAt($headerIndex + 1, new Token([T_WHITESPACE, $missing])); } } elseif ($lineBreakCount > $expectedLineCount && $tokens[$headerIndex + 1]->isWhitespace()) { $newLinesToRemove = $lineBreakCount - $expectedLineCount; $tokens[$headerIndex + 1] = new Token([ T_WHITESPACE, Preg::replace("/^\\R{{$newLinesToRemove}}/", '', $tokens[$headerIndex + 1]->getContent()), ]); } } $expectedLineCount = 'both' === $this->configuration['separate'] || 'top' === $this->configuration['separate'] ? 2 : 1; $prev = $tokens->getPrevNonWhitespace($headerIndex); $regex = '/\h$/'; if ($tokens[$prev]->isGivenKind(T_OPEN_TAG) && Preg::match($regex, $tokens[$prev]->getContent())) { $tokens[$prev] = new Token([T_OPEN_TAG, Preg::replace($regex, $lineEnding, $tokens[$prev]->getContent())]); } $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, -1); if ($lineBreakCount < $expectedLineCount) { $tokens->insertAt($headerIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount - $lineBreakCount)])); } } private function getLineBreakCount(Tokens $tokens, $index, $direction) { $whitespace = ''; for ($index += $direction; isset($tokens[$index]); $index += $direction) { $token = $tokens[$index]; if ($token->isWhitespace()) { $whitespace .= $token->getContent(); continue; } if (-1 === $direction && $token->isGivenKind(T_OPEN_TAG)) { $whitespace .= $token->getContent(); } if ('' !== $token->getContent()) { break; } } return substr_count($whitespace, "\n"); } private function removeHeader(Tokens $tokens, $index) { $prevIndex = $index - 1; $prevToken = $tokens[$prevIndex]; $newlineRemoved = false; if ($prevToken->isWhitespace()) { $content = $prevToken->getContent(); if (Preg::match('/\R/', $content)) { $newlineRemoved = true; } $content = Preg::replace('/\R?\h*$/', '', $content); if ('' === $content) { $tokens->clearAt($prevIndex); } else { $tokens[$prevIndex] = new Token([T_WHITESPACE, $content]); } } $nextIndex = $index + 1; $nextToken = isset($tokens[$nextIndex]) ? $tokens[$nextIndex] : null; if (!$newlineRemoved && null !== $nextToken && $nextToken->isWhitespace()) { $content = Preg::replace('/^\R/', '', $nextToken->getContent()); if ('' === $content) { $tokens->clearAt($nextIndex); } else { $tokens[$nextIndex] = new Token([T_WHITESPACE, $content]); } } $tokens->clearTokenAndMergeSurroundingWhitespace($index); } private function insertHeader(Tokens $tokens, $index) { $tokens->insertAt($index, new Token([self::HEADER_COMMENT === $this->configuration['comment_type'] ? T_COMMENT : T_DOC_COMMENT, $this->getHeaderAsComment()])); $this->fixWhiteSpaceAroundHeader($tokens, $index); } } isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $end = $tokens->count() - 1; $functionsAnalyzer = new FunctionsAnalyzer(); foreach (self::$functions as $map) { $seq = [[T_STRING, $map[0]], '(', [T_CONSTANT_ENCAPSED_STRING]]; $currIndex = 0; while (null !== $currIndex) { $match = $tokens->findSequence($seq, $currIndex, $end, false); if (null === $match) { break; } $match = array_keys($match); $currIndex = $match[2]; if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $match[0])) { continue; } $next = $tokens->getNextMeaningfulToken($match[2]); if (null === $next || !$tokens[$next]->equalsAny([',', ')'])) { continue; } $regexTokenContent = $tokens[$match[2]]->getContent(); $string = substr($regexTokenContent, 1, -1); $quote = $regexTokenContent[0]; $delim = $this->getBestDelimiter($string); $preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2]; if (!$this->checkPreg($preg)) { continue; } $tokens[$match[0]] = new Token([T_STRING, $map[1]]); $tokens[$match[2]] = new Token([T_CONSTANT_ENCAPSED_STRING, $quote.$preg.$quote]); } } } private function checkPreg($pattern) { try { Preg::match($pattern, ''); return true; } catch (PregException $e) { return false; } } private function getBestDelimiter($pattern) { $delimiters = []; foreach (self::$delimiters as $k => $d) { if (false === strpos($pattern, $d)) { return $d; } $delimiters[$d] = [substr_count($pattern, $d), $k]; } uasort($delimiters, static function ($a, $b) { if ($a[0] === $b[0]) { return Utils::cmpInt($a, $b); } return $a[0] < $b[0] ? -1 : 1; }); return key($delimiters); } } [0], 'mt_rand' => [1, 2], 'rand' => [0, 2], 'srand' => [0, 1], ]; public function configure(array $configuration = null) { parent::configure($configuration); foreach ($this->configuration['replacements'] as $functionName => $replacement) { $this->configuration['replacements'][$functionName] = [ 'alternativeName' => $replacement, 'argumentCount' => self::$argumentCounts[$functionName], ]; } } public function getDefinition() { return new FixerDefinition( 'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs.', [ new CodeSample(" ['getrandmax' => 'mt_getrandmax']] ), new CodeSample( " ['rand' => 'random_int']] ), ], null, 'Risky when the configured functions are overridden.' ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $argumentsAnalyzer = new ArgumentsAnalyzer(); foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) { if ($functionIdentity === $functionReplacement['alternativeName']) { continue; } $currIndex = 0; while (null !== $currIndex) { $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); if (null === $boundaries) { continue 2; } list($functionName, $openParenthesis, $closeParenthesis) = $boundaries; $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); if (!\in_array($count, $functionReplacement['argumentCount'], true)) { continue 2; } $currIndex = $openParenthesis; $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]); if (0 === $count && 'random_int' === $functionReplacement['alternativeName']) { $tokens->insertAt($currIndex + 1, [ new Token([T_LNUMBER, '0']), new Token(','), new Token([T_WHITESPACE, ' ']), new Token([T_STRING, 'getrandmax']), new Token('('), new Token(')'), ]); $currIndex += 6; } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('replacements', [ (new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.')) ->setAllowedTypes(['array']) ->setAllowedValues([static function ($value) { foreach ($value as $functionName => $replacement) { if (!\array_key_exists($functionName, self::$argumentCounts)) { throw new InvalidOptionsException(sprintf( 'Function "%s" is not handled by the fixer.', $functionName )); } if (!\is_string($replacement)) { throw new InvalidOptionsException(sprintf( 'Replacement for function "%s" must be a string, "%s" given.', $functionName, \is_object($replacement) ? \get_class($replacement) : \gettype($replacement) )); } } return true; }]) ->setDefault([ 'getrandmax' => 'mt_getrandmax', 'rand' => 'mt_rand', 'srand' => 'mt_srand', ]) ->getOption(), ], $this->getName()); } } 'rtrim', 'close' => 'closedir', 'doubleval' => 'floatval', 'fputs' => 'fwrite', 'get_required_files' => 'get_included_files', 'ini_alter' => 'ini_set', 'is_double' => 'is_float', 'is_integer' => 'is_int', 'is_long' => 'is_int', 'is_real' => 'is_float', 'is_writeable' => 'is_writable', 'join' => 'implode', 'key_exists' => 'array_key_exists', 'magic_quotes_runtime' => 'set_magic_quotes_runtime', 'pos' => 'current', 'show_source' => 'highlight_file', 'sizeof' => 'count', 'strchr' => 'strstr', 'user_error' => 'trigger_error', ]; private static $imapSet = [ 'imap_create' => 'imap_createmailbox', 'imap_fetchtext' => 'imap_body', 'imap_header' => 'imap_headerinfo', 'imap_listmailbox' => 'imap_list', 'imap_listsubscribed' => 'imap_lsub', 'imap_rename' => 'imap_renamemailbox', 'imap_scan' => 'imap_listscan', 'imap_scanmailbox' => 'imap_listscan', ]; private static $mbregSet = [ 'mbereg' => 'mb_ereg', 'mbereg_match' => 'mb_ereg_match', 'mbereg_replace' => 'mb_ereg_replace', 'mbereg_search' => 'mb_ereg_search', 'mbereg_search_getpos' => 'mb_ereg_search_getpos', 'mbereg_search_getregs' => 'mb_ereg_search_getregs', 'mbereg_search_init' => 'mb_ereg_search_init', 'mbereg_search_pos' => 'mb_ereg_search_pos', 'mbereg_search_regs' => 'mb_ereg_search_regs', 'mbereg_search_setpos' => 'mb_ereg_search_setpos', 'mberegi' => 'mb_eregi', 'mberegi_replace' => 'mb_eregi_replace', 'mbregex_encoding' => 'mb_regex_encoding', 'mbsplit' => 'mb_split', ]; private static $exifSet = [ 'read_exif_data' => 'exif_read_data', ]; private static $timeSet = [ 'mktime' => ['time', 0], 'gmmktime' => ['time', 0], ]; public function configure(array $configuration = null) { parent::configure($configuration); $this->aliases = []; foreach ($this->configuration['sets'] as $set) { if ('@all' === $set) { $this->aliases = self::$internalSet; $this->aliases = array_merge($this->aliases, self::$imapSet); $this->aliases = array_merge($this->aliases, self::$mbregSet); $this->aliases = array_merge($this->aliases, self::$timeSet); $this->aliases = array_merge($this->aliases, self::$exifSet); break; } if ('@internal' === $set) { $this->aliases = array_merge($this->aliases, self::$internalSet); } elseif ('@IMAP' === $set) { $this->aliases = array_merge($this->aliases, self::$imapSet); } elseif ('@mbreg' === $set) { $this->aliases = array_merge($this->aliases, self::$mbregSet); } elseif ('@time' === $set) { $this->aliases = array_merge($this->aliases, self::$timeSet); } elseif ('@exif' === $set) { $this->aliases = array_merge($this->aliases, self::$exifSet); } } } public function getDefinition() { return new FixerDefinition( 'Master functions shall be used instead of aliases.', [ new CodeSample( ' ['@mbreg']] ), ], null, 'Risky when any of the alias functions are overridden.' ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionsAnalyzer = new FunctionsAnalyzer(); $argumentsAnalyzer = new ArgumentsAnalyzer(); foreach ($tokens->findGivenKind(T_STRING) as $index => $token) { $tokenContent = strtolower($token->getContent()); if (!isset($this->aliases[$tokenContent])) { continue; } $openParenthesis = $tokens->getNextMeaningfulToken($index); if (!$tokens[$openParenthesis]->equals('(')) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } if (\is_array($this->aliases[$tokenContent])) { list($alias, $numberOfArguments) = $this->aliases[$tokenContent]; $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)); if ($numberOfArguments !== $count) { continue; } } else { $alias = $this->aliases[$tokenContent]; } $tokens[$index] = new Token([T_STRING, $alias]); } } protected function createConfigurationDefinition() { $sets = ['@internal', '@IMAP', '@mbreg', '@all', '@time', '@exif']; return new FixerConfigurationResolver([ (new FixerOptionBuilder('sets', 'List of sets to fix. Defined sets are `@internal` (native functions), `@IMAP` (IMAP functions), `@mbreg` (from `ext-mbstring`) `@all` (all listed sets).')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($sets)]) ->setDefault(['@internal', '@IMAP']) ->getOption(), ]); } } 'echo']; private $callBack; private $candidateTokenType; public function configure(array $configuration = null) { parent::configure($configuration); if ('echo' === $this->configuration['use']) { $this->candidateTokenType = T_PRINT; $this->callBack = 'fixPrintToEcho'; } else { $this->candidateTokenType = T_ECHO; $this->callBack = 'fixEchoToPrint'; } } public function getDefinition() { return new FixerDefinition( 'Either language construct `print` or `echo` should be used.', [ new CodeSample(" 'print']), ] ); } public function getPriority() { return -10; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound($this->candidateTokenType); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $callBack = $this->callBack; foreach ($tokens as $index => $token) { if ($token->isGivenKind($this->candidateTokenType)) { $this->{$callBack}($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use', 'The desired language construct.')) ->setAllowedValues(['print', 'echo']) ->setDefault('echo') ->getOption(), ]); } private function fixEchoToPrint(Tokens $tokens, $index) { $nextTokenIndex = $tokens->getNextMeaningfulToken($index); $endTokenIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); $canBeConverted = true; for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) { if ($tokens[$i]->equalsAny(['(', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) { $blockType = Tokens::detectBlockType($tokens[$i]); $i = $tokens->findBlockEnd($blockType['type'], $i); } if ($tokens[$i]->equals(',')) { $canBeConverted = false; break; } } if (false === $canBeConverted) { return; } $tokens[$index] = new Token([T_PRINT, 'print']); } private function fixPrintToEcho(Tokens $tokens, $index) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if (!$prevToken->equalsAny([';', '{', '}', [T_OPEN_TAG]])) { return; } $tokens[$index] = new Token([T_ECHO, 'echo']); } } isAllTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_STRING, T_VARIABLE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $map = [ 'array' => [T_ARRAY_CAST, '(array)'], 'bool' => [T_BOOL_CAST, '(bool)'], 'boolean' => [T_BOOL_CAST, '(bool)'], 'double' => [T_DOUBLE_CAST, '(float)'], 'float' => [T_DOUBLE_CAST, '(float)'], 'int' => [T_INT_CAST, '(int)'], 'integer' => [T_INT_CAST, '(int)'], 'object' => [T_OBJECT_CAST, '(object)'], 'string' => [T_STRING_CAST, '(string)'], ]; $argumentsAnalyzer = new ArgumentsAnalyzer(); foreach (array_reverse($this->findSettypeCalls($tokens)) as $candidate) { $functionNameIndex = $candidate[0]; $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); if (2 !== \count($arguments)) { continue; } $prev = $tokens->getPrevMeaningfulToken($functionNameIndex); if (!$tokens[$prev]->isGivenKind(T_OPEN_TAG) && !$tokens[$prev]->equalsAny([';', '{'])) { continue; } reset($arguments); $firstArgumentStart = key($arguments); if ($tokens[$firstArgumentStart]->isComment() || $tokens[$firstArgumentStart]->isWhitespace()) { $firstArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStart); } if (!$tokens[$firstArgumentStart]->isGivenKind(T_VARIABLE)) { continue; } $commaIndex = $tokens->getNextMeaningfulToken($firstArgumentStart); if (null === $commaIndex || !$tokens[$commaIndex]->equals(',')) { continue; } next($arguments); $secondArgumentStart = key($arguments); $secondArgumentEnd = $arguments[$secondArgumentStart]; if ($tokens[$secondArgumentStart]->isComment() || $tokens[$secondArgumentStart]->isWhitespace()) { $secondArgumentStart = $tokens->getNextMeaningfulToken($secondArgumentStart); } if ( !$tokens[$secondArgumentStart]->isGivenKind(T_CONSTANT_ENCAPSED_STRING) || $tokens->getNextMeaningfulToken($secondArgumentStart) < $secondArgumentEnd ) { continue; } $type = strtolower(trim($tokens[$secondArgumentStart]->getContent(), '"\'"')); if ('null' !== $type && !isset($map[$type])) { continue; } $argumentToken = $tokens[$firstArgumentStart]; $this->removeSettypeCall( $tokens, $functionNameIndex, $candidate[1], $firstArgumentStart, $commaIndex, $secondArgumentStart, $candidate[2] ); if ('null' === $type) { $this->findSettypeNullCall($tokens, $functionNameIndex, $argumentToken); } else { $this->fixSettypeCall($tokens, $functionNameIndex, $argumentToken, new Token($map[$type])); } } } private function findSettypeCalls(Tokens $tokens) { $candidates = []; $end = \count($tokens); for ($i = 1; $i < $end; ++$i) { $candidate = $this->find('settype', $tokens, $i, $end); if (null === $candidate) { break; } $i = $candidate[1]; $candidates[] = $candidate; } return $candidates; } private function removeSettypeCall( Tokens $tokens, $functionNameIndex, $openParenthesisIndex, $firstArgumentStart, $commaIndex, $secondArgumentStart, $closeParenthesisIndex ) { $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); $prevIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); if ($tokens[$prevIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($secondArgumentStart); $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStart); $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); $tokens->clearAt($functionNameIndex); $tokens->clearEmptyTokens(); } private function fixSettypeCall( Tokens $tokens, $functionNameIndex, Token $argumentToken, Token $castToken ) { $tokens->insertAt( $functionNameIndex, [ clone $argumentToken, new Token([T_WHITESPACE, ' ']), new Token('='), new Token([T_WHITESPACE, ' ']), $castToken, new Token([T_WHITESPACE, ' ']), clone $argumentToken, ] ); $tokens->removeTrailingWhitespace($functionNameIndex + 6); } private function findSettypeNullCall( Tokens $tokens, $functionNameIndex, Token $argumentToken ) { $tokens->insertAt( $functionNameIndex, [ clone $argumentToken, new Token([T_WHITESPACE, ' ']), new Token('='), new Token([T_WHITESPACE, ' ']), new Token([T_STRING, 'null']), ] ); $tokens->removeTrailingWhitespace($functionNameIndex + 4); } } count() > 7 && $tokens->isTokenKindFound(T_STRING); } public function getDefinition() { return new FixerDefinition( 'Converts `pow` to the `**` operator.', [ new CodeSample( "findPowCalls($tokens); $argumentsAnalyzer = new ArgumentsAnalyzer(); $numberOfTokensAdded = 0; $previousCloseParenthesisIndex = \count($tokens); foreach (array_reverse($candidates) as $candidate) { if ($previousCloseParenthesisIndex < $candidate[2]) { $previousCloseParenthesisIndex = $candidate[2]; $candidate[2] += $numberOfTokensAdded; } else { $previousCloseParenthesisIndex = $candidate[2]; $numberOfTokensAdded = 0; } $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); if (2 !== \count($arguments)) { continue; } for ($i = $candidate[1]; $i < $candidate[2]; ++$i) { if ($tokens[$i]->isGivenKind(T_ELLIPSIS)) { continue 2; } } $numberOfTokensAdded += $this->fixPowToExponentiation( $tokens, $candidate[0], $candidate[1], $candidate[2], $arguments ); } } private function findPowCalls(Tokens $tokens) { $candidates = []; $end = \count($tokens) - 6; for ($i = 1; $i < $end; ++$i) { $candidate = $this->find('pow', $tokens, $i, $end); if (null === $candidate) { break; } $i = $candidate[1]; $candidates[] = $candidate; } return $candidates; } private function fixPowToExponentiation(Tokens $tokens, $functionNameIndex, $openParenthesisIndex, $closeParenthesisIndex, array $arguments) { $tokens[$tokens->getNextTokenOfKind(reset($arguments), [','])] = new Token([T_POW, '**']); $tokens->clearAt($closeParenthesisIndex); $previousIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); if ($tokens[$previousIndex]->equals(',')) { $tokens->clearAt($previousIndex); } $added = 0; foreach (array_reverse($arguments, true) as $argumentStartIndex => $argumentEndIndex) { if ($this->isParenthesisNeeded($tokens, $argumentStartIndex, $argumentEndIndex)) { $tokens->insertAt($argumentEndIndex + 1, new Token(')')); $tokens->insertAt($argumentStartIndex, new Token('(')); $added += 2; } } $tokens->clearAt($openParenthesisIndex); $tokens->clearAt($functionNameIndex); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { $tokens->clearAt($prevMeaningfulTokenIndex); } return $added; } private function isParenthesisNeeded(Tokens $tokens, $argumentStartIndex, $argumentEndIndex) { static $allowedKinds = [ T_DNUMBER, T_LNUMBER, T_VARIABLE, T_STRING, T_OBJECT_OPERATOR, T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_CAST, T_INT_CAST, T_INC, T_DEC, T_NS_SEPARATOR, T_WHITESPACE, T_DOUBLE_COLON, T_LINE, T_COMMENT, T_DOC_COMMENT, CT::T_NAMESPACE_OPERATOR, ]; for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { if ($tokens[$i]->isGivenKind($allowedKinds) || $tokens->isEmptyAt($i)) { continue; } $blockType = Tokens::detectBlockType($tokens[$i]); if (null !== $blockType) { $i = $tokens->findBlockEnd($blockType['type'], $i); continue; } if ($tokens[$i]->equals('$')) { $i = $tokens->getNextMeaningfulToken($i); if ($tokens[$i]->isGivenKind(CT::T_DYNAMIC_VAR_BRACE_OPEN)) { $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, $i); continue; } } if ($tokens[$i]->equals('+') && $tokens->getPrevMeaningfulToken($i) < $argumentStartIndex) { continue; } return true; } return false; } } ['alternativeName' => 'mb_str_split', 'argumentCount' => [1, 2, 3]], 'stripos' => ['alternativeName' => 'mb_stripos', 'argumentCount' => [2, 3]], 'stristr' => ['alternativeName' => 'mb_stristr', 'argumentCount' => [2, 3]], 'strlen' => ['alternativeName' => 'mb_strlen', 'argumentCount' => [1]], 'strpos' => ['alternativeName' => 'mb_strpos', 'argumentCount' => [2, 3]], 'strrchr' => ['alternativeName' => 'mb_strrchr', 'argumentCount' => [2]], 'strripos' => ['alternativeName' => 'mb_strripos', 'argumentCount' => [2, 3]], 'strrpos' => ['alternativeName' => 'mb_strrpos', 'argumentCount' => [2, 3]], 'strstr' => ['alternativeName' => 'mb_strstr', 'argumentCount' => [2, 3]], 'strtolower' => ['alternativeName' => 'mb_strtolower', 'argumentCount' => [1]], 'strtoupper' => ['alternativeName' => 'mb_strtoupper', 'argumentCount' => [1]], 'substr' => ['alternativeName' => 'mb_substr', 'argumentCount' => [2, 3]], 'substr_count' => ['alternativeName' => 'mb_substr_count', 'argumentCount' => [2, 3, 4]], ]; private $functions; public function __construct() { parent::__construct(); $this->functions = array_filter( self::$functionsMap, static function (array $mapping) { return \function_exists($mapping['alternativeName']) && (new \ReflectionFunction($mapping['alternativeName']))->isInternal(); } ); } public function getDefinition() { return new FixerDefinition( 'Replace non multibyte-safe functions with corresponding mb function.', [ new CodeSample( 'isTokenKindFound(T_STRING); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $argumentsAnalyzer = new ArgumentsAnalyzer(); foreach ($this->functions as $functionIdentity => $functionReplacement) { $currIndex = 0; while (null !== $currIndex) { $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); if (null === $boundaries) { continue 2; } list($functionName, $openParenthesis, $closeParenthesis) = $boundaries; $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); if (!\in_array($count, $functionReplacement['argumentCount'], true)) { continue 2; } $currIndex = $openParenthesis; $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]); } } } } isTokenKindFound('`'); } public function getDefinition() { return new FixerDefinition( 'Converts backtick operators to `shell_exec` calls.', [ new CodeSample( <<<'EOT' call()}`; EOT ), ], 'Conversion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.' ); } public function getPriority() { return 2; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $backtickStarted = false; $backtickTokens = []; for ($index = $tokens->count() - 1; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->equals('`')) { if ($backtickStarted) { $backtickTokens[$index] = $token; } continue; } $backtickTokens[$index] = $token; if ($backtickStarted) { $this->fixBackticks($tokens, $backtickTokens); $backtickTokens = []; } $backtickStarted = !$backtickStarted; } } private function fixBackticks(Tokens $tokens, array $backtickTokens) { ksort($backtickTokens); $openingBacktickIndex = key($backtickTokens); end($backtickTokens); $closingBacktickIndex = key($backtickTokens); array_shift($backtickTokens); array_pop($backtickTokens); $count = \count($backtickTokens); $newTokens = [ new Token([T_STRING, 'shell_exec']), new Token('('), ]; if (1 !== $count) { $newTokens[] = new Token('"'); } foreach ($backtickTokens as $token) { if (!$token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { $newTokens[] = $token; continue; } $content = $token->getContent(); if (Preg::match('/[`"\']/u', $content)) { return; } $kind = T_ENCAPSED_AND_WHITESPACE; if (1 === $count) { $content = '"'.$content.'"'; $kind = T_CONSTANT_ENCAPSED_STRING; } $newTokens[] = new Token([$kind, $content]); } if (1 !== $count) { $newTokens[] = new Token('"'); } $newTokens[] = new Token(')'); $tokens->overrideRange($openingBacktickIndex, $closingBacktickIndex, $newTokens); } } getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.', [ new CodeSample( 'getMockWithoutInvokingTheOriginalConstructor("Foo"); $mock1 = $this->getMock("Foo"); $mock1 = $this->getMock("Bar", ["aaa"]); $mock1 = $this->getMock("Baz", ["aaa"], ["argument"]); // version with more than 2 params is not supported } } ' ), new CodeSample( 'getMock("Foo"); $mock1 = $this->getMock("Bar", ["aaa"]); // version with multiple params is not supported } } ', ['target' => PhpUnitTargetVersion::VERSION_5_4] ), ], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function isRisky() { return true; } public function configure(array $configuration = null) { parent::configure($configuration); $this->fixCreatePartialMock = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_5); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = $startIndex; $index < $endIndex; ++$index) { if (!$tokens[$index]->isGivenKind(T_OBJECT_OPERATOR)) { continue; } $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->equals([T_STRING, 'getMockWithoutInvokingTheOriginalConstructor'], false)) { $tokens[$index] = new Token([T_STRING, 'createMock']); } elseif ($tokens[$index]->equals([T_STRING, 'getMock'], false)) { $openingParenthesis = $tokens->getNextMeaningfulToken($index); $closingParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesis); $argumentsCount = $argumentsAnalyzer->countArguments($tokens, $openingParenthesis, $closingParenthesis); if (1 === $argumentsCount) { $tokens[$index] = new Token([T_STRING, 'createMock']); } elseif (2 === $argumentsCount && true === $this->fixCreatePartialMock) { $tokens[$index] = new Token([T_STRING, 'createPartialMock']); } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_4, PhpUnitTargetVersion::VERSION_5_5, PhpUnitTargetVersion::VERSION_NEWEST]) ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) ->getOption(), ]); } } PhpUnitTargetVersion::VERSION_4_8]), ], "PHPUnit v6 has finally fully switched to namespaces.\n" ."You could start preparing the upgrade by switching from non-namespaced TestCase to namespaced one.\n" .'Forward compatibility layer (`\PHPUnit\Framework\TestCase` class) was backported to PHPUnit v4.8.35 and PHPUnit v5.4.0.'."\n" .'Extended forward compatibility layer (`PHPUnit\Framework\Assert`, `PHPUnit\Framework\BaseTestListener`, `PHPUnit\Framework\TestListener` classes) was introduced in v5.7.0.'."\n", 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } public function configure(array $configuration = null) { parent::configure($configuration); if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_6_0)) { $this->originalClassRegEx = '/^PHPUnit_\w+$/i'; $this->classMap = [ 'PHPUnit_Extensions_PhptTestCase' => 'PHPUnit\Runner\PhptTestCase', 'PHPUnit_Framework_Constraint' => 'PHPUnit\Framework\Constraint\Constraint', 'PHPUnit_Framework_Constraint_StringMatches' => 'PHPUnit\Framework\Constraint\StringMatchesFormatDescription', 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => 'PHPUnit\Framework\Constraint\JsonMatchesErrorMessageProvider', 'PHPUnit_Framework_Constraint_PCREMatch' => 'PHPUnit\Framework\Constraint\RegularExpression', 'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => 'PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression', 'PHPUnit_Framework_Constraint_And' => 'PHPUnit\Framework\Constraint\LogicalAnd', 'PHPUnit_Framework_Constraint_Or' => 'PHPUnit\Framework\Constraint\LogicalOr', 'PHPUnit_Framework_Constraint_Not' => 'PHPUnit\Framework\Constraint\LogicalNot', 'PHPUnit_Framework_Constraint_Xor' => 'PHPUnit\Framework\Constraint\LogicalXor', 'PHPUnit_Framework_Error' => 'PHPUnit\Framework\Error\Error', 'PHPUnit_Framework_TestSuite_DataProvider' => 'PHPUnit\Framework\DataProviderTestSuite', 'PHPUnit_Framework_MockObject_Invocation_Static' => 'PHPUnit\Framework\MockObject\Invocation\StaticInvocation', 'PHPUnit_Framework_MockObject_Invocation_Object' => 'PHPUnit\Framework\MockObject\Invocation\ObjectInvocation', 'PHPUnit_Framework_MockObject_Stub_Return' => 'PHPUnit\Framework\MockObject\Stub\ReturnStub', 'PHPUnit_Runner_Filter_Group_Exclude' => 'PHPUnit\Runner\Filter\ExcludeGroupFilterIterator', 'PHPUnit_Runner_Filter_Group_Include' => 'PHPUnit\Runner\Filter\IncludeGroupFilterIterator', 'PHPUnit_Runner_Filter_Test' => 'PHPUnit\Runner\Filter\NameFilterIterator', 'PHPUnit_Util_PHP' => 'PHPUnit\Util\PHP\AbstractPhpProcess', 'PHPUnit_Util_PHP_Default' => 'PHPUnit\Util\PHP\DefaultPhpProcess', 'PHPUnit_Util_PHP_Windows' => 'PHPUnit\Util\PHP\WindowsPhpProcess', 'PHPUnit_Util_Regex' => 'PHPUnit\Util\RegularExpression', 'PHPUnit_Util_TestDox_ResultPrinter_XML' => 'PHPUnit\Util\TestDox\XmlResultPrinter', 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => 'PHPUnit\Util\TestDox\HtmlResultPrinter', 'PHPUnit_Util_TestDox_ResultPrinter_Text' => 'PHPUnit\Util\TestDox\TextResultPrinter', 'PHPUnit_Util_TestSuiteIterator' => 'PHPUnit\Framework\TestSuiteIterator', 'PHPUnit_Util_XML' => 'PHPUnit\Util\Xml', ]; } elseif (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_7)) { $this->originalClassRegEx = '/^PHPUnit_Framework_TestCase|PHPUnit_Framework_Assert|PHPUnit_Framework_BaseTestListener|PHPUnit_Framework_TestListener$/i'; $this->classMap = []; } else { $this->originalClassRegEx = '/^PHPUnit_Framework_TestCase$/i'; $this->classMap = []; } } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $importedOriginalClassesMap = []; $currIndex = 0; while (null !== $currIndex) { $currIndex = $tokens->getNextTokenOfKind($currIndex, [[T_STRING]]); if (null === $currIndex) { break; } $originalClass = $tokens[$currIndex]->getContent(); if (1 !== Preg::match($this->originalClassRegEx, $originalClass)) { ++$currIndex; continue; } $substituteTokens = $this->generateReplacement($originalClass); $tokens->clearAt($currIndex); $tokens->insertAt( $currIndex, isset($importedOriginalClassesMap[$originalClass]) ? $substituteTokens[$substituteTokens->getSize() - 1] : $substituteTokens ); $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); if ($tokens[$prevIndex]->isGivenKind(T_USE)) { $importedOriginalClassesMap[$originalClass] = true; } elseif ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); if ($tokens[$prevIndex]->isGivenKind(T_USE)) { $importedOriginalClassesMap[$originalClass] = true; } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([PhpUnitTargetVersion::VERSION_4_8, PhpUnitTargetVersion::VERSION_5_7, PhpUnitTargetVersion::VERSION_6_0, PhpUnitTargetVersion::VERSION_NEWEST]) ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) ->getOption(), ]); } private function generateReplacement($originalClassName) { $delimiter = '_'; $string = $originalClassName; if (isset($this->classMap[$originalClassName])) { $delimiter = '\\'; $string = $this->classMap[$originalClassName]; } $parts = explode($delimiter, $string); $tokensArray = []; while (!empty($parts)) { $tokensArray[] = new Token([T_STRING, array_shift($parts)]); if (!empty($parts)) { $tokensArray[] = new Token([T_NS_SEPARATOR, '\\']); } } return Tokens::fromArray($tokensArray); } } 'willReturnArgument', 'returncallback' => 'willReturnCallback', 'returnself' => 'willReturnSelf', 'returnvalue' => 'willReturn', 'returnvaluemap' => 'willReturnMap', ]; public function getDefinition() { return new FixerDefinition( 'Usage of PHPUnit\'s mock e.g. `->will($this->returnValue(..))` must be replaced by its shorter equivalent such as `->willReturn(...)`.', [ new CodeSample('createMock(Some::class); $someMock->method("some")->will($this->returnSelf()); $someMock->method("some")->will($this->returnValue("example")); $someMock->method("some")->will($this->returnArgument(2)); $someMock->method("some")->will($this->returnCallback("str_rot13")); $someMock->method("some")->will($this->returnValueMap(["a","b","c"])); } } '), ], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function isRisky() { return true; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { for ($index = $startIndex; $index < $endIndex; ++$index) { if (!$tokens[$index]->isGivenKind(T_OBJECT_OPERATOR)) { continue; } $functionToReplaceIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$functionToReplaceIndex]->equals([T_STRING, 'will'], false)) { continue; } $functionToReplaceOpeningBraceIndex = $tokens->getNextMeaningfulToken($functionToReplaceIndex); if (!$tokens[$functionToReplaceOpeningBraceIndex]->equals('(')) { continue; } $classReferenceIndex = $tokens->getNextMeaningfulToken($functionToReplaceOpeningBraceIndex); $objectOperatorIndex = $tokens->getNextMeaningfulToken($classReferenceIndex); if ( !($tokens[$classReferenceIndex]->equals([T_VARIABLE, '$this'], false) && $tokens[$objectOperatorIndex]->equals([T_OBJECT_OPERATOR, '->'])) && !($tokens[$classReferenceIndex]->equals([T_STRING, 'self'], false) && $tokens[$objectOperatorIndex]->equals([T_DOUBLE_COLON, '::'])) && !($tokens[$classReferenceIndex]->equals([T_STATIC, 'static'], false) && $tokens[$objectOperatorIndex]->equals([T_DOUBLE_COLON, '::'])) ) { continue; } $functionToRemoveIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex); if (!$tokens[$functionToRemoveIndex]->isGivenKind(T_STRING) || !\array_key_exists(strtolower($tokens[$functionToRemoveIndex]->getContent()), self::RETURN_METHODS_MAP)) { continue; } $openingBraceIndex = $tokens->getNextMeaningfulToken($functionToRemoveIndex); if (!$tokens[$openingBraceIndex]->equals('(')) { continue; } $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingBraceIndex); $tokens[$functionToReplaceIndex] = new Token([T_STRING, self::RETURN_METHODS_MAP[strtolower($tokens[$functionToRemoveIndex]->getContent())]]); $tokens->clearTokenAndMergeSurroundingWhitespace($classReferenceIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($objectOperatorIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($functionToRemoveIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($openingBraceIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($closingBraceIndex); } } } 'assertIsArray', 'boolean' => 'assertIsBool', 'bool' => 'assertIsBool', 'double' => 'assertIsFloat', 'float' => 'assertIsFloat', 'integer' => 'assertIsInt', 'int' => 'assertIsInt', 'null' => 'assertNull', 'numeric' => 'assertIsNumeric', 'object' => 'assertIsObject', 'real' => 'assertIsFloat', 'resource' => 'assertIsResource', 'string' => 'assertIsString', 'scalar' => 'assertIsScalar', 'callable' => 'assertIsCallable', 'iterable' => 'assertIsIterable', ]; public function getDefinition() { return new FixerDefinition( 'PHPUnit assertions like `assertIsArray` should be used over `assertInternalType`.', [ new CodeSample( 'assertInternalType("array", $var); $this->assertInternalType("boolean", $var); } } ' ), ], null, 'Risky when PHPUnit methods are overridden or when project has PHPUnit incompatibilities.' ); } public function isRisky() { return true; } public function getPriority() { return -16; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([PhpUnitTargetVersion::VERSION_7_5, PhpUnitTargetVersion::VERSION_NEWEST]) ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $anonymousClassIndexes = []; $tokenAnalyzer = new TokensAnalyzer($tokens); for ($index = $startIndex; $index < $endIndex; ++$index) { if (!$tokens[$index]->isClassy() || !$tokenAnalyzer->isAnonymousClass($index)) { continue; } $openingBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingBraceIndex); $anonymousClassIndexes[$closingBraceIndex] = $openingBraceIndex; } for ($index = $endIndex - 1; $index > $startIndex; --$index) { if (isset($anonymousClassIndexes[$index])) { $index = $anonymousClassIndexes[$index]; continue; } if (!$tokens[$index]->isGivenKind(T_STRING)) { continue; } $functionName = strtolower($tokens[$index]->getContent()); if ('assertinternaltype' !== $functionName && 'assertnotinternaltype' !== $functionName) { continue; } $bracketTokenIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$bracketTokenIndex]->equals('(')) { continue; } $expectedTypeTokenIndex = $tokens->getNextMeaningfulToken($bracketTokenIndex); $expectedTypeToken = $tokens[$expectedTypeTokenIndex]; if (!$expectedTypeToken->equals([T_CONSTANT_ENCAPSED_STRING])) { continue; } $expectedType = trim($expectedTypeToken->getContent(), '\'"'); if (!isset($this->typeToDedicatedAssertMap[$expectedType])) { continue; } $commaTokenIndex = $tokens->getNextMeaningfulToken($expectedTypeTokenIndex); if (!$tokens[$commaTokenIndex]->equals(',')) { continue; } $newAssertion = $this->typeToDedicatedAssertMap[$expectedType]; if ('assertnotinternaltype' === $functionName) { $newAssertion = str_replace('Is', 'IsNot', $newAssertion); $newAssertion = str_replace('Null', 'NotNull', $newAssertion); } $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($commaTokenIndex); $tokens->overrideRange($index, $nextMeaningfulTokenIndex - 1, [ new Token([T_STRING, $newAssertion]), new Token('('), ]); } } } whitespacesConfig->getLineEnding()), new CodeSample('whitespacesConfig->getLineEnding(), ['style' => 'annotation']), ], null, 'This fixer may change the name of your tests, and could cause incompatibility with'. ' abstract classes or interfaces.' ); } public function getPriority() { return 10; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { if ('annotation' === $this->configuration['style']) { $this->applyTestAnnotation($tokens, $startIndex, $endIndex); } else { $this->applyTestPrefix($tokens, $startIndex, $endIndex); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('style', 'Whether to use the @test annotation or not.')) ->setAllowedValues(['prefix', 'annotation']) ->setDefault('prefix') ->getOption(), (new FixerOptionBuilder('case', 'Whether to camel or snake case when adding the test prefix')) ->setAllowedValues(['camel', 'snake']) ->setDefault('camel') ->setDeprecationMessage('Use `php_unit_method_casing` fixer instead.') ->getOption(), ]); } private function applyTestAnnotation(Tokens $tokens, $startIndex, $endIndex) { for ($i = $endIndex - 1; $i > $startIndex; --$i) { if (!$this->isTestMethod($tokens, $i)) { continue; } $functionNameIndex = $tokens->getNextMeaningfulToken($i); $functionName = $tokens[$functionNameIndex]->getContent(); if ($this->hasTestPrefix($functionName) && !$this->hasProperTestAnnotation($tokens, $i)) { $newFunctionName = $this->removeTestPrefix($functionName); $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); } $docBlockIndex = $this->getDocBlockIndex($tokens, $i); if ($this->isPHPDoc($tokens, $docBlockIndex)) { $lines = $this->updateDocBlock($tokens, $docBlockIndex); $lines = $this->addTestAnnotation($lines, $tokens, $docBlockIndex); $lines = implode('', $lines); $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); } else { $this->createDocBlock($tokens, $docBlockIndex); } } } private function applyTestPrefix(Tokens $tokens, $startIndex, $endIndex) { for ($i = $endIndex - 1; $i > $startIndex; --$i) { if (!$this->isTestMethod($tokens, $i)) { continue; } $docBlockIndex = $this->getDocBlockIndex($tokens, $i); if (!$this->isPHPDoc($tokens, $docBlockIndex)) { continue; } $lines = $this->updateDocBlock($tokens, $docBlockIndex); $lines = implode('', $lines); $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); $functionNameIndex = $tokens->getNextMeaningfulToken($i); $functionName = $tokens[$functionNameIndex]->getContent(); if ($this->hasTestPrefix($functionName)) { continue; } $newFunctionName = $this->addTestPrefix($functionName); $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); } } private function isTestMethod(Tokens $tokens, $index) { if (!$this->isMethod($tokens, $index)) { return false; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); $functionName = $tokens[$functionNameIndex]->getContent(); if ($this->hasTestPrefix($functionName)) { return true; } $docBlockIndex = $this->getDocBlockIndex($tokens, $index); return $this->isPHPDoc($tokens, $docBlockIndex) && false !== strpos($tokens[$docBlockIndex]->getContent(), '@test') ; } private function isMethod(Tokens $tokens, $index) { $tokensAnalyzer = new TokensAnalyzer($tokens); return $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); } private function hasTestPrefix($functionName) { return 0 === strpos($functionName, 'test'); } private function hasProperTestAnnotation(Tokens $tokens, $index) { $docBlockIndex = $this->getDocBlockIndex($tokens, $index); $doc = $tokens[$docBlockIndex]->getContent(); return 1 === Preg::match('/\*\s+@test\b/', $doc); } private function removeTestPrefix($functionName) { $remainder = Preg::replace('/^test(?=[A-Z_])_?/', '', $functionName); if ('' === $remainder) { return $functionName; } return lcfirst($remainder); } private function addTestPrefix($functionName) { if ('camel' !== $this->configuration['case']) { return 'test_'.$functionName; } return 'test'.ucfirst($functionName); } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode($this->whitespacesConfig->getLineEnding(), $tokens[$index - 1]->getContent()); return end($explodedContent); } private function createDocBlock(Tokens $tokens, $docBlockIndex) { $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $toInsert = [ new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @test".$lineEnd."{$originalIndent} */"]), new Token([T_WHITESPACE, $lineEnd.$originalIndent]), ]; $index = $tokens->getNextMeaningfulToken($docBlockIndex); $tokens->insertAt($index, $toInsert); } private function updateDocBlock(Tokens $tokens, $docBlockIndex) { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); $lines = $doc->getLines(); return $this->updateLines($lines, $tokens, $docBlockIndex); } private function updateLines($lines, Tokens $tokens, $docBlockIndex) { $needsAnnotation = 'annotation' === $this->configuration['style']; $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); for ($i = 0; $i < \count($lines); ++$i) { if ($needsAnnotation && ($lines[$i]->isTheStart() && $lines[$i]->isTheEnd())) { if (!$this->doesDocBlockContainTest($doc)) { $lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex); return $this->updateLines($lines, $tokens, $docBlockIndex); } } if (!$needsAnnotation && false !== strpos($lines[$i]->getContent(), ' @test') && false === strpos($lines[$i]->getContent(), '@testWith') && false === strpos($lines[$i]->getContent(), '@testdox') ) { $lines[$i] = new Line(str_replace(' @test', '', $lines[$i]->getContent())); } if (false === strpos($lines[$i]->getContent(), '@depends')) { continue; } $lines[$i] = $this->updateDependsAnnotation($lines[$i]); } return $lines; } private function splitUpDocBlock($lines, Tokens $tokens, $docBlockIndex) { $lineContent = $this->getSingleLineDocBlockEntry($lines); $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); return [ new Line('/**'.$lineEnd), new Line($originalIndent.' * '.$lineContent.$lineEnd), new Line($originalIndent.' */'), ]; } private function getSingleLineDocBlockEntry($line) { $line = $line[0]; $line = str_replace('*/', '', $line); $line = trim($line); $line = str_split($line); $i = \count($line); do { --$i; } while ('*' !== $line[$i] && '*' !== $line[$i - 1] && '/' !== $line[$i - 2]); if (' ' === $line[$i]) { ++$i; } $line = \array_slice($line, $i); return implode('', $line); } private function updateDependsAnnotation(Line $line) { if ('annotation' === $this->configuration['style']) { return $this->removeTestPrefixFromDependsAnnotation($line); } return $this->addTestPrefixToDependsAnnotation($line); } private function removeTestPrefixFromDependsAnnotation(Line $line) { $line = str_split($line->getContent()); $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); if ($this->hasTestPrefix($dependsFunctionName)) { $dependsFunctionName = $this->removeTestPrefix($dependsFunctionName); } array_splice($line, $dependsIndex); return new Line(implode('', $line).$dependsFunctionName); } private function addTestPrefixToDependsAnnotation(Line $line) { $line = str_split($line->getContent()); $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); if (!$this->hasTestPrefix($dependsFunctionName)) { $dependsFunctionName = $this->addTestPrefix($dependsFunctionName); } array_splice($line, $dependsIndex); return new Line(implode('', $line).$dependsFunctionName); } private function findWhereDependsFunctionNameStarts(array $line) { $counter = \count($line); do { --$counter; } while (' ' !== $line[$counter]); return $counter + 1; } private function addTestAnnotation($lines, Tokens $tokens, $docBlockIndex) { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); if (!$this->doesDocBlockContainTest($doc)) { $originalIndent = $this->detectIndent($tokens, $docBlockIndex); $lineEnd = $this->whitespacesConfig->getLineEnding(); array_splice($lines, -1, 0, $originalIndent.' *'.$lineEnd.$originalIndent.' * @test'.$lineEnd); } return $lines; } private function doesDocBlockContainTest(DocBlock $doc) { return !empty($doc->getAnnotationsOfType('test')); } } true, self::CALL_TYPE_SELF => true, self::CALL_TYPE_STATIC => true, ]; private $staticMethods = [ 'anything' => true, 'arrayHasKey' => true, 'assertArrayHasKey' => true, 'assertArrayNotHasKey' => true, 'assertArraySubset' => true, 'assertAttributeContains' => true, 'assertAttributeContainsOnly' => true, 'assertAttributeCount' => true, 'assertAttributeEmpty' => true, 'assertAttributeEquals' => true, 'assertAttributeGreaterThan' => true, 'assertAttributeGreaterThanOrEqual' => true, 'assertAttributeInstanceOf' => true, 'assertAttributeInternalType' => true, 'assertAttributeLessThan' => true, 'assertAttributeLessThanOrEqual' => true, 'assertAttributeNotContains' => true, 'assertAttributeNotContainsOnly' => true, 'assertAttributeNotCount' => true, 'assertAttributeNotEmpty' => true, 'assertAttributeNotEquals' => true, 'assertAttributeNotInstanceOf' => true, 'assertAttributeNotInternalType' => true, 'assertAttributeNotSame' => true, 'assertAttributeSame' => true, 'assertClassHasAttribute' => true, 'assertClassHasStaticAttribute' => true, 'assertClassNotHasAttribute' => true, 'assertClassNotHasStaticAttribute' => true, 'assertContains' => true, 'assertContainsEquals' => true, 'assertContainsOnly' => true, 'assertContainsOnlyInstancesOf' => true, 'assertCount' => true, 'assertDirectoryDoesNotExist' => true, 'assertDirectoryExists' => true, 'assertDirectoryIsNotReadable' => true, 'assertDirectoryIsNotWritable' => true, 'assertDirectoryIsReadable' => true, 'assertDirectoryIsWritable' => true, 'assertDirectoryNotExists' => true, 'assertDirectoryNotIsReadable' => true, 'assertDirectoryNotIsWritable' => true, 'assertDoesNotMatchRegularExpression' => true, 'assertEmpty' => true, 'assertEqualXMLStructure' => true, 'assertEquals' => true, 'assertEqualsCanonicalizing' => true, 'assertEqualsIgnoringCase' => true, 'assertEqualsWithDelta' => true, 'assertFalse' => true, 'assertFileDoesNotExist' => true, 'assertFileEquals' => true, 'assertFileEqualsCanonicalizing' => true, 'assertFileEqualsIgnoringCase' => true, 'assertFileExists' => true, 'assertFileIsNotReadable' => true, 'assertFileIsNotWritable' => true, 'assertFileIsReadable' => true, 'assertFileIsWritable' => true, 'assertFileNotEquals' => true, 'assertFileNotEqualsCanonicalizing' => true, 'assertFileNotEqualsIgnoringCase' => true, 'assertFileNotExists' => true, 'assertFileNotIsReadable' => true, 'assertFileNotIsWritable' => true, 'assertFinite' => true, 'assertGreaterThan' => true, 'assertGreaterThanOrEqual' => true, 'assertInfinite' => true, 'assertInstanceOf' => true, 'assertInternalType' => true, 'assertIsArray' => true, 'assertIsBool' => true, 'assertIsCallable' => true, 'assertIsClosedResource' => true, 'assertIsFloat' => true, 'assertIsInt' => true, 'assertIsIterable' => true, 'assertIsNotArray' => true, 'assertIsNotBool' => true, 'assertIsNotCallable' => true, 'assertIsNotClosedResource' => true, 'assertIsNotFloat' => true, 'assertIsNotInt' => true, 'assertIsNotIterable' => true, 'assertIsNotNumeric' => true, 'assertIsNotObject' => true, 'assertIsNotReadable' => true, 'assertIsNotResource' => true, 'assertIsNotScalar' => true, 'assertIsNotString' => true, 'assertIsNotWritable' => true, 'assertIsNumeric' => true, 'assertIsObject' => true, 'assertIsReadable' => true, 'assertIsResource' => true, 'assertIsScalar' => true, 'assertIsString' => true, 'assertIsWritable' => true, 'assertJson' => true, 'assertJsonFileEqualsJsonFile' => true, 'assertJsonFileNotEqualsJsonFile' => true, 'assertJsonStringEqualsJsonFile' => true, 'assertJsonStringEqualsJsonString' => true, 'assertJsonStringNotEqualsJsonFile' => true, 'assertJsonStringNotEqualsJsonString' => true, 'assertLessThan' => true, 'assertLessThanOrEqual' => true, 'assertMatchesRegularExpression' => true, 'assertNan' => true, 'assertNotContains' => true, 'assertNotContainsEquals' => true, 'assertNotContainsOnly' => true, 'assertNotCount' => true, 'assertNotEmpty' => true, 'assertNotEquals' => true, 'assertNotEqualsCanonicalizing' => true, 'assertNotEqualsIgnoringCase' => true, 'assertNotEqualsWithDelta' => true, 'assertNotFalse' => true, 'assertNotInstanceOf' => true, 'assertNotInternalType' => true, 'assertNotIsReadable' => true, 'assertNotIsWritable' => true, 'assertNotNull' => true, 'assertNotRegExp' => true, 'assertNotSame' => true, 'assertNotSameSize' => true, 'assertNotTrue' => true, 'assertNull' => true, 'assertObjectEquals' => true, 'assertObjectHasAttribute' => true, 'assertObjectNotHasAttribute' => true, 'assertRegExp' => true, 'assertSame' => true, 'assertSameSize' => true, 'assertStringContainsString' => true, 'assertStringContainsStringIgnoringCase' => true, 'assertStringEndsNotWith' => true, 'assertStringEndsWith' => true, 'assertStringEqualsFile' => true, 'assertStringEqualsFileCanonicalizing' => true, 'assertStringEqualsFileIgnoringCase' => true, 'assertStringMatchesFormat' => true, 'assertStringMatchesFormatFile' => true, 'assertStringNotContainsString' => true, 'assertStringNotContainsStringIgnoringCase' => true, 'assertStringNotEqualsFile' => true, 'assertStringNotEqualsFileCanonicalizing' => true, 'assertStringNotEqualsFileIgnoringCase' => true, 'assertStringNotMatchesFormat' => true, 'assertStringNotMatchesFormatFile' => true, 'assertStringStartsNotWith' => true, 'assertStringStartsWith' => true, 'assertThat' => true, 'assertTrue' => true, 'assertXmlFileEqualsXmlFile' => true, 'assertXmlFileNotEqualsXmlFile' => true, 'assertXmlStringEqualsXmlFile' => true, 'assertXmlStringEqualsXmlString' => true, 'assertXmlStringNotEqualsXmlFile' => true, 'assertXmlStringNotEqualsXmlString' => true, 'attribute' => true, 'attributeEqualTo' => true, 'callback' => true, 'classHasAttribute' => true, 'classHasStaticAttribute' => true, 'contains' => true, 'containsEqual' => true, 'containsIdentical' => true, 'containsOnly' => true, 'containsOnlyInstancesOf' => true, 'countOf' => true, 'directoryExists' => true, 'equalTo' => true, 'equalToCanonicalizing' => true, 'equalToIgnoringCase' => true, 'equalToWithDelta' => true, 'fail' => true, 'fileExists' => true, 'getCount' => true, 'getObjectAttribute' => true, 'getStaticAttribute' => true, 'greaterThan' => true, 'greaterThanOrEqual' => true, 'identicalTo' => true, 'isEmpty' => true, 'isFalse' => true, 'isFinite' => true, 'isInfinite' => true, 'isInstanceOf' => true, 'isJson' => true, 'isNan' => true, 'isNull' => true, 'isReadable' => true, 'isTrue' => true, 'isType' => true, 'isWritable' => true, 'lessThan' => true, 'lessThanOrEqual' => true, 'logicalAnd' => true, 'logicalNot' => true, 'logicalOr' => true, 'logicalXor' => true, 'markTestIncomplete' => true, 'markTestSkipped' => true, 'matches' => true, 'matchesRegularExpression' => true, 'objectEquals' => true, 'objectHasAttribute' => true, 'readAttribute' => true, 'resetCount' => true, 'stringContains' => true, 'stringEndsWith' => true, 'stringStartsWith' => true, 'any' => true, 'at' => true, 'atLeast' => true, 'atLeastOnce' => true, 'atMost' => true, 'exactly' => true, 'never' => true, 'once' => true, 'onConsecutiveCalls' => true, 'returnArgument' => true, 'returnCallback' => true, 'returnSelf' => true, 'returnValue' => true, 'returnValueMap' => true, 'setUpBeforeClass' => true, 'tearDownAfterClass' => true, 'throwException' => true, ]; private $conversionMap = [ self::CALL_TYPE_THIS => [[T_OBJECT_OPERATOR, '->'], [T_VARIABLE, '$this']], self::CALL_TYPE_SELF => [[T_DOUBLE_COLON, '::'], [T_STRING, 'self']], self::CALL_TYPE_STATIC => [[T_DOUBLE_COLON, '::'], [T_STATIC, 'static']], ]; public function getDefinition() { $codeSample = 'assertSame(1, 2); self::assertSame(1, 2); static::assertSame(1, 2); } } '; return new FixerDefinition( 'Calls to `PHPUnit\Framework\TestCase` static methods must all be of the same type, either `$this->`, `self::` or `static::`.', [ new CodeSample($codeSample), new CodeSample($codeSample, ['call_type' => self::CALL_TYPE_THIS]), ], null, 'Risky when PHPUnit methods are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function getPriority() { return 0; } public function isRisky() { return true; } protected function createConfigurationDefinition() { $thisFixer = $this; return new FixerConfigurationResolver([ (new FixerOptionBuilder('call_type', 'The call type to use for referring to PHPUnit methods.')) ->setAllowedTypes(['string']) ->setAllowedValues(array_keys($this->allowedValues)) ->setDefault('static') ->getOption(), (new FixerOptionBuilder('methods', 'Dictionary of `method` => `call_type` values that differ from the default strategy.')) ->setAllowedTypes(['array']) ->setAllowedValues([static function ($option) use ($thisFixer) { foreach ($option as $method => $value) { if (!isset($thisFixer->staticMethods[$method])) { throw new InvalidOptionsException( sprintf( 'Unexpected "methods" key, expected any of "%s", got "%s".', implode('", "', array_keys($thisFixer->staticMethods)), \is_object($method) ? \get_class($method) : \gettype($method).'#'.$method ) ); } if (!isset($thisFixer->allowedValues[$value])) { throw new InvalidOptionsException( sprintf( 'Unexpected value for method "%s", expected any of "%s", got "%s".', $method, implode('", "', array_keys($thisFixer->allowedValues)), \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value) ) ); } } return true; }]) ->setDefault([]) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $analyzer = new TokensAnalyzer($tokens); for ($index = $startIndex; $index < $endIndex; ++$index) { if ($tokens[$index]->isGivenKind(T_CLASS)) { $index = $this->findEndOfNextBlock($tokens, $index); continue; } $callType = $this->configuration['call_type']; if ($tokens[$index]->isGivenKind(T_FUNCTION)) { if ($analyzer->isLambda($index)) { $index = $this->findEndOfNextBlock($tokens, $index); continue; } if ('this' === $callType) { $attributes = $analyzer->getMethodAttributes($index); if (false !== $attributes['static']) { $index = $this->findEndOfNextBlock($tokens, $index); continue; } } } if (!$tokens[$index]->isGivenKind(T_STRING) || !isset($this->staticMethods[$tokens[$index]->getContent()])) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$nextIndex]->equals('(')) { $index = $nextIndex; continue; } $methodName = $tokens[$index]->getContent(); if (isset($this->configuration['methods'][$methodName])) { $callType = $this->configuration['methods'][$methodName]; } $operatorIndex = $tokens->getPrevMeaningfulToken($index); $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); if (!$this->needsConversion($tokens, $index, $referenceIndex, $callType)) { continue; } $tokens[$operatorIndex] = new Token($this->conversionMap[$callType][0]); $tokens[$referenceIndex] = new Token($this->conversionMap[$callType][1]); } } private function needsConversion(Tokens $tokens, $index, $referenceIndex, $callType) { $functionsAnalyzer = new FunctionsAnalyzer(); return $functionsAnalyzer->isTheSameClassCall($tokens, $index) && !$tokens[$referenceIndex]->equals($this->conversionMap[$callType][1], false); } private function findEndOfNextBlock(Tokens $tokens, $index) { $index = $tokens->getNextTokenOfKind($index, ['{']); return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); } } hello = "hello"; } public function tearDown() { $this->hello = null; } } ' ), ], null, 'This fixer may change functions named `setUp()` or `tearDown()` outside of PHPUnit tests, '. 'when a class is wrongly seen as a PHPUnit test.' ); } public function isRisky() { return true; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $counter = 0; $tokensAnalyzer = new TokensAnalyzer($tokens); for ($i = $endIndex - 1; $i > $startIndex; --$i) { if (2 === $counter) { break; } if (!$this->isSetupOrTearDownMethod($tokens, $i)) { continue; } ++$counter; $visibility = $tokensAnalyzer->getMethodAttributes($i)['visibility']; if (T_PUBLIC === $visibility) { $index = $tokens->getPrevTokenOfKind($i, [[T_PUBLIC]]); $tokens[$index] = new Token([T_PROTECTED, 'protected']); continue; } if (null === $visibility) { $tokens->insertAt($i, [new Token([T_PROTECTED, 'protected']), new Token([T_WHITESPACE, ' '])]); } } } private function isSetupOrTearDownMethod(Tokens $tokens, $index) { $tokensAnalyzer = new TokensAnalyzer($tokens); $isMethod = $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); if (!$isMethod) { return false; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); $functionName = strtolower($tokens[$functionNameIndex]->getContent()); return 'setup' === $functionName || 'teardown' === $functionName; } } getPrevTokenOfKind($startIndex, [[T_CLASS]]); $docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex); for ($index = $endIndex; $index >= $docBlockIndex; --$index) { if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT) || 0 === Preg::match('/@covers\s.+@covers\s/s', $tokens[$index]->getContent())) { continue; } $docBlock = new DocBlock($tokens[$index]->getContent()); $covers = $docBlock->getAnnotationsOfType('covers'); $coversMap = []; foreach ($covers as $annotation) { $rawContent = $annotation->getContent(); $comparableContent = Preg::replace('/\*\s*@covers\s+(.+)/', '\1', strtolower(trim($rawContent))); $coversMap[$comparableContent] = $rawContent; } $orderedCoversMap = $coversMap; ksort($orderedCoversMap, SORT_STRING); if ($orderedCoversMap === $coversMap) { continue; } $lines = $docBlock->getLines(); foreach (array_reverse($covers) as $annotation) { array_splice( $lines, $annotation->getStart(), $annotation->getEnd() - $annotation->getStart() + 1, array_pop($orderedCoversMap) ); } $tokens[$index] = new Token([T_DOC_COMMENT, implode('', $lines)]); } } } 'medium']), ], 'The special groups [small, medium, large] provides a way to identify tests that are taking long to be executed.' ); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('group', 'Define a specific group to be used in case no group is already in use')) ->setAllowedValues(['small', 'medium', 'large']) ->setDefault('small') ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); if ($this->isAbstractClass($tokens, $classIndex)) { return; } $docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex); if ($this->isPHPDoc($tokens, $docBlockIndex)) { $this->updateDocBlockIfNeeded($tokens, $docBlockIndex); } else { $this->createDocBlock($tokens, $docBlockIndex); } } private function isAbstractClass(Tokens $tokens, $i) { $typeIndex = $tokens->getPrevMeaningfulToken($i); return $tokens[$typeIndex]->isGivenKind(T_ABSTRACT); } private function createDocBlock(Tokens $tokens, $docBlockIndex) { $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $group = $this->configuration['group']; $toInsert = [ new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @".$group.$lineEnd."{$originalIndent} */"]), new Token([T_WHITESPACE, $lineEnd.$originalIndent]), ]; $index = $tokens->getNextMeaningfulToken($docBlockIndex); $tokens->insertAt($index, $toInsert); } private function updateDocBlockIfNeeded(Tokens $tokens, $docBlockIndex) { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); if (!empty($this->filterDocBlock($doc))) { return; } $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex); $lines = $this->addSizeAnnotation($doc, $tokens, $docBlockIndex); $lines = implode('', $lines); $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode($this->whitespacesConfig->getLineEnding(), $tokens[$index - 1]->getContent()); return end($explodedContent); } private function addSizeAnnotation(DocBlock $docBlock, Tokens $tokens, $docBlockIndex) { $lines = $docBlock->getLines(); $originalIndent = $this->detectIndent($tokens, $docBlockIndex); $lineEnd = $this->whitespacesConfig->getLineEnding(); $group = $this->configuration['group']; array_splice($lines, -1, 0, $originalIndent.' *'.$lineEnd.$originalIndent.' * @'.$group.$lineEnd); return $lines; } private function makeDocBlockMultiLineIfNeeded(DocBlock $doc, Tokens $tokens, $docBlockIndex) { $lines = $doc->getLines(); if (1 === \count($lines) && empty($this->filterDocBlock($doc))) { $lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex); return new DocBlock(implode('', $lines)); } return $doc; } private function splitUpDocBlock($lines, Tokens $tokens, $docBlockIndex) { $lineContent = $this->getSingleLineDocBlockEntry($lines); $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); return [ new Line('/**'.$lineEnd), new Line($originalIndent.' * '.$lineContent.$lineEnd), new Line($originalIndent.' */'), ]; } private function getSingleLineDocBlockEntry($line) { $line = $line[0]; $line = str_replace('*/', '', $line); $line = trim($line); $line = str_split($line); $i = \count($line); do { --$i; } while ('*' !== $line[$i] && '*' !== $line[$i - 1] && '/' !== $line[$i - 2]); if (' ' === $line[$i]) { ++$i; } $line = \array_slice($line, $i); return implode('', $line); } private function filterDocBlock(DocBlock $doc) { return array_filter([ $doc->getAnnotationsOfType('small'), $doc->getAnnotationsOfType('large'), $doc->getAnnotationsOfType('medium'), ]); } } fixMessageRegExp = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_4_3); } public function getDefinition() { return new FixerDefinition( 'Usages of `@expectedException*` annotations MUST be replaced by `->setExpectedException*` methods.', [ new CodeSample( ' PhpUnitTargetVersion::VERSION_3_2] ), ], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function getPriority() { return 10; } public function isRisky() { return true; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([PhpUnitTargetVersion::VERSION_3_2, PhpUnitTargetVersion::VERSION_4_3, PhpUnitTargetVersion::VERSION_NEWEST]) ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) ->getOption(), (new FixerOptionBuilder('use_class_const', 'Use ::class notation.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($i = $endIndex - 1; $i > $startIndex; --$i) { if (!$tokens[$i]->isGivenKind(T_FUNCTION) || $tokensAnalyzer->isLambda($i)) { continue; } $functionIndex = $i; $docBlockIndex = $i; $braceIndex = $tokens->getNextTokenOfKind($functionIndex, [';', '{']); if (!$tokens[$braceIndex]->equals('{')) { continue; } do { $docBlockIndex = $tokens->getPrevNonWhitespace($docBlockIndex); } while ($tokens[$docBlockIndex]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT])); if (!$tokens[$docBlockIndex]->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); $annotations = []; foreach ($doc->getAnnotationsOfType([ 'expectedException', 'expectedExceptionCode', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp', ]) as $annotation) { $tag = $annotation->getTag()->getName(); $content = $this->extractContentFromAnnotation($annotation); $annotations[$tag] = $content; $annotation->remove(); } if (!isset($annotations['expectedException'])) { continue; } if (!$this->fixMessageRegExp && isset($annotations['expectedExceptionMessageRegExp'])) { continue; } $originalIndent = $this->detectIndent($tokens, $docBlockIndex); $paramList = $this->annotationsToParamList($annotations); $newMethodsCode = '' .(isset($annotations['expectedExceptionMessageRegExp']) ? 'setExpectedExceptionRegExp' : 'setExpectedException') .'(' .implode(', ', $paramList) .');'; $newMethods = Tokens::fromCode($newMethodsCode); $newMethods[0] = new Token([ T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$originalIndent.$this->whitespacesConfig->getIndent(), ]); $docContent = $doc->getContent(); if ('' === $docContent) { $docContent = '/** */'; } $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $docContent]); $tokens->insertAt($braceIndex + 1, $newMethods); $whitespaceIndex = $braceIndex + $newMethods->getSize() + 1; $tokens[$whitespaceIndex] = new Token([ T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$tokens[$whitespaceIndex]->getContent(), ]); $i = $docBlockIndex; } } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode("\n", $tokens[$index - 1]->getContent()); return end($explodedContent); } private function extractContentFromAnnotation(Annotation $annotation) { $tag = $annotation->getTag()->getName(); if (1 !== Preg::match('/@'.$tag.'\s+(.+)$/s', $annotation->getContent(), $matches)) { return ''; } $content = Preg::replace('/\*+\/$/', '', $matches[1]); if (Preg::match('/\R/u', $content)) { $content = Preg::replace('/\s*\R+\s*\*\s*/u', ' ', $content); } return rtrim($content); } private function annotationsToParamList(array $annotations) { $params = []; $exceptionClass = ltrim($annotations['expectedException'], '\\'); if ($this->configuration['use_class_const']) { $params[] = "\\{$exceptionClass}::class"; } else { $params[] = "'{$exceptionClass}'"; } if (isset($annotations['expectedExceptionMessage'])) { $params[] = var_export($annotations['expectedExceptionMessage'], true); } elseif (isset($annotations['expectedExceptionMessageRegExp'])) { $params[] = var_export($annotations['expectedExceptionMessageRegExp'], true); } elseif (isset($annotations['expectedExceptionCode'])) { $params[] = 'null'; } if (isset($annotations['expectedExceptionCode'])) { $params[] = $annotations['expectedExceptionCode']; } return $params; } } self::SNAKE_CASE] ), ] ); } public function getPriority() { return 0; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('case', 'Apply camel or snake case to test methods')) ->setAllowedValues([self::CAMEL_CASE, self::SNAKE_CASE]) ->setDefault(self::CAMEL_CASE) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { for ($index = $endIndex - 1; $index > $startIndex; --$index) { if (!$this->isTestMethod($tokens, $index)) { continue; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); $functionName = $tokens[$functionNameIndex]->getContent(); $newFunctionName = $this->updateMethodCasing($functionName); if ($newFunctionName !== $functionName) { $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); } $docBlockIndex = $this->getDocBlockIndex($tokens, $index); if ($this->isPHPDoc($tokens, $docBlockIndex)) { $this->updateDocBlock($tokens, $docBlockIndex); } } } private function updateMethodCasing($functionName) { if (self::CAMEL_CASE === $this->configuration['case']) { $newFunctionName = $functionName; $newFunctionName = ucwords($newFunctionName, '_'); $newFunctionName = str_replace('_', '', $newFunctionName); $newFunctionName = lcfirst($newFunctionName); } else { $newFunctionName = Utils::camelCaseToUnderscore($functionName); } return $newFunctionName; } private function isTestMethod(Tokens $tokens, $index) { if (!$this->isMethod($tokens, $index)) { return false; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); $functionName = $tokens[$functionNameIndex]->getContent(); if ($this->startsWith('test', $functionName)) { return true; } $docBlockIndex = $this->getDocBlockIndex($tokens, $index); return $this->isPHPDoc($tokens, $docBlockIndex) && false !== strpos($tokens[$docBlockIndex]->getContent(), '@test') ; } private function isMethod(Tokens $tokens, $index) { $tokensAnalyzer = new TokensAnalyzer($tokens); return $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); } private function startsWith($needle, $haystack) { return substr($haystack, 0, \strlen($needle)) === $needle; } private function updateDocBlock(Tokens $tokens, $docBlockIndex) { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); $lines = $doc->getLines(); $docBlockNeedsUpdate = false; for ($inc = 0; $inc < \count($lines); ++$inc) { $lineContent = $lines[$inc]->getContent(); if (false === strpos($lineContent, '@depends')) { continue; } $newLineContent = Preg::replaceCallback('/(@depends\s+)(.+)(\b)/', function (array $matches) { return sprintf( '%s%s%s', $matches[1], $this->updateMethodCasing($matches[2]), $matches[3] ); }, $lineContent); if ($newLineContent !== $lineContent) { $lines[$inc] = new Line($newLineContent); $docBlockNeedsUpdate = true; } } if ($docBlockNeedsUpdate) { $lines = implode('', $lines); $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); } } } 'fixAssertPositive', 'assertEquals' => 'fixAssertPositive', 'assertNotEquals' => 'fixAssertNegative', 'assertNotSame' => 'fixAssertNegative', ]; public function isRisky() { return true; } public function getDefinition() { return new FixerDefinition( 'PHPUnit assertion method calls like `->assertSame(true, $foo)` should be written with dedicated method like `->assertTrue($foo)`.', [ new CodeSample( 'assertEquals(false, $b); $this->assertSame(true, $a); $this->assertNotEquals(null, $c); $this->assertNotSame(null, $d); } } ' ), new CodeSample( 'assertEquals(false, $b); $this->assertSame(true, $a); $this->assertNotEquals(null, $c); $this->assertNotSame(null, $d); } } ', ['assertions' => ['assertSame', 'assertNotSame']] ), ], null, 'Fixer could be risky if one is overriding PHPUnit\'s native methods.' ); } public function getPriority() { return -10; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { if (empty($this->configuration['assertions'])) { return; } foreach ($this->configuration['assertions'] as $assertionMethod) { $assertionFixer = self::$assertionFixers[$assertionMethod]; for ($index = $startIndex; $index < $endIndex; ++$index) { $index = $this->{$assertionFixer}($tokens, $index, $assertionMethod); if (null === $index) { break; } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('assertions', [ (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(array_keys(self::$assertionFixers))]) ->setDefault([ 'assertEquals', 'assertSame', 'assertNotEquals', 'assertNotSame', ]) ->getOption(), ], $this->getName()); } private function fixAssertNegative(Tokens $tokens, $index, $method) { static $map = [ 'false' => 'assertNotFalse', 'null' => 'assertNotNull', 'true' => 'assertNotTrue', ]; return $this->fixAssert($map, $tokens, $index, $method); } private function fixAssertPositive(Tokens $tokens, $index, $method) { static $map = [ 'false' => 'assertFalse', 'null' => 'assertNull', 'true' => 'assertTrue', ]; return $this->fixAssert($map, $tokens, $index, $method); } private function fixAssert(array $map, Tokens $tokens, $index, $method) { $functionsAnalyzer = new FunctionsAnalyzer(); $sequence = $tokens->findSequence( [ [T_STRING, $method], '(', ], $index ); if (null === $sequence) { return null; } $sequenceIndexes = array_keys($sequence); if (!$functionsAnalyzer->isTheSameClassCall($tokens, $sequenceIndexes[0])) { return null; } $sequenceIndexes[2] = $tokens->getNextMeaningfulToken($sequenceIndexes[1]); $firstParameterToken = $tokens[$sequenceIndexes[2]]; if (!$firstParameterToken->isNativeConstant()) { return $sequenceIndexes[2]; } $sequenceIndexes[3] = $tokens->getNextMeaningfulToken($sequenceIndexes[2]); if (!$tokens[$sequenceIndexes[3]]->equals(',')) { return $sequenceIndexes[3]; } $tokens[$sequenceIndexes[0]] = new Token([T_STRING, $map[strtolower($firstParameterToken->getContent())]]); $tokens->clearRange($sequenceIndexes[2], $tokens->getNextNonWhitespace($sequenceIndexes[3]) - 1); return $sequenceIndexes[3]; } } methodMap = [ 'setExpectedException' => 'expectExceptionMessage', ]; if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp'; } } public function getDefinition() { return new FixerDefinition( 'Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.', [ new CodeSample( 'setExpectedException("RuntimeException", "Msg", 123); foo(); } public function testBar() { $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); bar(); } } ' ), new CodeSample( 'setExpectedException("RuntimeException", null, 123); foo(); } public function testBar() { $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); bar(); } } ', ['target' => PhpUnitTargetVersion::VERSION_5_6] ), new CodeSample( 'setExpectedException("RuntimeException", "Msg", 123); foo(); } public function testBar() { $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); bar(); } } ', ['target' => PhpUnitTargetVersion::VERSION_5_2] ), ], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' ); } public function getPriority() { return 0; } public function isRisky() { return true; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_2, PhpUnitTargetVersion::VERSION_5_6, PhpUnitTargetVersion::VERSION_NEWEST]) ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $argumentsAnalyzer = new ArgumentsAnalyzer(); $oldMethodSequence = [ new Token([T_VARIABLE, '$this']), new Token([T_OBJECT_OPERATOR, '->']), [T_STRING], ]; for ($index = $startIndex; $startIndex < $endIndex; ++$index) { $match = $tokens->findSequence($oldMethodSequence, $index); if (null === $match) { return; } list($thisIndex, , $index) = array_keys($match); if (!isset($this->methodMap[$tokens[$index]->getContent()])) { continue; } $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); if ($tokens[$commaIndex]->equals(',')) { $tokens->removeTrailingWhitespace($commaIndex); $tokens->clearAt($commaIndex); } $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); $argumentsCnt = \count($arguments); $argumentsReplacements = ['expectException', $this->methodMap[$tokens[$index]->getContent()], 'expectExceptionCode']; $indent = $this->whitespacesConfig->getLineEnding().$this->detectIndent($tokens, $thisIndex); $isMultilineWhitespace = false; for ($cnt = $argumentsCnt - 1; $cnt >= 1; --$cnt) { $argStart = array_keys($arguments)[$cnt]; $argBefore = $tokens->getPrevMeaningfulToken($argStart); if ('expectExceptionMessage' === $argumentsReplacements[$cnt]) { $paramIndicatorIndex = $tokens->getNextMeaningfulToken($argBefore); $afterParamIndicatorIndex = $tokens->getNextMeaningfulToken($paramIndicatorIndex); if ( $tokens[$paramIndicatorIndex]->equals([T_STRING, 'null'], false) && $tokens[$afterParamIndicatorIndex]->equals(')') ) { if ($tokens[$argBefore + 1]->isWhitespace()) { $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore + 1); } $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore); $tokens->clearTokenAndMergeSurroundingWhitespace($paramIndicatorIndex); continue; } } $isMultilineWhitespace = $isMultilineWhitespace || ($tokens[$argStart]->isWhitespace() && !$tokens[$argStart]->isWhitespace(" \t")); $tokensOverrideArgStart = [ new Token([T_WHITESPACE, $indent]), new Token([T_VARIABLE, '$this']), new Token([T_OBJECT_OPERATOR, '->']), new Token([T_STRING, $argumentsReplacements[$cnt]]), new Token('('), ]; $tokensOverrideArgBefore = [ new Token(')'), new Token(';'), ]; if ($isMultilineWhitespace) { $tokensOverrideArgStart[] = new Token([T_WHITESPACE, $indent.$this->whitespacesConfig->getIndent()]); array_unshift($tokensOverrideArgBefore, new Token([T_WHITESPACE, $indent])); } if ($tokens[$argStart]->isWhitespace()) { $tokens->overrideRange($argStart, $argStart, $tokensOverrideArgStart); } else { $tokens->insertAt($argStart, $tokensOverrideArgStart); } $tokens->overrideRange($argBefore, $argBefore, $tokensOverrideArgBefore); } $tokens[$index] = new Token([T_STRING, 'expectException']); } } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode("\n", $tokens[$index - 1]->getContent()); return end($explodedContent); } } assertSame(a(), b()); } } ' ), ] ); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); $prevIndex = $tokens->getPrevMeaningfulToken($classIndex); if ($tokens[$prevIndex]->isGivenKind(T_ABSTRACT)) { return; } $index = $tokens[$prevIndex]->isGivenKind(T_FINAL) ? $prevIndex : $classIndex; $indent = $tokens[$index - 1]->isGivenKind(T_WHITESPACE) ? Preg::replace('/^.*\R*/', '', $tokens[$index - 1]->getContent()) : ''; $prevIndex = $tokens->getPrevNonWhitespace($index); if ($tokens[$prevIndex]->isGivenKind(T_DOC_COMMENT)) { $docIndex = $prevIndex; $docContent = $tokens[$docIndex]->getContent(); if (false === strpos($docContent, "\n")) { return; } $doc = new DocBlock($docContent); if (!empty($doc->getAnnotationsOfType([ 'covers', 'coversDefaultClass', 'coversNothing', ]))) { return; } } else { $docIndex = $index; $tokens->insertAt($docIndex, [ new Token([T_DOC_COMMENT, sprintf('/**%s%s */', $this->whitespacesConfig->getLineEnding(), $indent)]), new Token([T_WHITESPACE, sprintf('%s%s', $this->whitespacesConfig->getLineEnding(), $indent)]), ]); if (!$tokens[$docIndex - 1]->isGivenKind(T_WHITESPACE)) { $extraNewLines = $this->whitespacesConfig->getLineEnding(); if (!$tokens[$docIndex - 1]->isGivenKind(T_OPEN_TAG)) { $extraNewLines .= $this->whitespacesConfig->getLineEnding(); } $tokens->insertAt($docIndex, [ new Token([T_WHITESPACE, $extraNewLines.$indent]), ]); ++$docIndex; } $doc = new DocBlock($tokens[$docIndex]->getContent()); } $lines = $doc->getLines(); array_splice( $lines, \count($lines) - 1, 0, [ new Line(sprintf( '%s * @coversNothing%s', $indent, $this->whitespacesConfig->getLineEnding() )), ] ); $tokens[$docIndex] = new Token([T_DOC_COMMENT, implode('', $lines)]); } } getPrevTokenOfKind($startIndex, [[T_DOC_COMMENT]]); if (null !== $prevDocCommentIndex) { $startIndex = $prevDocCommentIndex; } $this->fixPhpUnitClass($tokens, $startIndex, $endIndex); } private function fixPhpUnitClass(Tokens $tokens, $startIndex, $endIndex) { for ($index = $startIndex; $index < $endIndex; ++$index) { if ($tokens[$index]->isGivenKind(T_DOC_COMMENT)) { $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replace( '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(?!(?:self|static)::)(\w.*)$~m', '$1\\\\$2', $tokens[$index]->getContent() )]); } } } } ['assertArrayNotHasKey', 'assertArrayHasKey'], 'empty' => ['assertNotEmpty', 'assertEmpty'], 'file_exists' => ['assertFileNotExists', 'assertFileExists'], 'is_array' => true, 'is_bool' => true, 'is_callable' => true, 'is_dir' => ['assertDirectoryNotExists', 'assertDirectoryExists'], 'is_double' => true, 'is_float' => true, 'is_infinite' => ['assertFinite', 'assertInfinite'], 'is_int' => true, 'is_integer' => true, 'is_long' => true, 'is_nan' => [false, 'assertNan'], 'is_null' => ['assertNotNull', 'assertNull'], 'is_numeric' => true, 'is_object' => true, 'is_readable' => ['assertNotIsReadable', 'assertIsReadable'], 'is_real' => true, 'is_resource' => true, 'is_scalar' => true, 'is_string' => true, 'is_writable' => ['assertNotIsWritable', 'assertIsWritable'], ]; private $functions = []; public function configure(array $configuration = null) { parent::configure($configuration); if (isset($this->configuration['functions'])) { $this->functions = $this->configuration['functions']; return; } $this->functions = [ 'array_key_exists', 'file_exists', 'is_null', ]; if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_3_5)) { $this->functions = array_merge($this->functions, [ 'empty', 'is_array', 'is_bool', 'is_boolean', 'is_callable', 'is_double', 'is_float', 'is_int', 'is_integer', 'is_long', 'is_numeric', 'is_object', 'is_real', 'is_resource', 'is_scalar', 'is_string', ]); } if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_0)) { $this->functions = array_merge($this->functions, [ 'is_infinite', 'is_nan', ]); } if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { $this->functions = array_merge($this->functions, [ 'is_dir', 'is_readable', 'is_writable', ]); } } public function isRisky() { return true; } public function getDefinition() { return new FixerDefinition( 'PHPUnit assertions like `assertInternalType`, `assertFileExists`, should be used over `assertTrue`.', [ new CodeSample( 'assertTrue(is_float( $a), "my message"); $this->assertTrue(is_nan($a)); } } ' ), new CodeSample( 'assertTrue(is_dir($a)); $this->assertTrue(is_writable($a)); $this->assertTrue(is_readable($a)); } } ', ['target' => PhpUnitTargetVersion::VERSION_5_6] ), ], null, 'Fixer could be risky if one is overriding PHPUnit\'s native methods.' ); } public function getPriority() { return -15; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) { if ('asserttrue' === $assertCall['loweredName'] || 'assertfalse' === $assertCall['loweredName']) { $this->fixAssertTrueFalse($tokens, $assertCall); continue; } if ( 'assertsame' === $assertCall['loweredName'] || 'assertnotsame' === $assertCall['loweredName'] || 'assertequals' === $assertCall['loweredName'] || 'assertnotequals' === $assertCall['loweredName'] ) { $this->fixAssertSameEquals($tokens, $assertCall); continue; } } } protected function createConfigurationDefinition() { $values = [ 'array_key_exists', 'empty', 'file_exists', 'is_array', 'is_bool', 'is_callable', 'is_double', 'is_float', 'is_infinite', 'is_int', 'is_integer', 'is_long', 'is_nan', 'is_null', 'is_numeric', 'is_object', 'is_real', 'is_resource', 'is_scalar', 'is_string', ]; sort($values); return new FixerConfigurationResolverRootless('functions', [ (new FixerOptionBuilder('functions', 'List of assertions to fix (overrides `target`).')) ->setAllowedTypes(['null', 'array']) ->setAllowedValues([ null, new AllowedValueSubset($values), ]) ->setDefault(null) ->setDeprecationMessage('Use option `target` instead.') ->getOption(), (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) ->setAllowedTypes(['string']) ->setAllowedValues([ PhpUnitTargetVersion::VERSION_3_0, PhpUnitTargetVersion::VERSION_3_5, PhpUnitTargetVersion::VERSION_5_0, PhpUnitTargetVersion::VERSION_5_6, PhpUnitTargetVersion::VERSION_NEWEST, ]) ->setDefault(PhpUnitTargetVersion::VERSION_5_0) ->getOption(), ], $this->getName()); } private function fixAssertTrueFalse(Tokens $tokens, array $assertCall) { $testDefaultNamespaceTokenIndex = false; $testIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); if (!$tokens[$testIndex]->isGivenKind([T_EMPTY, T_STRING])) { if (!$tokens[$testIndex]->isGivenKind(T_NS_SEPARATOR)) { return; } $testDefaultNamespaceTokenIndex = $testIndex; $testIndex = $tokens->getNextMeaningfulToken($testIndex); } $testOpenIndex = $tokens->getNextMeaningfulToken($testIndex); if (!$tokens[$testOpenIndex]->equals('(')) { return; } $testCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $testOpenIndex); $assertCallCloseIndex = $tokens->getNextMeaningfulToken($testCloseIndex); if (!$tokens[$assertCallCloseIndex]->equalsAny([')', ','])) { return; } $isPositive = 'asserttrue' === $assertCall['loweredName']; $content = strtolower($tokens[$testIndex]->getContent()); if (!\in_array($content, $this->functions, true)) { return; } if (\is_array(self::$fixMap[$content])) { if (false !== self::$fixMap[$content][$isPositive]) { $tokens[$assertCall['index']] = new Token([T_STRING, self::$fixMap[$content][$isPositive]]); $this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex); } return; } $type = substr($content, 3); $tokens[$assertCall['index']] = new Token([T_STRING, $isPositive ? 'assertInternalType' : 'assertNotInternalType']); $tokens[$testIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, "'".$type."'"]); $tokens[$testOpenIndex] = new Token(','); $tokens->clearTokenAndMergeSurroundingWhitespace($testCloseIndex); $commaIndex = $tokens->getPrevMeaningfulToken($testCloseIndex); if ($tokens[$commaIndex]->equals(',')) { $tokens->removeTrailingWhitespace($commaIndex); $tokens->clearAt($commaIndex); } if (!$tokens[$testOpenIndex + 1]->isWhitespace()) { $tokens->insertAt($testOpenIndex + 1, new Token([T_WHITESPACE, ' '])); } if (false !== $testDefaultNamespaceTokenIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex); } } private function fixAssertSameEquals(Tokens $tokens, array $assertCall) { $expectedIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); if (!$tokens[$expectedIndex]->isGivenKind(T_LNUMBER)) { return; } $commaIndex = $tokens->getNextMeaningfulToken($expectedIndex); if (!$tokens[$commaIndex]->equals(',')) { return; } $countCallIndex = $tokens->getNextMeaningfulToken($commaIndex); if ($tokens[$countCallIndex]->isGivenKind(T_NS_SEPARATOR)) { $defaultNamespaceTokenIndex = $countCallIndex; $countCallIndex = $tokens->getNextMeaningfulToken($countCallIndex); } else { $defaultNamespaceTokenIndex = false; } if (!$tokens[$countCallIndex]->isGivenKind(T_STRING)) { return; } $lowerContent = strtolower($tokens[$countCallIndex]->getContent()); if ('count' !== $lowerContent && 'sizeof' !== $lowerContent) { return; } $countCallOpenBraceIndex = $tokens->getNextMeaningfulToken($countCallIndex); if (!$tokens[$countCallOpenBraceIndex]->equals('(')) { return; } $countCallCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $countCallOpenBraceIndex); $afterCountCallCloseBraceIndex = $tokens->getNextMeaningfulToken($countCallCloseBraceIndex); if (!$tokens[$afterCountCallCloseBraceIndex]->equalsAny([')', ','])) { return; } $this->removeFunctionCall( $tokens, $defaultNamespaceTokenIndex, $countCallIndex, $countCallOpenBraceIndex, $countCallCloseBraceIndex ); $tokens[$assertCall['index']] = new Token([ T_STRING, false === strpos($assertCall['loweredName'], 'not', 6) ? 'assertCount' : 'assertNotCount', ]); } private function getPreviousAssertCall(Tokens $tokens, $startIndex, $endIndex) { $functionsAnalyzer = new FunctionsAnalyzer(); for ($index = $endIndex; $index > $startIndex; --$index) { $index = $tokens->getPrevTokenOfKind($index, [[T_STRING]]); if (null === $index) { return; } $loweredContent = strtolower($tokens[$index]->getContent()); if ('assert' !== substr($loweredContent, 0, 6)) { continue; } $openBraceIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$openBraceIndex]->equals('(')) { continue; } if (!$functionsAnalyzer->isTheSameClassCall($tokens, $index)) { continue; } yield [ 'index' => $index, 'loweredName' => $loweredContent, 'openBraceIndex' => $openBraceIndex, 'closeBraceIndex' => $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex), ]; } } private function removeFunctionCall(Tokens $tokens, $callNSIndex, $callIndex, $openIndex, $closeIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); if (false !== $callNSIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); if ($tokens[$commaIndex]->equals(',')) { $tokens->removeTrailingWhitespace($commaIndex); $tokens->clearAt($commaIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); } } 'assertAttributeSame', 'assertAttributeNotEquals' => 'assertAttributeNotSame', 'assertEquals' => 'assertSame', 'assertNotEquals' => 'assertNotSame', ]; public function getDefinition() { return new FixerDefinition( 'PHPUnit methods like `assertSame` should be used instead of `assertEquals`.', [ new CodeSample( 'assertAttributeEquals(a(), b()); $this->assertAttributeNotEquals(a(), b()); $this->assertEquals(a(), b()); $this->assertNotEquals(a(), b()); } } ' ), new CodeSample( 'assertAttributeEquals(a(), b()); $this->assertAttributeNotEquals(a(), b()); $this->assertEquals(a(), b()); $this->assertNotEquals(a(), b()); } } ', ['assertions' => ['assertEquals']] ), ], null, 'Risky when any of the functions are overridden or when testing object equality.' ); } public function isRisky() { return true; } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $argumentsAnalyzer = new ArgumentsAnalyzer(); $functionsAnalyzer = new FunctionsAnalyzer(); foreach ($this->configuration['assertions'] as $methodBefore) { $methodAfter = self::$assertionMap[$methodBefore]; for ($index = $startIndex; $index < $endIndex; ++$index) { $methodIndex = $tokens->getNextTokenOfKind($index, [[T_STRING, $methodBefore]]); if (null === $methodIndex) { break; } if (!$functionsAnalyzer->isTheSameClassCall($tokens, $methodIndex)) { continue; } $openingParenthesisIndex = $tokens->getNextMeaningfulToken($methodIndex); $argumentsCount = $argumentsAnalyzer->countArguments( $tokens, $openingParenthesisIndex, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex) ); if (2 === $argumentsCount || 3 === $argumentsCount) { $tokens[$methodIndex] = new Token([T_STRING, $methodAfter]); } $index = $methodIndex; } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('assertions', [ (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(array_keys(self::$assertionMap))]) ->setDefault([ 'assertAttributeEquals', 'assertAttributeNotEquals', 'assertEquals', 'assertNotEquals', ]) ->getOption(), ], $this->getName()); } } ['final']] ), ] ); } public function getPriority() { return 68; } protected function createConfigurationDefinition() { $types = ['normal', 'final', 'abstract']; return new FixerConfigurationResolver([ (new FixerOptionBuilder('types', 'What types of classes to mark as internal')) ->setAllowedValues([(new AllowedValueSubset($types))]) ->setAllowedTypes(['array']) ->setDefault(['normal', 'final']) ->getOption(), ]); } protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex) { $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); if (!$this->isAllowedByConfiguration($tokens, $classIndex)) { return; } $docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex); if ($this->isPHPDoc($tokens, $docBlockIndex)) { $this->updateDocBlockIfNeeded($tokens, $docBlockIndex); } else { $this->createDocBlock($tokens, $docBlockIndex); } } private function isAllowedByConfiguration(Tokens $tokens, $i) { $typeIndex = $tokens->getPrevMeaningfulToken($i); if ($tokens[$typeIndex]->isGivenKind(T_FINAL)) { return \in_array('final', $this->configuration['types'], true); } if ($tokens[$typeIndex]->isGivenKind(T_ABSTRACT)) { return \in_array('abstract', $this->configuration['types'], true); } return \in_array('normal', $this->configuration['types'], true); } private function createDocBlock(Tokens $tokens, $docBlockIndex) { $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $toInsert = [ new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @internal".$lineEnd."{$originalIndent} */"]), new Token([T_WHITESPACE, $lineEnd.$originalIndent]), ]; $index = $tokens->getNextMeaningfulToken($docBlockIndex); $tokens->insertAt($index, $toInsert); } private function updateDocBlockIfNeeded(Tokens $tokens, $docBlockIndex) { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); if (!empty($doc->getAnnotationsOfType('internal'))) { return; } $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex); $lines = $this->addInternalAnnotation($doc, $tokens, $docBlockIndex); $lines = implode('', $lines); $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode($this->whitespacesConfig->getLineEnding(), $tokens[$index - 1]->getContent()); return end($explodedContent); } private function addInternalAnnotation(DocBlock $docBlock, Tokens $tokens, $docBlockIndex) { $lines = $docBlock->getLines(); $originalIndent = $this->detectIndent($tokens, $docBlockIndex); $lineEnd = $this->whitespacesConfig->getLineEnding(); array_splice($lines, -1, 0, $originalIndent.' *'.$lineEnd.$originalIndent.' * @internal'.$lineEnd); return $lines; } private function makeDocBlockMultiLineIfNeeded(DocBlock $doc, Tokens $tokens, $docBlockIndex) { $lines = $doc->getLines(); if (1 === \count($lines) && empty($doc->getAnnotationsOfType('internal'))) { $indent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding()); return $doc; } return $doc; } } callback = 'none' === $this->configuration['space'] ? 'removeWhitespaceAroundToken' : 'ensureWhitespaceAroundToken'; } public function getDefinition() { return new FixerDefinition( 'Equal sign in declare statement should be surrounded by spaces or not following configuration.', [ new CodeSample(" 'single']), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DECLARE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $callback = $this->callback; for ($index = 0, $count = $tokens->count(); $index < $count - 6; ++$index) { if (!$tokens[$index]->isGivenKind(T_DECLARE)) { continue; } while (!$tokens[++$index]->equals('=')); $this->{$callback}($tokens, $index); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('space', 'Spacing to apply around the equal sign.')) ->setAllowedValues(['single', 'none']) ->setDefault('none') ->getOption(), ]); } private function ensureWhitespaceAroundToken(Tokens $tokens, $index) { if ($tokens[$index + 1]->isWhitespace()) { if (' ' !== $tokens[$index + 1]->getContent()) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } } else { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } if ($tokens[$index - 1]->isWhitespace()) { if (' ' !== $tokens[$index - 1]->getContent() && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); } } else { $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); } } private function removeWhitespaceAroundToken(Tokens $tokens, $index) { if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { $tokens->removeLeadingWhitespace($index); } $tokens->removeTrailingWhitespace($index); } } isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $sequenceNeeded = [[T_STRING, 'is_null'], '(']; $functionsAnalyzer = new FunctionsAnalyzer(); $currIndex = 0; while (null !== $currIndex) { $matches = $tokens->findSequence($sequenceNeeded, $currIndex, $tokens->count() - 1, false); if (null === $matches) { break; } $matches = array_keys($matches); list($isNullIndex, $currIndex) = $matches; if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $matches[0])) { continue; } $next = $tokens->getNextMeaningfulToken($currIndex); if ($tokens[$next]->equals(')')) { continue; } $prevTokenIndex = $tokens->getPrevMeaningfulToken($matches[0]); if ($tokens[$prevTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { $tokens->removeTrailingWhitespace($prevTokenIndex); $tokens->clearAt($prevTokenIndex); $prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); } $isInvertedNullCheck = false; if ($tokens[$prevTokenIndex]->equals('!')) { $isInvertedNullCheck = true; $tokens->removeTrailingWhitespace($prevTokenIndex); $tokens->clearAt($prevTokenIndex); } $referenceEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $matches[1]); $isContainingDangerousConstructs = false; for ($paramTokenIndex = $matches[1]; $paramTokenIndex <= $referenceEnd; ++$paramTokenIndex) { if (\in_array($tokens[$paramTokenIndex]->getContent(), ['?', '?:', '=', '??'], true)) { $isContainingDangerousConstructs = true; break; } } $parentLeftToken = $tokens[$tokens->getPrevMeaningfulToken($isNullIndex)]; $parentRightToken = $tokens[$tokens->getNextMeaningfulToken($referenceEnd)]; $parentOperations = [T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL]; $wrapIntoParentheses = $parentLeftToken->isGivenKind($parentOperations) || $parentRightToken->isGivenKind($parentOperations); $prevIndex = $tokens->getPrevMeaningfulToken($referenceEnd); if ($tokens[$prevIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } if (!$isContainingDangerousConstructs) { $tokens->removeLeadingWhitespace($referenceEnd); $tokens->clearAt($referenceEnd); $tokens->removeLeadingWhitespace($matches[1]); $tokens->removeTrailingWhitespace($matches[1]); $tokens->clearAt($matches[1]); } $replacement = [ new Token([T_STRING, 'null']), new Token([T_WHITESPACE, ' ']), new Token($isInvertedNullCheck ? [T_IS_NOT_IDENTICAL, '!=='] : [T_IS_IDENTICAL, '===']), new Token([T_WHITESPACE, ' ']), ]; if (true === $this->configuration['use_yoda_style']) { if ($wrapIntoParentheses) { array_unshift($replacement, new Token('(')); $tokens->insertAt($referenceEnd + 1, new Token(')')); } $tokens->overrideRange($isNullIndex, $isNullIndex, $replacement); } else { $replacement = array_reverse($replacement); if ($wrapIntoParentheses) { $replacement[] = new Token(')'); $tokens[$isNullIndex] = new Token('('); } else { $tokens->clearAt($isNullIndex); } $tokens->insertAt($referenceEnd + 1, $replacement); } $currIndex = $isNullIndex; } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use_yoda_style', 'Whether Yoda style conditions should be used.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->setDeprecationMessage('Use `yoda_style` fixer instead.') ->getOption(), ]); } } isTokenKindFound(CT::T_CLASS_CONSTANT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $namespacesAnalyzer = new NamespacesAnalyzer(); $previousNamespaceScopeEndIndex = 0; foreach ($namespacesAnalyzer->getDeclarations($tokens) as $declaration) { $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $declaration->getStartIndex()); $this->replaceClassKeywordsSection($tokens, $declaration->getFullName(), $declaration->getStartIndex(), $declaration->getScopeEndIndex()); $previousNamespaceScopeEndIndex = $declaration->getScopeEndIndex(); } $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $tokens->count() - 1); } private function storeImports(Tokens $tokens, $startIndex, $endIndex) { $tokensAnalyzer = new TokensAnalyzer($tokens); $this->imports = []; foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { if ($index < $startIndex || $index > $endIndex) { continue; } $import = ''; while ($index = $tokens->getNextMeaningfulToken($index)) { if ($tokens[$index]->equalsAny([';', [CT::T_GROUP_IMPORT_BRACE_OPEN]]) || $tokens[$index]->isGivenKind(T_AS)) { break; } $import .= $tokens[$index]->getContent(); } if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { $groupEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $index); $groupImports = array_map( static function ($import) { return trim($import); }, explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1)) ); foreach ($groupImports as $groupImport) { $groupImportParts = array_map(static function ($import) { return trim($import); }, explode(' as ', $groupImport)); if (2 === \count($groupImportParts)) { $this->imports[$groupImportParts[1]] = $import.$groupImportParts[0]; } else { $this->imports[] = $import.$groupImport; } } } elseif ($tokens[$index]->isGivenKind(T_AS)) { $aliasIndex = $tokens->getNextMeaningfulToken($index); $alias = $tokens[$aliasIndex]->getContent(); $this->imports[$alias] = $import; } else { $this->imports[] = $import; } } } private function replaceClassKeywordsSection(Tokens $tokens, $namespace, $startIndex, $endIndex) { if ($endIndex - $startIndex < 3) { return; } $this->storeImports($tokens, $startIndex, $endIndex); $ctClassTokens = $tokens->findGivenKind(CT::T_CLASS_CONSTANT, $startIndex, $endIndex); foreach (array_reverse(array_keys($ctClassTokens)) as $classIndex) { $this->replaceClassKeyword($tokens, $namespace, $classIndex); } } private function replaceClassKeyword(Tokens $tokens, $namespacePrefix, $classIndex) { $classEndIndex = $tokens->getPrevMeaningfulToken($classIndex); $classEndIndex = $tokens->getPrevMeaningfulToken($classEndIndex); if (!$tokens[$classEndIndex]->isGivenKind(T_STRING)) { return; } if ($tokens[$classEndIndex]->equalsAny([[T_STRING, 'self'], [T_STATIC, 'static'], [T_STRING, 'parent']], false)) { return; } $classBeginIndex = $classEndIndex; while (true) { $prev = $tokens->getPrevMeaningfulToken($classBeginIndex); if (!$tokens[$prev]->isGivenKind([T_NS_SEPARATOR, T_STRING])) { break; } $classBeginIndex = $prev; } $classString = $tokens->generatePartialCode( $tokens[$classBeginIndex]->isGivenKind(T_NS_SEPARATOR) ? $tokens->getNextMeaningfulToken($classBeginIndex) : $classBeginIndex, $classEndIndex ); $classImport = false; if ($tokens[$classBeginIndex]->isGivenKind(T_NS_SEPARATOR)) { $namespacePrefix = ''; } else { foreach ($this->imports as $alias => $import) { if ($classString === $alias) { $classImport = $import; break; } $classStringArray = explode('\\', $classString); $namespaceToTest = $classStringArray[0]; if (0 === strcmp($namespaceToTest, substr($import, -\strlen($namespaceToTest)))) { $classImport = $import; break; } } } for ($i = $classBeginIndex; $i <= $classIndex; ++$i) { if (!$tokens[$i]->isComment() && !($tokens[$i]->isWhitespace() && false !== strpos($tokens[$i]->getContent(), "\n"))) { $tokens->clearAt($i); } } $tokens->insertAt($classBeginIndex, new Token([ T_CONSTANT_ENCAPSED_STRING, "'".$this->makeClassFQN($namespacePrefix, $classImport, $classString)."'", ])); } private function makeClassFQN($namespacePrefix, $classImport, $classString) { if (false === $classImport) { return ('' !== $namespacePrefix ? ($namespacePrefix.'\\') : '').$classString; } $classStringArray = explode('\\', $classString); $classStringLength = \count($classStringArray); $classImportArray = explode('\\', $classImport); $classImportLength = \count($classImportArray); if (1 === $classStringLength) { return $classImport; } return implode('\\', array_merge( \array_slice($classImportArray, 0, $classImportLength - $classStringLength + 1), $classStringArray )); } } a);\n")], null, 'Risky when relying on attributes to be removed using `unset` rather than be set to `null`.'. ' Changing variables to `null` instead of unsetting means these still show up when looping over class variables'. ' and reference properties remain unbroken.'. ' With PHP 7.4, this rule might introduce `null` assignments to properties whose type declaration does not allow it.' ); } public function isRisky() { return true; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_UNSET) && $tokens->isAnyTokenKindsFound([T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM]); } public function getPriority() { return 25; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if (!$tokens[$index]->isGivenKind(T_UNSET)) { continue; } $unsetsInfo = $this->getUnsetsInfo($tokens, $index); if (!$this->isAnyUnsetToTransform($unsetsInfo)) { continue; } $isLastUnset = true; foreach (array_reverse($unsetsInfo) as $unsetInfo) { $this->updateTokens($tokens, $unsetInfo, $isLastUnset); $isLastUnset = false; } } } private function getUnsetsInfo(Tokens $tokens, $index) { $argumentsAnalyzer = new ArgumentsAnalyzer(); $unsetStart = $tokens->getNextTokenOfKind($index, ['(']); $unsetEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $unsetStart); $isFirst = true; $unsets = []; foreach ($argumentsAnalyzer->getArguments($tokens, $unsetStart, $unsetEnd) as $startIndex => $endIndex) { $startIndex = $tokens->getNextMeaningfulToken($startIndex - 1); $endIndex = $tokens->getPrevMeaningfulToken($endIndex + 1); $unsets[] = [ 'startIndex' => $startIndex, 'endIndex' => $endIndex, 'isToTransform' => $this->isProperty($tokens, $startIndex, $endIndex), 'isFirst' => $isFirst, ]; $isFirst = false; } return $unsets; } private function isProperty(Tokens $tokens, $index, $endIndex) { if ($tokens[$index]->isGivenKind(T_VARIABLE)) { $nextIndex = $tokens->getNextMeaningfulToken($index); if (null === $nextIndex || !$tokens[$nextIndex]->isGivenKind(T_OBJECT_OPERATOR)) { return false; } $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { return false; } return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_STRING); } if ($tokens[$index]->isGivenKind([T_NS_SEPARATOR, T_STRING])) { $nextIndex = $tokens->getTokenNotOfKindsSibling($index, 1, [T_DOUBLE_COLON, T_NS_SEPARATOR, T_STRING]); $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { return false; } return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_VARIABLE); } return false; } private function isAnyUnsetToTransform(array $unsetsInfo) { foreach ($unsetsInfo as $unsetInfo) { if ($unsetInfo['isToTransform']) { return true; } } return false; } private function updateTokens(Tokens $tokens, array $unsetInfo, $isLastUnset) { if ($unsetInfo['isFirst'] && $unsetInfo['isToTransform']) { $braceIndex = $tokens->getPrevTokenOfKind($unsetInfo['startIndex'], ['(']); $unsetIndex = $tokens->getPrevTokenOfKind($braceIndex, [[T_UNSET]]); $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($unsetIndex); } if ($isLastUnset && $unsetInfo['isToTransform']) { $braceIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [')']); $previousIndex = $tokens->getPrevMeaningfulToken($braceIndex); if ($tokens[$previousIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($previousIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); } if (!$isLastUnset) { $commaIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [',']); $tokens[$commaIndex] = new Token(';'); } if (!$unsetInfo['isToTransform'] && !$isLastUnset) { $tokens->insertAt($unsetInfo['endIndex'] + 1, new Token(')')); } if (!$unsetInfo['isToTransform'] && !$unsetInfo['isFirst']) { $tokens->insertAt( $unsetInfo['startIndex'], [ new Token([T_UNSET, 'unset']), new Token('('), ] ); } if ($unsetInfo['isToTransform']) { $tokens->insertAt( $unsetInfo['endIndex'] + 1, [ new Token([T_WHITESPACE, ' ']), new Token('='), new Token([T_WHITESPACE, ' ']), new Token([T_STRING, 'null']), ] ); } } } = 7.0.', [ new VersionSpecificCodeSample( <<<'EOT' $bar['baz']; echo $foo->$callback($baz); EOT , new VersionSpecification(70000) ), ] ); } public function isCandidate(Tokens $tokens) { return \PHP_VERSION_ID >= 70000 && $tokens->isTokenKindFound(T_VARIABLE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index > 1; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_VARIABLE)) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if (!$prevToken->equals('$') && !$prevToken->isGivenKind(T_OBJECT_OPERATOR)) { continue; } $openingBrace = CT::T_DYNAMIC_VAR_BRACE_OPEN; $closingBrace = CT::T_DYNAMIC_VAR_BRACE_CLOSE; if ($prevToken->isGivenKind(T_OBJECT_OPERATOR)) { $openingBrace = CT::T_DYNAMIC_PROP_BRACE_OPEN; $closingBrace = CT::T_DYNAMIC_PROP_BRACE_CLOSE; } $tokens->overrideRange($index, $index, [ new Token([$openingBrace, '{']), new Token([T_VARIABLE, $token->getContent()]), new Token([$closingBrace, '}']), ]); } } } true] ), new CodeSample( " true, self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE => ['unlink'], ] ), ], null, 'Risky because adding/removing `@` might cause changes to code behaviour or if `trigger_error` function is overridden.' ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(['@', T_STRING]); } public function isRisky() { return true; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder(self::OPTION_MUTE_DEPRECATION_ERROR, 'Whether to add `@` in deprecation notices.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES, 'Whether to remove `@` in remaining usages.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE, 'List of global functions to exclude from removing `@`')) ->setAllowedTypes(['array']) ->setDefault([]) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionsAnalyzer = new FunctionsAnalyzer(); $excludedFunctions = array_map(static function ($function) { return strtolower($function); }, $this->configuration[self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE]); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ($this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && $token->equals('@')) { $tokens->clearAt($index); continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $functionIndex = $index; $startIndex = $index; $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { $startIndex = $prevIndex; $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); } $index = $prevIndex; if ($this->isDeprecationErrorCall($tokens, $functionIndex)) { if (!$this->configuration[self::OPTION_MUTE_DEPRECATION_ERROR]) { continue; } if ($tokens[$prevIndex]->equals('@')) { continue; } $tokens->insertAt($startIndex, new Token('@')); continue; } if (!$tokens[$prevIndex]->equals('@')) { continue; } if ($this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && !\in_array($tokens[$functionIndex]->getContent(), $excludedFunctions, true)) { $tokens->clearAt($index); } } } private function isDeprecationErrorCall(Tokens $tokens, $index) { if ('trigger_error' !== strtolower($tokens[$index]->getContent())) { return false; } $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, [T_STRING, '('])); $prevIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); if ($tokens[$prevIndex]->equals(',')) { $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); } return $tokens[$prevIndex]->equals([T_STRING, 'E_USER_DEPRECATED']); } } [ new Token([T_STATIC, 'static']), new Token([T_DOUBLE_COLON, '::']), new Token([CT::T_CLASS_CONSTANT, 'class']), ], 'get_class' => [new Token([T_CLASS_C, '__CLASS__'])], 'get_class_this' => [ new Token([T_STATIC, 'static']), new Token([T_DOUBLE_COLON, '::']), new Token([CT::T_CLASS_CONSTANT, 'class']), ], 'php_sapi_name' => [new Token([T_STRING, 'PHP_SAPI'])], 'phpversion' => [new Token([T_STRING, 'PHP_VERSION'])], 'pi' => [new Token([T_STRING, 'M_PI'])], ]; } parent::__construct(); } public function configure(array $configuration = null) { parent::configure($configuration); $this->functionsFixMap = []; foreach ($this->configuration['functions'] as $key) { $this->functionsFixMap[$key] = self::$availableFunctions[$key]; } } public function getDefinition() { return new FixerDefinition( 'Replace core functions calls returning constants with the constants.', [ new CodeSample( " ['get_called_class', 'get_class_this', 'phpversion']] ), ], null, 'Risky when any of the configured functions to replace are overridden.' ); } public function getPriority() { return 1; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionAnalyzer = new FunctionsAnalyzer(); for ($index = $tokens->count() - 4; $index > 0; --$index) { $candidate = $this->getReplaceCandidate($tokens, $functionAnalyzer, $index); if (null === $candidate) { continue; } $this->fixFunctionCallToConstant( $tokens, $index, $candidate[0], $candidate[1], $candidate[2] ); } } protected function createConfigurationDefinition() { $functionNames = array_keys(self::$availableFunctions); return new FixerConfigurationResolver([ (new FixerOptionBuilder('functions', 'List of function names to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($functionNames)]) ->setDefault([ 'get_class', 'php_sapi_name', 'phpversion', 'pi', ]) ->getOption(), ]); } private function fixFunctionCallToConstant(Tokens $tokens, $index, $braceOpenIndex, $braceCloseIndex, array $replacements) { for ($i = $braceCloseIndex; $i >= $braceOpenIndex; --$i) { if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { continue; } $tokens->clearTokenAndMergeSurroundingWhitespace($i); } if ($replacements[0]->isGivenKind([T_CLASS_C, T_STATIC])) { $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->isGivenKind(T_NS_SEPARATOR)) { $tokens->clearAt($prevIndex); } } $tokens->clearAt($index); $tokens->insertAt($index, $replacements); } private function getReplaceCandidate( Tokens $tokens, FunctionsAnalyzer $functionAnalyzer, $index ) { if (!$tokens[$index]->isGivenKind(T_STRING)) { return null; } $lowerContent = strtolower($tokens[$index]->getContent()); if ('get_class' === $lowerContent) { return $this->fixGetClassCall($tokens, $functionAnalyzer, $index); } if (!isset($this->functionsFixMap[$lowerContent])) { return null; } if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { return null; } $braceOpenIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$braceOpenIndex]->equals('(')) { return null; } $braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex); if (!$tokens[$braceCloseIndex]->equals(')')) { return null; } return $this->getReplacementTokenClones($lowerContent, $braceOpenIndex, $braceCloseIndex); } private function fixGetClassCall( Tokens $tokens, FunctionsAnalyzer $functionAnalyzer, $index ) { if (!isset($this->functionsFixMap['get_class']) && !isset($this->functionsFixMap['get_class_this'])) { return null; } if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { return null; } $braceOpenIndex = $tokens->getNextMeaningfulToken($index); $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { if (isset($this->functionsFixMap['get_class'])) { return $this->getReplacementTokenClones('get_class', $braceOpenIndex, $braceCloseIndex); } } elseif (isset($this->functionsFixMap['get_class_this'])) { $isThis = false; for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { if ($tokens[$i]->equalsAny([[T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT], ')'])) { continue; } if ($tokens[$i]->isGivenKind(T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { $isThis = true; continue; } if (false === $isThis && $tokens[$i]->equals('(')) { continue; } $isThis = false; break; } if ($isThis) { return $this->getReplacementTokenClones('get_class_this', $braceOpenIndex, $braceCloseIndex); } } return null; } private function getReplacementTokenClones($lowerContent, $braceOpenIndex, $braceCloseIndex) { $clones = []; foreach ($this->functionsFixMap[$lowerContent] as $token) { $clones[] = clone $token; } return [ $braceOpenIndex, $braceCloseIndex, $clones, ]; } } proxyFixers); } protected function createProxyFixers() { return [new ErrorSuppressionFixer()]; } } isAllTokenKindsFound([T_ISSET, T_BOOLEAN_AND]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokenCount = $tokens->count(); for ($index = 1; $index < $tokenCount; ++$index) { if (!$tokens[$index]->isGivenKind(T_ISSET) || !$tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['(', '{', ';', '=', [T_OPEN_TAG], [T_BOOLEAN_AND], [T_BOOLEAN_OR]])) { continue; } $issetInfo = $this->getIssetInfo($tokens, $index); $issetCloseBraceIndex = end($issetInfo); $insertLocation = prev($issetInfo) + 1; $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); while ($tokens[$booleanAndTokenIndex]->isGivenKind(T_BOOLEAN_AND)) { $issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex); if (!$tokens[$issetIndex]->isGivenKind(T_ISSET)) { $index = $issetIndex; break; } $nextIssetInfo = $this->getIssetInfo($tokens, $issetIndex); $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken(end($nextIssetInfo)); $nextMeaningfulToken = $tokens[$nextMeaningfulTokenIndex]; if (!$nextMeaningfulToken->equalsAny([')', '}', ';', [T_CLOSE_TAG], [T_BOOLEAN_AND], [T_BOOLEAN_OR]])) { $index = $nextMeaningfulTokenIndex; break; } $clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1)); $this->clearTokens($tokens, array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex])); array_unshift($clones, new Token(','), new Token([T_WHITESPACE, ' '])); $tokens->insertAt($insertLocation, $clones); $numberOfTokensInserted = \count($clones); $tokenCount += $numberOfTokensInserted; $issetCloseBraceIndex += $numberOfTokensInserted; $insertLocation += $numberOfTokensInserted; $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); } } } private function clearTokens(Tokens $tokens, array $indexes) { foreach ($indexes as $index) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } private function getIssetInfo(Tokens $tokens, $index) { $openIndex = $tokens->getNextMeaningfulToken($index); $braceOpenCount = 1; $meaningfulTokenIndexes = [$openIndex]; for ($i = $openIndex + 1;; ++$i) { if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { continue; } $meaningfulTokenIndexes[] = $i; if ($tokens[$i]->equals(')')) { --$braceOpenCount; if (0 === $braceOpenCount) { break; } } elseif ($tokens[$i]->equals('(')) { ++$braceOpenCount; } } return $meaningfulTokenIndexes; } private function getTokenClones(Tokens $tokens, array $indexes) { $clones = []; foreach ($indexes as $i) { $clones[] = clone $tokens[$i]; } return $clones; } } isTokenKindFound(T_UNSET); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if (!$tokens[$index]->isGivenKind(T_UNSET)) { continue; } $previousUnsetCall = $this->getPreviousUnsetCall($tokens, $index); if (\is_int($previousUnsetCall)) { $index = $previousUnsetCall; continue; } list($previousUnset, , $previousUnsetBraceEnd) = $previousUnsetCall; $tokensAddCount = $this->moveTokens( $tokens, $nextUnsetContentStart = $tokens->getNextTokenOfKind($index, ['(']), $nextUnsetContentEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextUnsetContentStart), $previousUnsetBraceEnd - 1 ); if (!$tokens[$previousUnsetBraceEnd]->isWhitespace()) { $tokens->insertAt($previousUnsetBraceEnd, new Token([T_WHITESPACE, ' '])); ++$tokensAddCount; } $tokens->insertAt($previousUnsetBraceEnd, new Token(',')); ++$tokensAddCount; $this->clearOffsetTokens($tokens, $tokensAddCount, [$index, $nextUnsetContentStart, $nextUnsetContentEnd]); $nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd); if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) { $tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon); } $index = $previousUnset + 1; } } private function clearOffsetTokens(Tokens $tokens, $offset, array $indices) { foreach ($indices as $index) { $tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset); } } private function getPreviousUnsetCall(Tokens $tokens, $index) { $previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index); if (null === $previousUnsetSemicolon) { return $index; } if (!$tokens[$previousUnsetSemicolon]->equals(';')) { return $previousUnsetSemicolon; } $previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon); if (null === $previousUnsetBraceEnd) { return $index; } if (!$tokens[$previousUnsetBraceEnd]->equals(')')) { return $previousUnsetBraceEnd; } $previousUnsetBraceStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $previousUnsetBraceEnd); $previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart); if (null === $previousUnset) { return $index; } if (!$tokens[$previousUnset]->isGivenKind(T_UNSET)) { return $previousUnset; } return [ $previousUnset, $previousUnsetBraceStart, $previousUnsetBraceEnd, $previousUnsetSemicolon, ]; } private function moveTokens(Tokens $tokens, $start, $end, $to) { $added = 0; for ($i = $start + 1; $i < $end; $i += 2) { if ($tokens[$i]->isWhitespace() && $tokens[$to + 1]->isWhitespace()) { $tokens[$to + 1] = new Token([T_WHITESPACE, $tokens[$to + 1]->getContent().$tokens[$i]->getContent()]); } else { $tokens->insertAt(++$to, clone $tokens[$i]); ++$end; ++$added; } $tokens->clearAt($i + 1); } return $added; } } isTokenKindFound(T_FILE); } public function getPriority() { return 4; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $currIndex = 0; while (null !== $currIndex) { $boundaries = $this->find('dirname', $tokens, $currIndex, $tokens->count() - 1); if (null === $boundaries) { return; } list($functionNameIndex, $openParenthesis, $closeParenthesis) = $boundaries; $currIndex = $openParenthesis; $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($closeParenthesis); $trailingCommaIndex = null; if ($tokens[$fileCandidateRightIndex]->equals(',')) { $trailingCommaIndex = $fileCandidateRightIndex; $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($fileCandidateRightIndex); } $fileCandidateRight = $tokens[$fileCandidateRightIndex]; if (!$fileCandidateRight->isGivenKind(T_FILE)) { continue; } $fileCandidateLeftIndex = $tokens->getNextMeaningfulToken($openParenthesis); $fileCandidateLeft = $tokens[$fileCandidateLeftIndex]; if (!$fileCandidateLeft->isGivenKind(T_FILE)) { continue; } $namespaceCandidateIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); $namespaceCandidate = $tokens[$namespaceCandidateIndex]; if ($namespaceCandidate->isGivenKind(T_NS_SEPARATOR)) { $tokens->removeTrailingWhitespace($namespaceCandidateIndex); $tokens->clearAt($namespaceCandidateIndex); } if (null !== $trailingCommaIndex) { if (!$tokens[$tokens->getNextNonWhitespace($trailingCommaIndex)]->isComment()) { $tokens->removeTrailingWhitespace($trailingCommaIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($trailingCommaIndex); } if (!$tokens[$tokens->getNextNonWhitespace($closeParenthesis)]->isComment()) { $tokens->removeLeadingWhitespace($closeParenthesis); } $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesis); if (!$tokens[$tokens->getNextNonWhitespace($openParenthesis)]->isComment()) { $tokens->removeLeadingWhitespace($openParenthesis); } $tokens->removeTrailingWhitespace($openParenthesis); $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesis); $tokens[$fileCandidateLeftIndex] = new Token([T_DIR, '__DIR__']); $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); } } } $token) { if ($token->isGivenKind(T_NAMESPACE)) { if ($isNamespaceFound) { return; } $isNamespaceFound = true; } elseif ($token->isClassy()) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ($prevToken->isGivenKind(T_NEW)) { continue; } if (null !== $classyName) { return; } $classyIndex = $tokens->getNextMeaningfulToken($index); $classyName = $tokens[$classyIndex]->getContent(); } } if (null === $classyName) { return; } if ($isNamespaceFound) { $filename = basename(str_replace('\\', '/', $file->getRealPath()), '.php'); if ($classyName !== $filename) { $tokens[$classyIndex] = new Token([T_STRING, $filename]); } } else { $normClass = str_replace('_', '/', $classyName); $filename = substr(str_replace('\\', '/', $file->getRealPath()), -\strlen($normClass) - 4, -4); if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) { $tokens[$classyIndex] = new Token([T_STRING, str_replace('/', '_', $filename)]); } } } } symbolsReplace = [ pack('H*', 'e2808b') => ['', '200b'], pack('H*', 'e28087') => [' ', '2007'], pack('H*', 'e280af') => [' ', '202f'], pack('H*', 'e281a0') => ['', '2060'], pack('H*', 'c2a0') => [' ', 'a0'], ]; } public function getDefinition() { return new FixerDefinition( 'Remove Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols.', [ new CodeSample( ' true] ), ], null, 'Risky when strings contain intended invisible characters.' ); } public function isRisky() { return true; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(self::$tokens); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use_escape_sequences_in_strings', 'Whether characters should be replaced with escape sequences in strings.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->setNormalizer(static function (Options $options, $value) { if (\PHP_VERSION_ID < 70000 && $value) { throw new InvalidOptionsForEnvException('Escape sequences require PHP 7.0+.'); } return $value; }) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $replacements = []; $escapeSequences = []; foreach ($this->symbolsReplace as $character => list($replacement, $codepoint)) { $replacements[$character] = $replacement; $escapeSequences[$character] = '\u{'.$codepoint.'}'; } foreach ($tokens as $index => $token) { $content = $token->getContent(); if ( $this->configuration['use_escape_sequences_in_strings'] && $token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE]) ) { if (!Preg::match('/'.implode('|', array_keys($escapeSequences)).'/', $content)) { continue; } $previousToken = $tokens[$index - 1]; $stringTypeChanged = false; $swapQuotes = false; if ($previousToken->isGivenKind(T_START_HEREDOC)) { $previousTokenContent = $previousToken->getContent(); if (false !== strpos($previousTokenContent, '\'')) { $tokens[$index - 1] = new Token([T_START_HEREDOC, str_replace('\'', '', $previousTokenContent)]); $stringTypeChanged = true; } } elseif ("'" === $content[0]) { $stringTypeChanged = true; $swapQuotes = true; } if ($swapQuotes) { $content = str_replace("\\'", "'", $content); } if ($stringTypeChanged) { $content = Preg::replace('/(\\\\{1,2})/', '\\\\\\\\', $content); $content = str_replace('$', '\$', $content); } if ($swapQuotes) { $content = str_replace('"', '\"', $content); $content = Preg::replace('/^\'(.*)\'$/', '"$1"', $content); } $tokens[$index] = new Token([$token->getId(), strtr($content, $escapeSequences)]); continue; } if ($token->isGivenKind(self::$tokens)) { $tokens[$index] = new Token([$token->getId(), strtr($content, $replacements)]); } } } } './src'] ), ], null, 'This fixer may change your class name, which will break the code that depends on the old name.' ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $namespace = false; $namespaceIndex = 0; $namespaceEndIndex = 0; $classyName = null; $classyIndex = 0; foreach ($tokens as $index => $token) { if ($token->isGivenKind(T_NAMESPACE)) { if (false !== $namespace) { return; } $namespaceIndex = $tokens->getNextMeaningfulToken($index); $namespaceEndIndex = $tokens->getNextTokenOfKind($index, [';']); $namespace = trim($tokens->generatePartialCode($namespaceIndex, $namespaceEndIndex - 1)); } elseif ($token->isClassy()) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ($prevToken->isGivenKind(T_NEW)) { continue; } if (null !== $classyName) { return; } $classyIndex = $tokens->getNextMeaningfulToken($index); $classyName = $tokens[$classyIndex]->getContent(); } } if (null === $classyName) { return; } if (false !== $namespace) { $normNamespace = str_replace('\\', '/', $namespace); $path = str_replace('\\', '/', $file->getRealPath()); $dir = \dirname($path); if ('' !== $this->configuration['dir']) { $dir = substr($dir, \strlen(realpath($this->configuration['dir'])) + 1); if (false === $dir) { $dir = ''; } if (\strlen($normNamespace) > \strlen($dir)) { if ('' !== $dir) { $normNamespace = substr($normNamespace, -\strlen($dir)); } else { $normNamespace = ''; } } } $dir = substr($dir, -\strlen($normNamespace)); if (false === $dir) { $dir = ''; } $filename = basename($path, '.php'); if ($classyName !== $filename) { $tokens[$classyIndex] = new Token([T_STRING, $filename]); } if ($normNamespace !== $dir && strtolower($normNamespace) === strtolower($dir)) { for ($i = $namespaceIndex; $i <= $namespaceEndIndex; ++$i) { $tokens->clearAt($i); } $namespace = substr($namespace, 0, -\strlen($dir)).str_replace('/', '\\', $dir); $newNamespace = Tokens::fromCode('clearRange(0, 2); $newNamespace->clearEmptyTokens(); $tokens->insertAt($namespaceIndex, $newNamespace); } } else { $normClass = str_replace('_', '/', $classyName); $path = str_replace('\\', '/', $file->getRealPath()); $filename = substr($path, -\strlen($normClass) - 4, -4); if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) { $tokens[$classyIndex] = new Token([T_STRING, str_replace('/', '_', $filename)]); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('dir', 'The directory where the project code is placed.')) ->setAllowedTypes(['string']) ->setDefault('') ->getOption(), ]); } } = 0; }; $negative = function ($item) { return $item < 0; }; ', ['allow_single_line_closure' => true] ), new CodeSample( ' self::LINE_SAME] ), ] ); } public function getPriority() { return -25; } public function isCandidate(Tokens $tokens) { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->fixCommentBeforeBrace($tokens); $this->fixMissingControlBraces($tokens); $this->fixIndents($tokens); $this->fixControlContinuationBraces($tokens); $this->fixSpaceAroundToken($tokens); $this->fixDoWhile($tokens); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_NEXT) ->getOption(), (new FixerOptionBuilder('position_after_control_structures', 'whether the opening brace should be placed on "next" or "same" line after control structures.')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_SAME) ->getOption(), (new FixerOptionBuilder('position_after_anonymous_constructs', 'whether the opening brace should be placed on "next" or "same" line after anonymous constructs (anonymous classes and lambda functions).')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_SAME) ->getOption(), ]); } private function fixCommentBeforeBrace(Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $controlTokens = $this->getControlTokens(); for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if ($token->isGivenKind($controlTokens)) { $prevIndex = $this->findParenthesisEnd($tokens, $index); } elseif ( ($token->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($index)) || ($token->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) ) { $prevIndex = $tokens->getNextTokenOfKind($index, ['{']); $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); } else { continue; } $commentIndex = $tokens->getNextNonWhitespace($prevIndex); $commentToken = $tokens[$commentIndex]; if (!$commentToken->isGivenKind(T_COMMENT) || 0 === strpos($commentToken->getContent(), '/*')) { continue; } $braceIndex = $tokens->getNextMeaningfulToken($commentIndex); $braceToken = $tokens[$braceIndex]; if (!$braceToken->equals('{')) { continue; } $tokenTmp = $tokens[$braceIndex]; $newBraceIndex = $prevIndex + 1; for ($i = $braceIndex; $i > $newBraceIndex; --$i) { $previousToken = $tokens[$i - 1]; $tokens[$i] = $previousToken; if ($tokens[$i]->isWhitespace() && $tokens[$i + 1]->isWhitespace()) { $tokens[$i] = new Token([T_WHITESPACE, $tokens[$i]->getContent().$tokens[$i + 1]->getContent()]); $tokens->clearAt($i + 1); } } $tokens[$newBraceIndex] = $tokenTmp; $c = $tokens[$braceIndex]->getContent(); if (substr_count($c, "\n") > 1) { $tokens[$braceIndex] = new Token([T_WHITESPACE, substr($c, strrpos($c, "\n"))]); } } } private function fixControlContinuationBraces(Tokens $tokens) { $controlContinuationTokens = $this->getControlContinuationTokens(); for ($index = \count($tokens) - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind($controlContinuationTokens)) { continue; } $prevIndex = $tokens->getPrevNonWhitespace($index); $prevToken = $tokens[$prevIndex]; if (!$prevToken->equals('}')) { continue; } $tokens->ensureWhitespaceAtIndex( $index - 1, 1, self::LINE_NEXT === $this->configuration['position_after_control_structures'] ? $this->whitespacesConfig->getLineEnding().$this->detectIndent($tokens, $index) : ' ' ); } } private function fixDoWhile(Tokens $tokens) { for ($index = \count($tokens) - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_DO)) { continue; } $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex); $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex); $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($endBraceIndex); $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex]; if (!$nextNonWhitespaceToken->isGivenKind(T_WHILE)) { continue; } $tokens->ensureWhitespaceAtIndex($nextNonWhitespaceIndex - 1, 1, ' '); } } private function fixIndents(Tokens $tokens) { $classyTokens = Token::getClassyTokenKinds(); $classyAndFunctionTokens = array_merge([T_FUNCTION], $classyTokens); $controlTokens = $this->getControlTokens(); $indentTokens = array_filter( array_merge($classyAndFunctionTokens, $controlTokens), static function ($item) { return T_SWITCH !== $item; } ); $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = 0, $limit = \count($tokens); $index < $limit; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind($indentTokens)) { continue; } if ( $token->isGivenKind(T_WHILE) && $tokensAnalyzer->isWhilePartOfDoWhile($index) ) { continue; } if ( $this->configuration['allow_single_line_closure'] && $token->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($index) ) { $braceEndIndex = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($index, ['{']) ); if (!$this->isMultilined($tokens, $index, $braceEndIndex)) { $index = $braceEndIndex; continue; } } if ($token->isGivenKind($classyAndFunctionTokens)) { $startBraceIndex = $tokens->getNextTokenOfKind($index, [';', '{']); $startBraceToken = $tokens[$startBraceIndex]; } else { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex); $startBraceToken = $tokens[$startBraceIndex]; } if (!$startBraceToken->equals('{')) { continue; } $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startBraceIndex, " \t"); $nextNonWhitespace = $tokens[$nextNonWhitespaceIndex]; if ($nextNonWhitespace->isGivenKind(T_CLOSE_TAG)) { continue; } if ($nextNonWhitespace->isComment() && $tokens[$tokens->getNextMeaningfulToken($nextNonWhitespaceIndex)]->isGivenKind(T_CLOSE_TAG)) { continue; } $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex); $indent = $this->detectIndent($tokens, $index); $tokens->ensureWhitespaceAtIndex($endBraceIndex - 1, 1, $this->whitespacesConfig->getLineEnding().$indent); $lastCommaIndex = $tokens->getPrevTokenOfKind($endBraceIndex - 1, [';', '}']); $nestLevel = 1; for ($nestIndex = $lastCommaIndex; $nestIndex >= $startBraceIndex; --$nestIndex) { $nestToken = $tokens[$nestIndex]; if ($nestToken->equalsAny([')', [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE]])) { $nestIndex = $tokens->findBlockStart( $nestToken->equals(')') ? Tokens::BLOCK_TYPE_PARENTHESIS_BRACE : Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, $nestIndex ); continue; } if (1 === $nestLevel) { $nextLineCanBeIndented = false; if ($nestToken->equalsAny([';', '}'])) { $nextLineCanBeIndented = true; } elseif ($this->isCommentWithFixableIndentation($tokens, $nestIndex)) { for ($i = $nestIndex; $i > $startBraceIndex; --$i) { if ($tokens[$i]->equalsAny([';', '}'])) { $nextLineCanBeIndented = true; break; } if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) { break; } } if ($nextLineCanBeIndented || $i === $startBraceIndex) { $nextToken = $tokens[$nestIndex + 1]; $nextLineCanBeIndented = $nextToken->isWhitespace() && 1 === Preg::match('/\R/', $nextToken->getContent()); } } if (!$nextLineCanBeIndented) { continue; } $nextNonWhitespaceNestIndex = $tokens->getNextNonWhitespace($nestIndex); $nextNonWhitespaceNestToken = $tokens[$nextNonWhitespaceNestIndex]; if ( !($nextNonWhitespaceNestToken->isComment() && ( !$tokens[$nextNonWhitespaceNestIndex - 1]->isWhitespace() || !Preg::match('/\R/', $tokens[$nextNonWhitespaceNestIndex - 1]->getContent()) )) && !($nestToken->equals('}') && $nextNonWhitespaceNestToken->equalsAny([';', ',', ']', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) && !($nestToken->equals('}') && $nextNonWhitespaceNestToken->equals('(')) && !($nestToken->equals('}') && $tokens[$nestIndex - 1]->equalsAny(['"', "'", [T_CONSTANT_ENCAPSED_STRING], [T_VARIABLE]])) && !($tokens[$nestIndex - 1]->isGivenKind(T_END_HEREDOC) && $nextNonWhitespaceNestToken->isGivenKind(T_CLOSE_TAG)) ) { if ( ( self::LINE_NEXT !== $this->configuration['position_after_control_structures'] && $nextNonWhitespaceNestToken->isGivenKind($this->getControlContinuationTokens()) && !$tokens[$tokens->getPrevNonWhitespace($nextNonWhitespaceNestIndex)]->isComment() ) || $nextNonWhitespaceNestToken->isGivenKind(T_CLOSE_TAG) || ( self::LINE_NEXT !== $this->configuration['position_after_control_structures'] && $nextNonWhitespaceNestToken->isGivenKind(T_WHILE) && $tokensAnalyzer->isWhilePartOfDoWhile($nextNonWhitespaceNestIndex) ) ) { $whitespace = ' '; } else { $nextToken = $tokens[$nestIndex + 1]; $nextWhitespace = ''; if ($nextToken->isWhitespace()) { $nextWhitespace = rtrim($nextToken->getContent(), " \t"); if ('' !== $nextWhitespace) { $nextWhitespace = Preg::replace( sprintf('/%s$/', $this->whitespacesConfig->getLineEnding()), '', $nextWhitespace, 1 ); } } $whitespace = $nextWhitespace.$this->whitespacesConfig->getLineEnding().$indent; if (!$nextNonWhitespaceNestToken->equals('}')) { $determineIsIndentableBlockContent = static function ($contentIndex) use ($tokens) { if (!$tokens[$contentIndex]->isComment()) { return true; } if (!$tokens[$tokens->getPrevMeaningfulToken($contentIndex)]->equals(';')) { return true; } $nextIndex = $tokens->getNextMeaningfulToken($contentIndex); if (!$tokens[$nextIndex]->equals('}')) { return true; } $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if (null === $nextNextIndex) { return true; } if ($tokens[$nextNextIndex]->equalsAny([ [T_ELSE], [T_ELSEIF], ',', ])) { return false; } return true; }; if ($determineIsIndentableBlockContent($nestIndex + 2)) { $whitespace .= $this->whitespacesConfig->getIndent(); } } } $this->ensureWhitespaceAtIndexAndIndentMultilineComment($tokens, $nestIndex + 1, $whitespace); } } if ($nestToken->equals('}')) { ++$nestLevel; continue; } if ($nestToken->equals('{')) { --$nestLevel; continue; } } if (isset($tokens[$startBraceIndex + 2]) && $tokens[$startBraceIndex + 2]->equals('}')) { $tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, $this->whitespacesConfig->getLineEnding().$indent); } else { $nextToken = $tokens[$startBraceIndex + 1]; $nextNonWhitespaceToken = $tokens[$tokens->getNextNonWhitespace($startBraceIndex)]; if ( !$nextNonWhitespaceToken->isComment() || ($nextToken->isWhitespace() && 1 === substr_count($nextToken->getContent(), "\n")) ) { $this->ensureWhitespaceAtIndexAndIndentMultilineComment( $tokens, $startBraceIndex + 1, $this->whitespacesConfig->getLineEnding().$indent.$this->whitespacesConfig->getIndent() ); } } if ($token->isGivenKind($classyTokens) && !$tokensAnalyzer->isAnonymousClass($index)) { if (self::LINE_SAME === $this->configuration['position_after_functions_and_oop_constructs'] && !$tokens[$tokens->getPrevNonWhitespace($startBraceIndex)]->isComment()) { $ensuredWhitespace = ' '; } else { $ensuredWhitespace = $this->whitespacesConfig->getLineEnding().$indent; } $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, $ensuredWhitespace); } elseif ( $token->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index) || ( self::LINE_NEXT === $this->configuration['position_after_control_structures'] && $token->isGivenKind($controlTokens) || ( self::LINE_NEXT === $this->configuration['position_after_anonymous_constructs'] && ( $token->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($index) || $token->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($index) ) ) ) ) { $isAnonymousClass = $token->isGivenKind($classyTokens) && $tokensAnalyzer->isAnonymousClass($index); $closingParenthesisIndex = $tokens->getPrevTokenOfKind($startBraceIndex, [')']); if (null === $closingParenthesisIndex && !$isAnonymousClass) { continue; } if ( !$isAnonymousClass && $tokens[$closingParenthesisIndex - 1]->isWhitespace() && false !== strpos($tokens[$closingParenthesisIndex - 1]->getContent(), "\n") ) { if (!$tokens[$startBraceIndex - 2]->isComment()) { $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); } } else { if ( self::LINE_SAME === $this->configuration['position_after_functions_and_oop_constructs'] && ( $token->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index) || $token->isGivenKind($classyTokens) && !$tokensAnalyzer->isAnonymousClass($index) ) && !$tokens[$tokens->getPrevNonWhitespace($startBraceIndex)]->isComment() ) { $ensuredWhitespace = ' '; } else { $ensuredWhitespace = $this->whitespacesConfig->getLineEnding().$indent; } $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, $ensuredWhitespace); } } else { $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); } $limit = \count($tokens); } } private function fixMissingControlBraces(Tokens $tokens) { $controlTokens = $this->getControlTokens(); for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind($controlTokens)) { continue; } $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $nextAfterParenthesisEndIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); $tokenAfterParenthesis = $tokens[$nextAfterParenthesisEndIndex]; if ($tokenAfterParenthesis->equals('{') && self::LINE_SAME === $this->configuration['position_after_control_structures']) { $tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' '); continue; } if ($tokenAfterParenthesis->equalsAny([';', '{', ':'])) { continue; } if ($tokenAfterParenthesis->isGivenKind([T_FOR, T_FOREACH, T_SWITCH, T_WHILE])) { $tokenAfterParenthesisBlockEnd = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($nextAfterParenthesisEndIndex) ); if ($tokens[$tokens->getNextMeaningfulToken($tokenAfterParenthesisBlockEnd)]->equals(':')) { continue; } } $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); $tokens->insertAt($statementEndIndex + 1, [new Token([T_WHITESPACE, ' ']), new Token('}')]); if (!$tokens[$statementEndIndex]->equalsAny([';', '}'])) { $tokens->insertAt($statementEndIndex + 1, new Token(';')); } $tokens->insertAt($parenthesisEndIndex + 1, new Token('{')); $tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' '); } } private function fixSpaceAroundToken(Tokens $tokens) { $controlTokens = $this->getControlTokens(); for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_DECLARE)) { $this->fixDeclareStatement($tokens, $index); } elseif ($token->isGivenKind($controlTokens) || $token->isGivenKind(CT::T_USE_LAMBDA)) { $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index); if (!$tokens[$nextNonWhitespaceIndex]->equals(':')) { $tokens->ensureWhitespaceAtIndex( $index + 1, 0, self::LINE_NEXT === $this->configuration['position_after_control_structures'] && !$tokens[$nextNonWhitespaceIndex]->equals('(') ? $this->whitespacesConfig->getLineEnding().$this->detectIndent($tokens, $index) : ' ' ); } $prevToken = $tokens[$index - 1]; if (!$prevToken->isWhitespace() && !$prevToken->isComment() && !$prevToken->isGivenKind(T_OPEN_TAG)) { $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' '); } } } } private function detectIndent(Tokens $tokens, $index) { while (true) { $whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE]]); if (null === $whitespaceIndex) { return ''; } $whitespaceToken = $tokens[$whitespaceIndex]; if (false !== strpos($whitespaceToken->getContent(), "\n")) { break; } $prevToken = $tokens[$whitespaceIndex - 1]; if ($prevToken->isGivenKind([T_OPEN_TAG, T_COMMENT]) && "\n" === substr($prevToken->getContent(), -1)) { break; } $index = $whitespaceIndex; } $explodedContent = explode("\n", $whitespaceToken->getContent()); return end($explodedContent); } private function findParenthesisEnd(Tokens $tokens, $structureTokenIndex) { $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); $nextToken = $tokens[$nextIndex]; if (!$nextToken->equals('(')) { return $structureTokenIndex; } return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); } private function findStatementEnd(Tokens $tokens, $parenthesisEndIndex) { $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); $nextToken = $tokens[$nextIndex]; if (!$nextToken) { return $parenthesisEndIndex; } if ($nextToken->equals('{')) { return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex); } if ($nextToken->isGivenKind($this->getControlTokens())) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); if ($nextToken->isGivenKind([T_IF, T_TRY, T_DO])) { $openingTokenKind = $nextToken->getId(); while (true) { $nextIndex = $tokens->getNextMeaningfulToken($endIndex); $nextToken = isset($nextIndex) ? $tokens[$nextIndex] : null; if ($nextToken && $nextToken->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); if ($nextToken->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) { return $endIndex; } } else { break; } } } return $endIndex; } $index = $parenthesisEndIndex; while (true) { $token = $tokens[++$index]; if ($token->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->equals(';')) { return $index; } if ($token->isGivenKind(T_CLOSE_TAG)) { return $tokens->getPrevNonWhitespace($index); } } } private function getControlTokens() { static $tokens = [ T_DECLARE, T_DO, T_ELSE, T_ELSEIF, T_FINALLY, T_FOR, T_FOREACH, T_IF, T_WHILE, T_TRY, T_CATCH, T_SWITCH, ]; return $tokens; } private function getControlContinuationTokens() { static $tokens = [ T_CATCH, T_ELSE, T_ELSEIF, T_FINALLY, ]; return $tokens; } private function getControlContinuationTokensForOpeningToken($openingTokenKind) { if (T_IF === $openingTokenKind) { return [ T_ELSE, T_ELSEIF, ]; } if (T_DO === $openingTokenKind) { return [T_WHILE]; } if (T_TRY === $openingTokenKind) { return [ T_CATCH, T_FINALLY, ]; } return []; } private function getFinalControlContinuationTokensForOpeningToken($openingTokenKind) { if (T_IF === $openingTokenKind) { return [T_ELSE]; } if (T_TRY === $openingTokenKind) { return [T_FINALLY]; } return []; } private function fixDeclareStatement(Tokens $tokens, $index) { $tokens->removeTrailingWhitespace($index); $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); $tokens->removeTrailingWhitespace($startParenthesisIndex); $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); $tokens->removeLeadingWhitespace($endParenthesisIndex); $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{']); $startBraceToken = $tokens[$startBraceIndex]; if ($startBraceToken->equals('{')) { $this->fixSingleLineWhitespaceForDeclare($tokens, $startBraceIndex); } } private function fixSingleLineWhitespaceForDeclare(Tokens $tokens, $startBraceIndex) { if ( !$tokens[$startBraceIndex - 1]->isWhitespace() || $tokens[$startBraceIndex - 1]->isWhitespace(" \t") ) { $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); } } private function ensureWhitespaceAtIndexAndIndentMultilineComment(Tokens $tokens, $index, $whitespace) { if ($tokens[$index]->isWhitespace()) { $nextTokenIndex = $tokens->getNextNonWhitespace($index); } else { $nextTokenIndex = $index; } $nextToken = $tokens[$nextTokenIndex]; if ($nextToken->isComment()) { $previousToken = $tokens[$nextTokenIndex - 1]; $nextTokenContent = $nextToken->getContent(); if ( $previousToken->isWhitespace() && 1 === Preg::match('/\R$/', $previousToken->getContent()) && ( (0 === strpos($nextTokenContent, '//'.$this->whitespacesConfig->getIndent()) || '//' === $nextTokenContent) || (0 === strpos($nextTokenContent, '#'.$this->whitespacesConfig->getIndent()) || '#' === $nextTokenContent) ) ) { return; } $tokens[$nextTokenIndex] = new Token([ $nextToken->getId(), Preg::replace( '/(\R)'.$this->detectIndent($tokens, $nextTokenIndex).'(\h*\S+.*)/', '$1'.Preg::replace('/^.*\R(\h*)$/s', '$1', $whitespace).'$2', $nextToken->getContent() ), ]); } $tokens->ensureWhitespaceAtIndex($index, 0, $whitespace); } private function isMultilined(Tokens $tokens, $startParenthesisIndex, $endParenthesisIndex) { for ($i = $startParenthesisIndex; $i < $endParenthesisIndex; ++$i) { if (false !== strpos($tokens[$i]->getContent(), "\n")) { return true; } } return false; } private function isCommentWithFixableIndentation(Tokens $tokens, $index) { if (!$tokens[$index]->isComment()) { return false; } if (0 === strpos($tokens[$index]->getContent(), '/*')) { return true; } $firstCommentIndex = $index; while (true) { $i = $this->getSiblingContinuousSingleLineComment($tokens, $firstCommentIndex, false); if (null === $i) { break; } $firstCommentIndex = $i; } $lastCommentIndex = $index; while (true) { $i = $this->getSiblingContinuousSingleLineComment($tokens, $lastCommentIndex, true); if (null === $i) { break; } $lastCommentIndex = $i; } if ($firstCommentIndex === $lastCommentIndex) { return true; } for ($i = $firstCommentIndex + 1; $i < $lastCommentIndex; ++$i) { if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) { return false; } } return true; } private function getSiblingContinuousSingleLineComment(Tokens $tokens, $index, $after) { $siblingIndex = $index; do { $siblingIndex = $tokens->getTokenOfKindSibling($siblingIndex, $after ? 1 : -1, [[T_COMMENT]]); if (null === $siblingIndex) { return null; } } while (0 === strpos($tokens[$siblingIndex]->getContent(), '/*')); $newLines = 0; for ($i = min($siblingIndex, $index) + 1, $max = max($siblingIndex, $index); $i < $max; ++$i) { if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) { if (1 === $newLines || Preg::match('/\R.*\R/', $tokens[$i]->getContent())) { return null; } ++$newLines; } } return $siblingIndex; } } BOM = pack('CCC', 0xef, 0xbb, 0xbf); } public function getDefinition() { return new FixerDefinition( 'PHP code MUST use only UTF-8 without BOM (remove BOM).', [ new CodeSample( $this->BOM.'getContent(); if (0 === strncmp($content, $this->BOM, 3)) { $newContent = substr($content, 3); if (false === $newContent) { $newContent = ''; } if ('' === $newContent) { $tokens->clearAt(0); } else { $tokens[0] = new Token([$tokens[0]->getId(), $newContent]); } } } } true, ]), ] ); } public function getPriority() { return -1; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(';'); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('remove_in_empty_for_expressions', 'Whether spaces should be removed for empty `for` expressions.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $insideForParenthesesUntil = null; for ($index = 0, $max = \count($tokens) - 1; $index < $max; ++$index) { if ($this->configuration['remove_in_empty_for_expressions']) { if ($tokens[$index]->isGivenKind(T_FOR)) { $index = $tokens->getNextMeaningfulToken($index); $insideForParenthesesUntil = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($index === $insideForParenthesesUntil) { $insideForParenthesesUntil = null; continue; } } if (!$tokens[$index]->equals(';')) { continue; } if (!$tokens[$index + 1]->isWhitespace()) { if ( !$tokens[$index + 1]->equalsAny([')', [T_INLINE_HTML]]) && ( !$this->configuration['remove_in_empty_for_expressions'] || !$tokens[$index + 1]->equals(';') ) ) { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); ++$max; } continue; } if ( null !== $insideForParenthesesUntil && ($tokens[$index + 2]->equals(';') || $index + 2 === $insideForParenthesesUntil) && !Preg::match('/\R/', $tokens[$index + 1]->getContent()) ) { $tokens->clearAt($index + 1); continue; } if ( isset($tokens[$index + 2]) && !$tokens[$index + 1]->equals([T_WHITESPACE, ' ']) && $tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment() && !$tokens[$index + 2]->equals(')') ) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } } } } isTokenKindFound(';'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if ($tokens[$index]->isGivenKind(T_FOR)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index)) + 1; continue; } if (!$tokens[$index]->equals(';')) { continue; } $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$previousMeaningfulIndex]->equalsAny(['{', ';', [T_OPEN_TAG]])) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); continue; } if ($tokens[$previousMeaningfulIndex]->equals('}')) { $this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex); } } } private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, $index, $curlyCloseIndex) { static $beforeCurlyOpeningKinds = null; if (null === $beforeCurlyOpeningKinds) { $beforeCurlyOpeningKinds = [T_ELSE, T_FINALLY, T_NAMESPACE, T_OPEN_TAG]; } $curlyOpeningIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $curlyCloseIndex); $beforeCurlyOpening = $tokens->getPrevMeaningfulToken($curlyOpeningIndex); if ($tokens[$beforeCurlyOpening]->isGivenKind($beforeCurlyOpeningKinds) || $tokens[$beforeCurlyOpening]->equalsAny([';', '{', '}'])) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); return; } if ($tokens[$beforeCurlyOpening]->isGivenKind(T_STRING)) { $classyTest = $tokens->getPrevMeaningfulToken($beforeCurlyOpening); while ($tokens[$classyTest]->equals(',') || $tokens[$classyTest]->isGivenKind([T_STRING, T_NS_SEPARATOR, T_EXTENDS, T_IMPLEMENTS])) { $classyTest = $tokens->getPrevMeaningfulToken($classyTest); } $tokensAnalyzer = new TokensAnalyzer($tokens); if ( $tokens[$classyTest]->isGivenKind(T_NAMESPACE) || ($tokens[$classyTest]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTest)) ) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } return; } if (!$tokens[$beforeCurlyOpening]->equals(')')) { return; } $openingBrace = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpening); $beforeOpeningBrace = $tokens->getPrevMeaningfulToken($openingBrace); if ($tokens[$beforeOpeningBrace]->isGivenKind([T_IF, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_SWITCH, T_CATCH, T_DECLARE])) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); return; } if ($tokens[$beforeOpeningBrace]->isGivenKind(T_STRING)) { $beforeString = $tokens->getPrevMeaningfulToken($beforeOpeningBrace); if ($tokens[$beforeString]->isGivenKind(T_FUNCTION)) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } } } foo() ;\n")] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(';'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(" \t")) { continue; } if ($tokens[$index - 2]->equals(';')) { if (!$tokens[$index - 1]->equals(' ')) { $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); } } elseif (!$tokens[$index - 2]->isComment()) { $tokens->clearAt($index - 1); } } } } \n")] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_CLOSE_TAG); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; $index > 1; --$index) { if (!$tokens[$index]->isGivenKind(T_CLOSE_TAG)) { continue; } $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->equalsAny([';', '{', '}', ':', [T_OPEN_TAG]])) { continue; } $tokens->insertAt($prev + 1, new Token(';')); } } } proxyFixers); } protected function createProxyFixers() { $fixer = new MultilineWhitespaceBeforeSemicolonsFixer(); $fixer->configure(['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NO_MULTI_LINE]); return [$fixer]; } } method1() ->method2() ->method(3); ?> ', ['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(';'); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder( 'strategy', 'Forbid multi-line whitespace or move the semicolon to the new line for chained calls.' )) ->setAllowedValues([self::STRATEGY_NO_MULTI_LINE, self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS]) ->setDefault(self::STRATEGY_NO_MULTI_LINE) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy']) { $this->applyChainedCallsFix($tokens); return; } if (self::STRATEGY_NO_MULTI_LINE === $this->configuration['strategy']) { $this->applyNoMultiLineFix($tokens); } } private function applyNoMultiLineFix(Tokens $tokens) { $lineEnding = $this->whitespacesConfig->getLineEnding(); foreach ($tokens as $index => $token) { if (!$token->equals(';')) { continue; } $previousIndex = $index - 1; $previous = $tokens[$previousIndex]; if (!$previous->isWhitespace() || false === strpos($previous->getContent(), "\n")) { continue; } $content = $previous->getContent(); if (0 === strpos($content, $lineEnding) && $tokens[$index - 2]->isComment()) { $tokens->ensureWhitespaceAtIndex($previousIndex, 0, $lineEnding); } else { $tokens->clearAt($previousIndex); } } } private function applyChainedCallsFix(Tokens $tokens) { for ($index = \count($tokens) - 1; $index >= 0; --$index) { if (!$tokens[$index]->equals(';')) { continue; } $indent = $this->findWhitespaceBeforeFirstCall($index - 1, $tokens); if (null === $indent) { continue; } $tokens->clearAt($index); $index = $this->getNewLineIndex($index, $tokens); $lineEnding = $this->whitespacesConfig->getLineEnding(); $newline = new Token([T_WHITESPACE, $lineEnding.$indent]); $tokens->insertAt($index, [$newline, new Token(';')]); } } private function getNewLineIndex($index, Tokens $tokens) { $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($index, $count = \count($tokens); $index < $count; ++$index) { if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) { return $index; } } return $index; } private function findWhitespaceBeforeFirstCall($index, Tokens $tokens) { if (!$tokens[$index]->equals(')')) { return null; } $openingBrackets = 1; for (--$index; $index > 0; --$index) { if ($tokens[$index]->equals(')')) { ++$openingBrackets; continue; } if ($tokens[$index]->equals('(')) { if (1 === $openingBrackets) { break; } --$openingBrackets; } } if (!$tokens[--$index]->isGivenKind(T_STRING)) { return null; } if (!$tokens[--$index]->isGivenKind([T_OBJECT_OPERATOR, T_DOUBLE_COLON])) { return null; } if (!$tokens[--$index]->isGivenKind(T_WHITESPACE)) { return null; } $closingBrackets = 0; for ($index; $index >= 0; --$index) { if ($tokens[$index]->equals(')')) { ++$closingBrackets; } if ($tokens[$index]->equals('(')) { --$closingBrackets; } if ($tokens[$index]->isGivenKind([T_VARIABLE, T_RETURN, T_STRING]) && 0 === $closingBrackets) { if ($tokens[--$index]->isGivenKind(T_WHITESPACE) || $tokens[$index]->isGivenKind(T_OPEN_TAG)) { return $this->getIndentAt($tokens, $index); } } } return null; } private function getIndentAt(Tokens $tokens, $index) { $content = ''; $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($index; $index > 0; --$index) { if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) { break; } } if ($tokens[$index]->isWhitespace()) { $content = $tokens[$index]->getContent(); --$index; } if ($tokens[$index]->isGivenKind(T_OPEN_TAG)) { $content = $tokens[$index]->getContent().$content; } if (1 === Preg::match('/\R{1}(\h*)$/', $content, $matches)) { return $matches[1]; } return null; } } isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $this->fixSpacing($index, $tokens); } } } private function fixSpacing($index, Tokens $tokens) { if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $startIndex = $index; $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); } else { $startIndex = $tokens->getNextTokenOfKind($index, ['(']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); } for ($i = $endIndex - 1; $i > $startIndex; --$i) { $i = $this->skipNonArrayElements($i, $tokens); if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) { $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); } } } private function skipNonArrayElements($index, Tokens $tokens) { if ($tokens[$index]->equals('}')) { return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); } if ($tokens[$index]->equals(')')) { $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $startIndex = $tokens->getPrevMeaningfulToken($startIndex); if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { return $startIndex; } } return $index; } } isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) { if ($tokensAnalyzer->isArray($index)) { $this->fixArray($tokens, $index); } } } private function fixArray(Tokens $tokens, $index) { $tokensAnalyzer = new TokensAnalyzer($tokens); if ($tokensAnalyzer->isArrayMultiLine($index)) { return; } $startIndex = $index; if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) { $startIndex = $tokens->getNextTokenOfKind($startIndex, ['(']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); } else { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); } $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); $beforeEndToken = $tokens[$beforeEndIndex]; if ($beforeEndToken->equals(',')) { $tokens->removeTrailingWhitespace($beforeEndIndex); $tokens->clearAt($beforeEndIndex); } } } isTokenKindFound(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) { $tokens[$index] = new Token('['); } elseif ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE)) { $tokens[$index] = new Token(']'); } } } } isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) { if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { self::fixArray($tokens, $index); } } } private static function fixArray(Tokens $tokens, $index) { $startIndex = $index; if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) { $startIndex = $tokens->getNextMeaningfulToken($startIndex); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); } else { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); } $nextIndex = $startIndex + 1; $nextToken = $tokens[$nextIndex]; $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex); $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex]; $tokenAfterNextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex + 1]; $prevIndex = $endIndex - 1; $prevToken = $tokens[$prevIndex]; $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex); $prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex]; if ( $nextToken->isWhitespace(" \t") && ( !$nextNonWhitespaceToken->isComment() || $nextNonWhitespaceIndex === $prevNonWhitespaceIndex || $tokenAfterNextNonWhitespaceToken->isWhitespace(" \t") || '/*' === substr($nextNonWhitespaceToken->getContent(), 0, 2) ) ) { $tokens->clearAt($nextIndex); } if ( $prevToken->isWhitespace(" \t") && !$prevNonWhitespaceToken->equals(',') ) { $tokens->clearAt($prevIndex); } } } true] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokensAnalyzer->isArray($index) && $tokensAnalyzer->isArrayMultiLine($index)) { $this->fixArray($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('after_heredoc', 'Whether a trailing comma should also be placed after heredoc end.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->setNormalizer(static function (Options $options, $value) { if (\PHP_VERSION_ID < 70300 && $value) { throw new InvalidOptionsForEnvException('"after_heredoc" option can only be enabled with PHP 7.3+.'); } return $value; }) ->getOption(), ]); } private function fixArray(Tokens $tokens, $index) { $startIndex = $index; if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) { $startIndex = $tokens->getNextTokenOfKind($startIndex, ['(']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); } else { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); } $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); $beforeEndToken = $tokens[$beforeEndIndex]; if ( $startIndex !== $beforeEndIndex && !$beforeEndToken->equals(',') && ($this->configuration['after_heredoc'] || !$beforeEndToken->isGivenKind(T_END_HEREDOC)) ) { $tokens->insertAt($beforeEndIndex + 1, new Token(',')); $endToken = $tokens[$endIndex]; if (!$endToken->isComment() && !$endToken->isWhitespace()) { $tokens->ensureWhitespaceAtIndex($endIndex, 1, ' '); } } } } true] ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $this->fixSpacing($index, $tokens); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->setNormalizer(static function (Options $options, $value) { if (\PHP_VERSION_ID < 70300 && $value) { throw new InvalidOptionsForEnvException('"after_heredoc" option can only be enabled with PHP 7.3+.'); } return $value; }) ->getOption(), ]); } private function fixSpacing($index, Tokens $tokens) { if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $startIndex = $index; $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); } else { $startIndex = $tokens->getNextTokenOfKind($index, ['(']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); } for ($i = $endIndex - 1; $i > $startIndex; --$i) { $i = $this->skipNonArrayElements($i, $tokens); $currentToken = $tokens[$i]; $prevIndex = $tokens->getPrevNonWhitespace($i - 1); if ( $currentToken->equals(',') && !$tokens[$prevIndex]->isComment() && ($this->configuration['after_heredoc'] || !$tokens[$prevIndex]->equals([T_END_HEREDOC])) ) { $tokens->removeLeadingWhitespace($i); } } } private function skipNonArrayElements($index, Tokens $tokens) { if ($tokens[$index]->equals('}')) { return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); } if ($tokens[$index]->equals(')')) { $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $startIndex = $tokens->getPrevMeaningfulToken($startIndex); if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { return $startIndex; } } return $index; } } resolveCandidateTokenKind(); $this->resolveFixCallback(); } public function getDefinition() { return new FixerDefinition( 'PHP arrays should be declared using the configured syntax.', [ new CodeSample( " 'short'] ), ] ); } public function getPriority() { return 1; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound($this->candidateTokenKind); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $callback = $this->fixCallback; for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { $this->{$callback}($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` array syntax.')) ->setAllowedValues(['long', 'short']) ->setDefault('long') ->getOption(), ]); } private function fixToLongArraySyntax(Tokens $tokens, $index) { $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); $tokens[$index] = new Token('('); $tokens[$closeIndex] = new Token(')'); $tokens->insertAt($index, new Token([T_ARRAY, 'array'])); } private function fixToShortArraySyntax(Tokens $tokens, $index) { $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $tokens[$openIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']); $tokens[$closeIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } private function resolveFixCallback() { $this->fixCallback = sprintf('fixTo%sArraySyntax', ucfirst($this->configuration['syntax'])); } private function resolveCandidateTokenKind() { $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_ARRAY_SQUARE_BRACE_OPEN : T_ARRAY; } } ` should not be surrounded by multi-line whitespaces.', [new CodeSample(" 2);\n")] ); } public function getPriority() { return 1; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOUBLE_ARROW); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOUBLE_ARROW)) { continue; } $this->fixWhitespace($tokens, $index - 1); if (!$tokens[$index + 2]->isComment()) { $this->fixWhitespace($tokens, $index + 1); } } } private function fixWhitespace(Tokens $tokens, $index) { $token = $tokens[$index]; if ($token->isWhitespace() && !$token->isWhitespace(" \t")) { $tokens[$index] = new Token([T_WHITESPACE, rtrim($token->getContent()).' ']); } } } getPrevMeaningfulToken($index); $token = $tokens[$index]; $blockType = Tokens::detectBlockType($token); if (null !== $blockType && !$blockType['isStart']) { $index = $tokens->findBlockStart($blockType['type'], $index); $token = $tokens[$index]; } } while (!$token->equalsAny(['$', [T_VARIABLE]])); $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->equals('$')) { return $this->findStart($tokens, $index); } if ($prevToken->isGivenKind(T_OBJECT_OPERATOR)) { return $this->findStart($tokens, $prevIndex); } if ($prevToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); if (!$tokens[$prevPrevIndex]->isGivenKind([T_STATIC, T_STRING])) { return $this->findStart($tokens, $prevIndex); } $index = $tokens->getTokenNotOfKindsSibling($prevIndex, -1, [T_NS_SEPARATOR, T_STATIC, T_STRING]); $index = $tokens->getNextMeaningfulToken($index); } return $index; } } 'namespaced'] ), new CodeSample( " [ 'MY_CUSTOM_PI', ], ] ), new CodeSample( " false, 'include' => [ 'MY_CUSTOM_PI', ], ] ), new CodeSample( " [ 'M_PI', ], ] ), ], null, 'Risky when any of the constants are namespaced or overridden.' ); } public function getPriority() { return 10; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } public function configure(array $configuration = null) { parent::configure($configuration); $uniqueConfiguredExclude = array_unique($this->configuration['exclude']); $constantsToEscape = array_values($this->configuration['include']); if (true === $this->configuration['fix_built_in']) { $getDefinedConstants = get_defined_constants(true); unset($getDefinedConstants['user']); foreach ($getDefinedConstants as $constants) { $constantsToEscape = array_merge($constantsToEscape, array_keys($constants)); } } $constantsToEscape = array_diff( array_unique($constantsToEscape), $uniqueConfiguredExclude ); static $caseInsensitiveConstants = ['null', 'false', 'true']; $caseInsensitiveConstantsToEscape = []; foreach ($constantsToEscape as $constantIndex => $constant) { $loweredConstant = strtolower($constant); if (\in_array($loweredConstant, $caseInsensitiveConstants, true)) { $caseInsensitiveConstantsToEscape[] = $loweredConstant; unset($constantsToEscape[$constantIndex]); } } $caseInsensitiveConstantsToEscape = array_diff( array_unique($caseInsensitiveConstantsToEscape), array_map(static function ($function) { return strtolower($function); }, $uniqueConfiguredExclude) ); $this->constantsToEscape = array_fill_keys($constantsToEscape, true); ksort($this->constantsToEscape); $this->caseInsensitiveConstantsToEscape = array_fill_keys($caseInsensitiveConstantsToEscape, true); ksort($this->caseInsensitiveConstantsToEscape); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if ('all' === $this->configuration['scope']) { $this->fixConstantInvocations($tokens, 0, \count($tokens) - 1); return; } $namespaces = (new NamespacesAnalyzer())->getDeclarations($tokens); foreach (array_reverse($namespaces) as $namespace) { if ('' === $namespace->getFullName()) { continue; } $this->fixConstantInvocations($tokens, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex()); } } protected function createConfigurationDefinition() { $constantChecker = static function ($value) { foreach ($value as $constantName) { if (!\is_string($constantName) || '' === trim($constantName) || trim($constantName) !== $constantName) { throw new InvalidOptionsException(sprintf( 'Each element must be a non-empty, trimmed string, got "%s" instead.', \is_object($constantName) ? \get_class($constantName) : \gettype($constantName) )); } } return true; }; return new FixerConfigurationResolver([ (new FixerOptionBuilder('fix_built_in', 'Whether to fix constants returned by `get_defined_constants`. User constants are not accounted in this list and must be specified in the include one.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('include', 'List of additional constants to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([$constantChecker]) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('exclude', 'List of constants to ignore.')) ->setAllowedTypes(['array']) ->setAllowedValues([$constantChecker]) ->setDefault(['null', 'false', 'true']) ->getOption(), (new FixerOptionBuilder('scope', 'Only fix constant invocations that are made within a namespace or fix all.')) ->setAllowedValues(['all', 'namespaced']) ->setDefault('all') ->getOption(), ]); } private function fixConstantInvocations(Tokens $tokens, $start, $end) { $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); $useConstantDeclarations = []; foreach ($useDeclarations as $use) { if ($use->isConstant()) { $useConstantDeclarations[$use->getShortName()] = true; } } $tokenAnalyzer = new TokensAnalyzer($tokens); $indexes = []; for ($index = $start; $index < $end; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_STRING)) { continue; } $tokenContent = $token->getContent(); if (!isset($this->constantsToEscape[$tokenContent]) && !isset($this->caseInsensitiveConstantsToEscape[strtolower($tokenContent)])) { continue; } if (isset($useConstantDeclarations[$tokenContent])) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { continue; } if (!$tokenAnalyzer->isConstantInvocation($index)) { continue; } $indexes[] = $index; } $indexes = array_reverse($indexes); foreach ($indexes as $index) { $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } } isAllTokenKindsFound([T_CLASS, T_STRING]); } final protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $phpUnitTestCaseIndicator = new PhpUnitTestCaseIndicator(); foreach ($phpUnitTestCaseIndicator->findPhpUnitClasses($tokens) as $indices) { $this->applyPhpUnitClassFix($tokens, $indices[0], $indices[1]); } } abstract protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex); final protected function getDocBlockIndex(Tokens $tokens, $index) { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT])); return $index; } final protected function isPHPDoc(Tokens $tokens, $index) { return $tokens[$index]->isGivenKind(T_DOC_COMMENT); } } ['this' => 'self']] ), ] ); } public function isCandidate(Tokens $tokens) { return \count($tokens) > 10 && $tokens->isTokenKindFound(T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([T_CLASS, T_INTERFACE]); } public function getPriority() { return 10; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { if ('method' === $element['type']) { $this->fixMethod($tokens, $index); } } } protected function createConfigurationDefinition() { $default = [ 'this' => '$this', '@this' => '$this', '$self' => 'self', '@self' => 'self', '$static' => 'static', '@static' => 'static', ]; return new FixerConfigurationResolverRootless('replacements', [ (new FixerOptionBuilder('replacements', 'Mapping between replaced return types with new ones.')) ->setAllowedTypes(['array']) ->setNormalizer(static function (Options $options, $value) use ($default) { $normalizedValue = []; foreach ($value as $from => $to) { if (\is_string($from)) { $from = strtolower($from); } if (!isset($default[$from])) { throw new InvalidOptionsException(sprintf( 'Unknown key "%s", expected any of "%s".', \is_object($from) ? \get_class($from) : \gettype($from).(\is_resource($from) ? '' : '#'.$from), implode('", "', array_keys($default)) )); } if (!\in_array($to, self::$toTypes, true)) { throw new InvalidOptionsException(sprintf( 'Unknown value "%s", expected any of "%s".', \is_object($to) ? \get_class($to) : \gettype($to).(\is_resource($to) ? '' : '#'.$to), implode('", "', self::$toTypes) )); } $normalizedValue[$from] = $to; } return $normalizedValue; }) ->setDefault($default) ->getOption(), ], $this->getName()); } private function fixMethod(Tokens $tokens, $index) { static $methodModifiers = [T_STATIC, T_FINAL, T_ABSTRACT, T_PRIVATE, T_PROTECTED, T_PUBLIC]; do { $tokenIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$tokenIndex]->isGivenKind($methodModifiers)) { break; } $index = $tokenIndex; } while (true); $docIndex = $tokens->getPrevNonWhitespace($index); if (!$tokens[$docIndex]->isGivenKind(T_DOC_COMMENT)) { return; } $docBlock = new DocBlock($tokens[$docIndex]->getContent()); $returnsBlock = $docBlock->getAnnotationsOfType('return'); if (!\count($returnsBlock)) { return; } $returnsBlock = $returnsBlock[0]; $types = $returnsBlock->getTypes(); if (!\count($types)) { return; } $newTypes = []; foreach ($types as $type) { $lower = strtolower($type); $newTypes[] = isset($this->configuration['replacements'][$lower]) ? $this->configuration['replacements'][$lower] : $type; } if ($types === $newTypes) { return; } $returnsBlock->setTypes($newTypes); $tokens[$docIndex] = new Token([T_DOC_COMMENT, $docBlock->getContent()]); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $content = $this->fixStart($content); $content = $this->fixEnd($content); $tokens[$index] = new Token([T_DOC_COMMENT, $content]); } } private function fixStart($content) { return Preg::replace( '~ (^/\*\*) # DocComment begin (?: \R\h*(?:\*\h*)? # lines without useful content (?!\R\h*\*/) # not followed by a DocComment end )+ (\R\h*(?:\*\h*)?\S) # first line with useful content ~x', '$1$2', $content ); } private function fixEnd($content) { return Preg::replace( '~ (\R\h*(?:\*\h*)?\S.*?) # last line with useful content (?: (?isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $this->fixDescription($doc); $this->fixAnnotations($doc); $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } private function fixDescription(DocBlock $doc) { foreach ($doc->getLines() as $index => $line) { if ($line->containsATag()) { break; } if ($line->containsUsefulContent()) { $next = $doc->getLine($index + 1); if (null !== $next && $next->containsATag()) { $line->addBlank(); break; } } } } private function fixAnnotations(DocBlock $doc) { foreach ($doc->getAnnotations() as $index => $annotation) { $next = $doc->getAnnotation($index + 1); if (null === $next) { break; } if (true === $next->getTag()->valid()) { if (TagComparator::shouldBeTogether($annotation->getTag(), $next->getTag())) { $this->ensureAreTogether($doc, $annotation, $next); } else { $this->ensureAreSeparate($doc, $annotation, $next); } } } return $doc->getContent(); } private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second) { $pos = $first->getEnd(); $final = $second->getStart(); for ($pos = $pos + 1; $pos < $final; ++$pos) { $doc->getLine($pos)->remove(); } } private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second) { $pos = $first->getEnd(); $final = $second->getStart() - 1; if ($pos === $final) { $doc->getLine($pos)->addBlank(); return; } for ($pos = $pos + 1; $pos < $final; ++$pos) { $doc->getLine($pos)->remove(); } } } true]), new VersionSpecificCodeSample(' true]), new CodeSample(' true]), ] ); } public function getPriority() { return 6; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $namespaceUseAnalyzer = new NamespaceUsesAnalyzer(); $shortNames = []; foreach ($namespaceUseAnalyzer->getDeclarationsFromTokens($tokens) as $namespaceUseAnalysis) { $shortNames[strtolower($namespaceUseAnalysis->getShortName())] = '\\'.strtolower($namespaceUseAnalysis->getFullName()); } foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $content = $initialContent = $token->getContent(); $documentedElementIndex = $this->findDocumentedElement($tokens, $index); if (null === $documentedElementIndex) { continue; } $token = $tokens[$documentedElementIndex]; if ($this->configuration['remove_inheritdoc']) { $content = $this->removeSuperfluousInheritDoc($content); } if ($token->isGivenKind(T_FUNCTION)) { $content = $this->fixFunctionDocComment($content, $tokens, $index, $shortNames); } elseif ($token->isGivenKind(T_VARIABLE)) { $content = $this->fixPropertyDocComment($content, $tokens, $index, $shortNames); } if ('' === $content) { $content = '/** */'; } if ($content !== $initialContent) { $tokens[$index] = new Token([T_DOC_COMMENT, $content]); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('allow_mixed', 'Whether type `mixed` without description is allowed (`true`) or considered superfluous (`false`)')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('remove_inheritdoc', 'Remove `@inheritDoc` tags')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('allow_unused_params', 'Whether `param` annotation without actual signature is allowed (`true`) or considered superfluous (`false`)')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function findDocumentedElement(Tokens $tokens, $docCommentIndex) { $index = $docCommentIndex; do { $index = $tokens->getNextMeaningfulToken($index); if (null === $index || $tokens[$index]->isGivenKind([T_FUNCTION, T_CLASS, T_INTERFACE])) { return $index; } } while ($tokens[$index]->isGivenKind([T_ABSTRACT, T_FINAL, T_STATIC, T_PRIVATE, T_PROTECTED, T_PUBLIC])); $index = $tokens->getNextMeaningfulToken($docCommentIndex); $kindsBeforeProperty = [T_STATIC, T_PRIVATE, T_PROTECTED, T_PUBLIC, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, T_STRING, T_NS_SEPARATOR]; if (!$tokens[$index]->isGivenKind($kindsBeforeProperty)) { return null; } do { $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->isGivenKind(T_VARIABLE)) { return $index; } } while ($tokens[$index]->isGivenKind($kindsBeforeProperty)); return null; } private function fixFunctionDocComment($content, Tokens $tokens, $functionIndex, array $shortNames) { $docBlock = new DocBlock($content); $openingParenthesisIndex = $tokens->getNextTokenOfKind($functionIndex, ['(']); $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex); $argumentsInfo = $this->getArgumentsInfo( $tokens, $openingParenthesisIndex + 1, $closingParenthesisIndex - 1 ); foreach ($docBlock->getAnnotationsOfType('param') as $annotation) { if (0 === Preg::match('/@param(?:\s+[^\$]\S+)?\s+(\$\S+)/', $annotation->getContent(), $matches)) { continue; } $argumentName = $matches[1]; if (!isset($argumentsInfo[$argumentName]) && $this->configuration['allow_unused_params']) { continue; } if (!isset($argumentsInfo[$argumentName]) || $this->annotationIsSuperfluous($annotation, $argumentsInfo[$argumentName], $shortNames)) { $annotation->remove(); } } $returnTypeInfo = $this->getReturnTypeInfo($tokens, $closingParenthesisIndex); foreach ($docBlock->getAnnotationsOfType('return') as $annotation) { if ($this->annotationIsSuperfluous($annotation, $returnTypeInfo, $shortNames)) { $annotation->remove(); } } return $docBlock->getContent(); } private function fixPropertyDocComment($content, Tokens $tokens, $index, array $shortNames) { $docBlock = new DocBlock($content); do { $index = $tokens->getNextMeaningfulToken($index); } while ($tokens[$index]->isGivenKind([T_STATIC, T_PRIVATE, T_PROTECTED, T_PUBLIC])); $propertyTypeInfo = $this->getPropertyTypeInfo($tokens, $index); foreach ($docBlock->getAnnotationsOfType('var') as $annotation) { if ($this->annotationIsSuperfluous($annotation, $propertyTypeInfo, $shortNames)) { $annotation->remove(); } } return $docBlock->getContent(); } private function getArgumentsInfo(Tokens $tokens, $start, $end) { $argumentsInfo = []; for ($index = $start; $index <= $end; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_VARIABLE)) { continue; } $beforeArgumentIndex = $tokens->getPrevTokenOfKind($index, ['(', ',']); $typeIndex = $tokens->getNextMeaningfulToken($beforeArgumentIndex); if ($typeIndex !== $index) { $info = $this->parseTypeHint($tokens, $typeIndex); } else { $info = [ 'type' => null, 'allows_null' => true, ]; } if (!$info['allows_null']) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ( $tokens[$nextIndex]->equals('=') && $tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals([T_STRING, 'null']) ) { $info['allows_null'] = true; } } $argumentsInfo[$token->getContent()] = $info; } return $argumentsInfo; } private function getReturnTypeInfo(Tokens $tokens, $closingParenthesisIndex) { $colonIndex = $tokens->getNextMeaningfulToken($closingParenthesisIndex); if ($tokens[$colonIndex]->isGivenKind(CT::T_TYPE_COLON)) { return $this->parseTypeHint($tokens, $tokens->getNextMeaningfulToken($colonIndex)); } return [ 'type' => null, 'allows_null' => true, ]; } private function getPropertyTypeInfo(Tokens $tokens, $index) { if ($tokens[$index]->isGivenKind(T_VARIABLE)) { return [ 'type' => null, 'allows_null' => true, ]; } return $this->parseTypeHint($tokens, $index); } private function parseTypeHint(Tokens $tokens, $index) { $allowsNull = false; if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { $allowsNull = true; $index = $tokens->getNextMeaningfulToken($index); } $type = ''; while ($tokens[$index]->isGivenKind([T_NS_SEPARATOR, T_STRING, CT::T_ARRAY_TYPEHINT, T_CALLABLE])) { $type .= $tokens[$index]->getContent(); $index = $tokens->getNextMeaningfulToken($index); } return [ 'type' => '' === $type ? null : $type, 'allows_null' => $allowsNull, ]; } private function annotationIsSuperfluous(Annotation $annotation, array $info, array $symbolShortNames) { if ('param' === $annotation->getTag()->getName()) { $regex = '/@param\s+(?:\S|\s(?!\$))++\s\$\S+\s+\S/'; } elseif ('var' === $annotation->getTag()->getName()) { $regex = '/@var\s+\S+(\s+\$\S+)?(\s+)(?!\*+\/)([^$\s]+)/'; } else { $regex = '/@return\s+\S+\s+\S/'; } if (Preg::match($regex, $annotation->getContent())) { return false; } $annotationTypes = $this->toComparableNames($annotation->getTypes(), $symbolShortNames); if (['null'] === $annotationTypes) { return false; } if (['mixed'] === $annotationTypes && null === $info['type']) { return !$this->configuration['allow_mixed']; } $actualTypes = null === $info['type'] ? [] : [$info['type']]; if ($info['allows_null']) { $actualTypes[] = 'null'; } return $annotationTypes === $this->toComparableNames($actualTypes, $symbolShortNames); } private function toComparableNames(array $types, array $symbolShortNames) { $normalized = array_map( static function ($type) use ($symbolShortNames) { $type = strtolower($type); if (isset($symbolShortNames[$type])) { return $symbolShortNames[$type]; } return $type; }, $types ); sort($normalized); return $normalized; } private function removeSuperfluousInheritDoc($docComment) { return Preg::replace('~ # $1: before @inheritDoc tag ( # beginning of comment or a PHPDoc tag (?: ^/\*\* (?: \R [ \t]*(?:\*[ \t]*)? )*? | @\N+ ) # empty comment lines (?: \R [ \t]*(?:\*[ \t]*?)? )* ) # spaces before @inheritDoc tag [ \t]* # @inheritDoc tag (?:@inheritDocs?|\{@inheritDocs?\}) # $2: after @inheritDoc tag ( # empty comment lines (?: \R [ \t]*(?:\*[ \t]*)? )* # a PHPDoc tag or end of comment (?: @\N+ | (?: \R [ \t]*(?:\*[ \t]*)? )* [ \t]*\*/$ ) ) ~ix', '$1$2', $docComment); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $content = Preg::replaceCallback( '#(?:@{+|{+\h*@)[ \t]*(example|id|internal|inheritdoc|link|source|toc|tutorial)s?([^}]*)(?:}+)#i', static function (array $matches) { $doc = trim($matches[2]); if ('' === $doc) { return '{@'.strtolower($matches[1]).'}'; } return '{@'.strtolower($matches[1]).' '.$doc.'}'; }, $content ); $content = Preg::replace( '#(?isTokenKindFound(T_DOC_COMMENT); } public function getDefinition() { return new FixerDefinition( 'Annotations in PHPDoc should be ordered so that `@param` annotations come first, then `@throws` annotations, then `@return` annotations.', [ new CodeSample( ' $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $content = $this->moveParamAnnotations($content); $content = $this->moveReturnAnnotations($content); $tokens[$index] = new Token([T_DOC_COMMENT, $content]); } } private function moveParamAnnotations($content) { $doc = new DocBlock($content); $params = $doc->getAnnotationsOfType('param'); if (empty($params)) { return $content; } $others = $doc->getAnnotationsOfType(['throws', 'return']); if (empty($others)) { return $content; } $end = end($params)->getEnd(); $line = $doc->getLine($end); foreach ($others as $other) { if ($other->getStart() < $end) { $line->setContent($line->getContent().$other->getContent()); $other->remove(); } } return $doc->getContent(); } private function moveReturnAnnotations($content) { $doc = new DocBlock($content); $returns = $doc->getAnnotationsOfType('return'); if (empty($returns)) { return $content; } $others = $doc->getAnnotationsOfType(['param', 'throws']); if (empty($others)) { return $content; } $start = $returns[0]->getStart(); $line = $doc->getLine($start); foreach (array_reverse($others) as $other) { if ($other->getEnd() > $start) { $line->setContent($other->getContent().$line->getContent()); $other->remove(); } } return $doc->getContent(); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } if (Preg::match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } } } configure(['annotations' => ['package', 'subpackage']]); return [$fixer]; } } 'always_last'] ), new CodeSample( ' 'alpha'] ), new CodeSample( ' 'alpha', 'null_adjustment' => 'always_last', ] ), new CodeSample( ' 'alpha', 'null_adjustment' => 'none', ] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('sort_algorithm', 'The sorting algorithm to apply.')) ->setAllowedValues(['alpha', 'none']) ->setDefault('alpha') ->getOption(), (new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).')) ->setAllowedValues(['always_first', 'always_last', 'none']) ->setDefault('always_first') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); if (!\count($annotations)) { continue; } foreach ($annotations as $annotation) { $types = $annotation->getTypes(); $annotation->setTypes($this->sortTypes($types)); $line = $doc->getLine($annotation->getStart()); $line->setContent(Preg::replaceCallback('/(@method\s+.+?\s+\w+\()(.*)\)/', function (array $matches) { $sorted = Preg::replaceCallback('/([^\s,]+)([\s]+\$[^\s,]+)/', function (array $matches) { return $this->sortJoinedTypes($matches[1]).$matches[2]; }, $matches[2]); return $matches[1].$sorted.')'; }, $line->getContent())); } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } private function sortTypes(array $types) { foreach ($types as $index => $type) { $types[$index] = Preg::replaceCallback('/^([^<]+)<(?:([\w\|]+?)(,\s*))?(.*)>$/', function (array $matches) { return $matches[1].'<'.$this->sortJoinedTypes($matches[2]).$matches[3].$this->sortJoinedTypes($matches[4]).'>'; }, $type); } if ('alpha' === $this->configuration['sort_algorithm']) { $types = Utils::stableSort( $types, static function ($type) { return $type; }, static function ($typeA, $typeB) { $regexp = '/^\\??\\\?/'; return strcasecmp( Preg::replace($regexp, '', $typeA), Preg::replace($regexp, '', $typeB) ); } ); } if ('none' !== $this->configuration['null_adjustment']) { $nulls = []; foreach ($types as $index => $type) { if (Preg::match('/^\\\?null$/i', $type)) { $nulls[$index] = $type; unset($types[$index]); } } if (\count($nulls)) { if ('always_last' === $this->configuration['null_adjustment']) { array_push($types, ...$nulls); } else { array_unshift($types, ...$nulls); } } } return $types; } private function sortJoinedTypes($types) { $types = array_filter( Preg::split('/([^|<]+(?:<.*>)?)/', $types, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY), static function ($value) { return '|' !== $value; } ); return implode('|', $this->sortTypes($types)); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } if (false === stripos($token->getContent(), '@var') && false === stripos($token->getContent(), '@type')) { continue; } $newContent = Preg::replace( '/(@(?:type|var)\s*)(\$\S+)(\h+)([^\$](?:[^<\s]|<[^>]*>)*)(\s|\*)/i', '$1$4$3$2$5', $token->getContent() ); if ($newContent === $token->getContent()) { continue; } $tokens[$index] = new Token([$token->getId(), $newContent]); } } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $end = (new ShortDescription($doc))->getEnd(); if (null !== $end) { $line = $doc->getLine($end); $content = rtrim($line->getContent()); if (!$this->isCorrectlyFormatted($content)) { $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding()); $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } } } private function isCorrectlyFormatted($content) { if (false !== stripos($content, '{@inheritdoc}')) { return true; } return $content !== rtrim($content, '.。!?¡¿!?'); } } [ 'array', 'bool', 'callable', 'float', 'int', 'iterable', 'null', 'object', 'string', ], 'alias' => [ 'boolean', 'callback', 'double', 'integer', 'real', ], 'meta' => [ '$this', 'false', 'mixed', 'parent', 'resource', 'scalar', 'self', 'static', 'true', 'void', ], ]; private $typesToFix = []; public function configure(array $configuration = null) { parent::configure($configuration); $this->typesToFix = array_merge(...array_map(static function ($group) { return self::$possibleTypes[$group]; }, $this->configuration['groups'])); } public function getDefinition() { return new FixerDefinition( 'The correct case must be used for standard PHP types in PHPDoc.', [ new CodeSample( ' ['simple', 'alias']] ), ] ); } public function getPriority() { return 16; } protected function normalize($type) { $lower = strtolower($type); if (\in_array($lower, $this->typesToFix, true)) { return $lower; } return $type; } protected function createConfigurationDefinition() { $possibleGroups = array_keys(self::$possibleTypes); return new FixerConfigurationResolver([ (new FixerOptionBuilder('groups', 'Type groups to fix.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($possibleGroups)]) ->setDefault($possibleGroups) ->getOption(), ]); } } isTokenKindFound(T_DOC_COMMENT); } public function getDefinition() { return new FixerDefinition( 'No alias PHPDoc tags should be used.', [ new CodeSample( ' ['link' => 'website']] ), ] ); } public function getPriority() { return 11; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $searchFor = array_keys($this->configuration['replacements']); foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType($searchFor); if (empty($annotations)) { continue; } foreach ($annotations as $annotation) { $annotation->getTag()->setName($this->configuration['replacements'][$annotation->getTag()->getName()]); } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('replacements', [ (new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.')) ->setAllowedTypes(['array']) ->setNormalizer(static function (Options $options, $value) { $normalizedValue = []; foreach ($value as $from => $to) { if (!\is_string($from)) { throw new InvalidOptionsException('Tag to replace must be a string.'); } if (!\is_string($to)) { throw new InvalidOptionsException(sprintf( 'Tag to replace to from "%s" must be a string.', $from )); } if (1 !== Preg::match('#^\S+$#', $to) || false !== strpos($to, '*/')) { throw new InvalidOptionsException(sprintf( 'Tag "%s" cannot be replaced by invalid tag "%s".', $from, $to )); } $normalizedValue[trim($from)] = trim($to); } foreach ($normalizedValue as $from => $to) { if (isset($normalizedValue[$to])) { throw new InvalidOptionsException(sprintf( 'Cannot change tag "%1$s" to tag "%2$s", as the tag "%2$s" is configured to be replaced to "%3$s".', $from, $to, $normalizedValue[$to] )); } } return $normalizedValue; }) ->setDefault([ 'property-read' => 'property', 'property-write' => 'property', 'type' => 'var', 'link' => 'see', ]) ->getOption(), ], $this->getName()); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { continue; } $prevIndex = $index - 1; $prevToken = $tokens[$prevIndex]; if ( $prevToken->isGivenKind(T_OPEN_TAG) || ($prevToken->isWhitespace(" \t") && !$tokens[$index - 2]->isGivenKind(T_OPEN_TAG)) || $prevToken->equalsAny([';', ',', '{', '(']) ) { continue; } $indent = ''; if ($tokens[$nextIndex - 1]->isWhitespace()) { $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]); } $newPrevContent = $this->fixWhitespaceBeforeDocblock($prevToken->getContent(), $indent); if ($newPrevContent) { if ($prevToken->isArray()) { $tokens[$prevIndex] = new Token([$prevToken->getId(), $newPrevContent]); } else { $tokens[$prevIndex] = new Token($newPrevContent); } } else { $tokens->clearAt($prevIndex); } $tokens[$index] = new Token([T_DOC_COMMENT, $this->fixDocBlock($token->getContent(), $indent)]); } } private function fixDocBlock($content, $indent) { return ltrim(Preg::replace('/^\h*\*/m', $indent.' *', $content)); } private function fixWhitespaceBeforeDocblock($content, $indent) { return rtrim($content, " \t").$indent; } } configuration['tags'], self::$tagsWithName); $tagsWithMethodSignatureToAlign = array_intersect($this->configuration['tags'], self::$tagsWithMethodSignature); $tagsWithoutNameToAlign = array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign); $types = []; $indent = '(?P(?: {2}|\t)*)'; if (!empty($tagsWithNameToAlign)) { $types[] = '(?P'.implode('|', $tagsWithNameToAlign).')\s+(?P[^$]+?)\s+(?P(?:&|\.{3})?\$[^\s]+)'; } if (!empty($tagsWithoutNameToAlign)) { $types[] = '(?P'.implode('|', $tagsWithoutNameToAlign).')\s+(?P[^\s]+?)'; } if (!empty($tagsWithMethodSignatureToAlign)) { $types[] = '(?P'.implode('|', $tagsWithMethodSignatureToAlign).')(\s+(?P[^\s(]+)|)\s+(?P.+\))'; } $desc = '(?:\s+(?P\V*))'; $this->regex = '/^'.$indent.' \* @(?:'.implode('|', $types).')'.$desc.'\s*$/u'; $this->regexCommentLine = '/^'.$indent.' \*(?! @)(?:\s+(?P\V+))(?align = $this->configuration['align']; } public function getDefinition() { $code = <<<'EOF' self::ALIGN_VERTICAL]), new CodeSample($code, ['align' => self::ALIGN_LEFT]), ] ); } public function getPriority() { return -42; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $docBlock = new DocBlock($content); $this->fixDocBlock($docBlock); $newContent = $docBlock->getContent(); if ($newContent !== $content) { $tokens[$index] = new Token([T_DOC_COMMENT, $newContent]); } } } protected function createConfigurationDefinition() { $tags = new FixerOptionBuilder('tags', 'The tags that should be aligned.'); $tags ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(self::$alignableTags)]) ->setDefault([ 'param', 'return', 'throws', 'type', 'var', ]) ; $align = new FixerOptionBuilder('align', 'Align comments'); $align ->setAllowedTypes(['string']) ->setAllowedValues([self::ALIGN_LEFT, self::ALIGN_VERTICAL]) ->setDefault(self::ALIGN_VERTICAL) ; return new FixerConfigurationResolver([$tags->getOption(), $align->getOption()]); } private function fixDocBlock(DocBlock $docBlock) { $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($i = 0, $l = \count($docBlock->getLines()); $i < $l; ++$i) { $items = []; $matches = $this->getMatches($docBlock->getLine($i)->getContent()); if (null === $matches) { continue; } $current = $i; $items[] = $matches; while (true) { if (null === $docBlock->getLine(++$i)) { break 2; } $matches = $this->getMatches($docBlock->getLine($i)->getContent(), true); if (null === $matches) { break; } $items[] = $matches; } $tagMax = 0; $hintMax = 0; $varMax = 0; foreach ($items as $item) { if (null === $item['tag']) { continue; } $tagMax = max($tagMax, \strlen($item['tag'])); $hintMax = max($hintMax, \strlen($item['hint'])); $varMax = max($varMax, \strlen($item['var'])); } $currTag = null; foreach ($items as $j => $item) { if (null === $item['tag']) { if ('@' === $item['desc'][0]) { $docBlock->getLine($current + $j)->setContent($item['indent'].' * '.$item['desc'].$lineEnding); continue; } $extraIndent = 2; if (\in_array($currTag, self::$tagsWithName, true) || \in_array($currTag, self::$tagsWithMethodSignature, true)) { $extraIndent = 3; } $line = $item['indent'] .' * ' .$this->getIndent( $tagMax + $hintMax + $varMax + $extraIndent, $this->getLeftAlignedDescriptionIndent($items, $j) ) .$item['desc'] .$lineEnding; $docBlock->getLine($current + $j)->setContent($line); continue; } $currTag = $item['tag']; $line = $item['indent'] .' * @' .$item['tag'] .$this->getIndent( $tagMax - \strlen($item['tag']) + 1, $item['hint'] ? 1 : 0 ) .$item['hint'] ; if (!empty($item['var'])) { $line .= $this->getIndent(($hintMax ?: -1) - \strlen($item['hint']) + 1) .$item['var'] .( !empty($item['desc']) ? $this->getIndent($varMax - \strlen($item['var']) + 1).$item['desc'].$lineEnding : $lineEnding ) ; } elseif (!empty($item['desc'])) { $line .= $this->getIndent($hintMax - \strlen($item['hint']) + 1).$item['desc'].$lineEnding; } else { $line .= $lineEnding; } $docBlock->getLine($current + $j)->setContent($line); } } } private function getMatches($line, $matchCommentOnly = false) { if (Preg::match($this->regex, $line, $matches)) { if (!empty($matches['tag2'])) { $matches['tag'] = $matches['tag2']; $matches['hint'] = $matches['hint2']; $matches['var'] = ''; } if (!empty($matches['tag3'])) { $matches['tag'] = $matches['tag3']; $matches['hint'] = $matches['hint3']; $matches['var'] = $matches['signature']; } if (isset($matches['hint'])) { $matches['hint'] = trim($matches['hint']); } return $matches; } if ($matchCommentOnly && Preg::match($this->regexCommentLine, $line, $matches)) { $matches['tag'] = null; $matches['var'] = ''; $matches['hint'] = ''; return $matches; } return null; } private function getIndent($verticalAlignIndent, $leftAlignIndent = 1) { $indent = self::ALIGN_VERTICAL === $this->align ? $verticalAlignIndent : $leftAlignIndent; return str_repeat(' ', $indent); } private function getLeftAlignedDescriptionIndent(array $items, $index) { if (self::ALIGN_LEFT !== $this->align) { return 0; } $item = null; for (; $index >= 0; --$index) { $item = $items[$index]; if (null !== $item['tag']) { break; } } if (null === $item) { return 0; } return $this->getSentenceIndent($item['tag']) + $this->getSentenceIndent($item['hint']) + $this->getSentenceIndent($item['var']); } private function getSentenceIndent($sentence) { if (null === $sentence) { return 0; } $length = \strlen($sentence); return 0 === $length ? 0 : $length + 1; } } isTokenKindFound(T_DOC_COMMENT); } public function getDefinition() { return new FixerDefinition( 'There should not be blank lines between docblock and the documented element.', [ new CodeSample( ' $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $next = $tokens->getNextNonWhitespace($index); if ($index + 2 === $next && false === $tokens[$next]->isGivenKind($forbiddenSuccessors)) { $this->fixWhitespace($tokens, $index + 1); } } } private function fixWhitespace(Tokens $tokens, $index) { $content = $tokens[$index]->getContent(); if (substr_count($content, "\n") > 1) { $tokens[$index] = new Token([T_WHITESPACE, substr($content, strrpos($content, "\n"))]); } } } 'single'] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('const', 'Whether const blocks should be single or multi line')) ->setAllowedValues(['single', 'multi']) ->setDefault('multi') ->getOption(), (new FixerOptionBuilder('property', 'Whether property doc blocks should be single or multi line')) ->setAllowedValues(['single', 'multi']) ->setDefault('multi') ->getOption(), (new FixerOptionBuilder('method', 'Whether method doc blocks should be single or multi line')) ->setAllowedValues(['single', 'multi']) ->setDefault('multi') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $analyzer = new TokensAnalyzer($tokens); $elements = $analyzer->getClassyElements(); foreach ($elements as $index => $element) { if (!$this->hasDocBlock($tokens, $index)) { continue; } $type = $element['type']; $docIndex = $this->getDocBlockIndex($tokens, $index); $doc = new DocBlock($tokens[$docIndex]->getContent()); if ('multi' === $this->configuration[$type]) { $doc->makeMultiLine($originalIndent = $this->detectIndent($tokens, $docIndex), $this->whitespacesConfig->getLineEnding()); } else { $doc->makeSingleLine(); } $tokens->offsetSet($docIndex, new Token([T_DOC_COMMENT, $doc->getContent()])); } } private function hasDocBlock(Tokens $tokens, $index) { $docBlockIndex = $this->getDocBlockIndex($tokens, $index); return $tokens[$docBlockIndex]->isGivenKind(T_DOC_COMMENT); } private function getDocBlockIndex(Tokens $tokens, $index) { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([ T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT, T_VAR, T_STATIC, T_STRING, T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE, ])); return $index; } private function detectIndent(Tokens $tokens, $index) { if (!$tokens[$index - 1]->isWhitespace()) { return ''; } $explodedContent = explode($this->whitespacesConfig->getLineEnding(), $tokens[$index - 1]->getContent()); return end($explodedContent); } } isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isComment()) { continue; } $content = $token->getContent(); $fixedContent = $this->fixTokenContent($content); if ($content !== $fixedContent) { $tokens[$index] = new Token([T_DOC_COMMENT, $fixedContent]); } } } private function fixTokenContent($content) { return Preg::replaceCallback( '#^/\*\*\h*@var\h+(\S+)\h*(\$\S+)?\h*([^\n]*)\*/$#', static function (array $matches) { $content = '/** @var'; for ($i = 1, $m = \count($matches); $i < $m; ++$i) { if ('' !== $matches[$i]) { $content .= ' '.$matches[$i]; } } return rtrim($content).' */'; }, $content ); } } 'bool', 'callback' => 'callable', 'double' => 'float', 'integer' => 'int', 'real' => 'float', 'str' => 'string', ]; public function getDefinition() { return new FixerDefinition( 'Scalar types should always be written in the same form. `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`.', [ new CodeSample(' ['boolean']] ), ] ); } public function getPriority() { return 15; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('types', 'A map of types to fix.')) ->setAllowedValues([new AllowedValueSubset(array_keys(self::$types))]) ->setDefault(['boolean', 'double', 'integer', 'real', 'str']) ->getOption(), ]); } protected function normalize($type) { if (\in_array($type, $this->configuration['types'], true)) { return self::$types[$type]; } return $type; } } ['author']] ), new CodeSample( ' ['package', 'subpackage']] ), ] ); } public function getPriority() { return 10; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if (!\count($this->configuration['annotations'])) { return; } foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType($this->configuration['annotations']); if (empty($annotations)) { continue; } foreach ($annotations as $annotation) { $annotation->remove(); } if ('' === $doc->getContent()) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } else { $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('annotations', [ (new FixerOptionBuilder('annotations', 'List of annotations to remove, e.g. `["author"]`.')) ->setAllowedTypes(['array']) ->setDefault([]) ->getOption(), ], $this->getName()); } } configure(['annotations' => ['access']]); return [$fixer]; } } isTokenKindFound(T_DOC_COMMENT); } public function getDefinition() { return new FixerDefinition( '`@return void` and `@return null` annotations should be omitted from PHPDoc.', [ new CodeSample( ' $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType('return'); if (empty($annotations)) { continue; } foreach ($annotations as $annotation) { $this->fixAnnotation($doc, $annotation); } $newContent = $doc->getContent(); if ($newContent === $token->getContent()) { continue; } if ('' === $newContent) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); continue; } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } private function fixAnnotation(DocBlock $doc, Annotation $annotation) { $types = $annotation->getNormalizedTypes(); if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) { $annotation->remove(); } } } isTokenKindFound(T_DOC_COMMENT); } public function getPriority() { return 25; } public function getDefinition() { return new FixerDefinition( 'Docblocks should only be used on structural elements.', [ new CodeSample( ' $sqlite) { $sqlite->open($path); } ' ), ] ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $commentsAnalyzer = new CommentsAnalyzer(); foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { continue; } if ($commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { continue; } $tokens[$index] = new Token([T_COMMENT, '/*'.ltrim($token->getContent(), '/*')]); } } } isTokenKindFound(T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([T_CLASS, T_INTERFACE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 1, $count = \count($tokens) - 4; $index < $count; ++$index) { if ($tokens[$index]->isGivenKind([T_CLASS, T_INTERFACE])) { $index = $this->fixClassy($tokens, $index); } } } private function fixClassy(Tokens $tokens, $index) { $classOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); $extendingOrImplementing = $this->isExtendingOrImplementing($tokens, $index, $classOpenIndex); if (!$extendingOrImplementing) { $this->fixClassyOutside($tokens, $index); } if (!$extendingOrImplementing && $this->isUsingTrait($tokens, $index, $classOpenIndex, $classEndIndex)) { $extendingOrImplementing = true; } $this->fixClassyInside($tokens, $classOpenIndex, $classEndIndex, !$extendingOrImplementing); return $classEndIndex; } private function fixClassyInside(Tokens $tokens, $classOpenIndex, $classEndIndex, $fixThisLevel) { for ($i = $classOpenIndex; $i < $classEndIndex; ++$i) { if ($tokens[$i]->isGivenKind(T_CLASS)) { $i = $this->fixClassy($tokens, $i); } elseif ($fixThisLevel && $tokens[$i]->isGivenKind(T_DOC_COMMENT)) { $this->fixToken($tokens, $i); } } } private function fixClassyOutside(Tokens $tokens, $classIndex) { $previousIndex = $tokens->getPrevNonWhitespace($classIndex); if ($tokens[$previousIndex]->isGivenKind(T_DOC_COMMENT)) { $this->fixToken($tokens, $previousIndex); } } private function fixToken(Tokens $tokens, $tokenIndex) { $count = 0; $content = Preg::replaceCallback( '#(\h*(?:@{*|{*\h*@)\h*inheritdoc\h*)([^}]*)((?:}*)\h*)#i', static function ($matches) { return ' '.$matches[2]; }, $tokens[$tokenIndex]->getContent(), -1, $count ); if ($count) { $tokens[$tokenIndex] = new Token([T_DOC_COMMENT, $content]); } } private function isExtendingOrImplementing(Tokens $tokens, $classIndex, $classOpenIndex) { for ($index = $classIndex; $index < $classOpenIndex; ++$index) { if ($tokens[$index]->isGivenKind([T_EXTENDS, T_IMPLEMENTS])) { return true; } } return false; } private function isUsingTrait(Tokens $tokens, $classIndex, $classOpenIndex, $classCloseIndex) { if ($tokens[$classIndex]->isGivenKind(T_INTERFACE)) { return false; } $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); return null !== $useIndex && $useIndex < $classCloseIndex; } } tokenKinds = [T_DOC_COMMENT]; if ('phpdocs_only' !== $this->configuration['comment_type']) { $this->tokenKinds[] = T_COMMENT; } } public function getDefinition() { return new FixerDefinition( 'Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one.', [ new CodeSample( ' 'phpdocs_like'] ), new CodeSample( ' 'all_multiline'] ), ] ); } public function getPriority() { return -40; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound($this->tokenKinds); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $lineEnding = $this->whitespacesConfig->getLineEnding(); foreach ($tokens as $index => $token) { if (!$token->isGivenKind($this->tokenKinds)) { continue; } $whitespace = ''; $previousIndex = $index - 1; if ($tokens[$previousIndex]->isWhitespace()) { $whitespace = $tokens[$previousIndex]->getContent(); --$previousIndex; } if ($tokens[$previousIndex]->isGivenKind(T_OPEN_TAG)) { $whitespace = Preg::replace('/\S/', '', $tokens[$previousIndex]->getContent()).$whitespace; } if (1 !== Preg::match('/\R(\h*)$/', $whitespace, $matches)) { continue; } if ($token->isGivenKind(T_COMMENT) && 'all_multiline' !== $this->configuration['comment_type'] && 1 === Preg::match('/\R(?:\R|\s*[^\s\*])/', $token->getContent())) { continue; } $indentation = $matches[1]; $lines = Preg::split('/\R/u', $token->getContent()); foreach ($lines as $lineNumber => $line) { if (0 === $lineNumber) { continue; } $line = ltrim($line); if ($token->isGivenKind(T_COMMENT) && (!isset($line[0]) || '*' !== $line[0])) { continue; } if (!isset($line[0])) { $line = '*'; } elseif ('*' !== $line[0]) { $line = '* '.$line; } $lines[$lineNumber] = $indentation.' '.$line; } $tokens[$index] = new Token([$token->getId(), implode($lineEnding, $lines)]); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('comment_type', 'Whether to fix PHPDoc comments only (`phpdocs_only`), any multi-line comment whose lines all start with an asterisk (`phpdocs_like`) or any multi-line comment (`all_multiline`).')) ->setAllowedValues(['phpdocs_only', 'phpdocs_like', 'all_multiline']) ->setDefault('phpdocs_only') ->getOption(), ]); } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotations(); if (empty($annotations)) { continue; } foreach ($annotations as $annotation) { if ( !$annotation->getTag()->valid() || !\in_array($annotation->getTag()->getName(), $this->tags, true) ) { continue; } $lineAfterAnnotation = $doc->getLine($annotation->getEnd() + 1); if (null !== $lineAfterAnnotation) { $lineAfterAnnotationTrimmed = ltrim($lineAfterAnnotation->getContent()); if ('' === $lineAfterAnnotationTrimmed || '*' !== $lineAfterAnnotationTrimmed[0]) { continue; } } $content = $annotation->getContent(); if ( 1 !== Preg::match('/[.。]\h*$/u', $content) || 0 !== Preg::match('/[.。](?!\h*$)/u', $content, $matches) ) { continue; } $endLine = $doc->getLine($annotation->getEnd()); $endLine->setContent(Preg::replace('/(?getContent())); $startLine = $doc->getLine($annotation->getStart()); $optionalTypeRegEx = $annotation->supportTypes() ? sprintf('(?:%s\s+(?:\$\w+\s+)?)?', preg_quote(implode('|', $annotation->getTypes()), '/')) : ''; $content = Preg::replaceCallback( '/^(\s*\*\s*@\w+\s+'.$optionalTypeRegEx.')(\p{Lu}?(?=\p{Ll}|\p{Zs}))(.*)$/', static function (array $matches) { if (\function_exists('mb_strtolower')) { return $matches[1].mb_strtolower($matches[2]).$matches[3]; } return $matches[1].strtolower($matches[2]).$matches[3]; }, $startLine->getContent(), 1 ); $startLine->setContent($content); } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } } true] ), new CodeSample( ' false] ), ] ); } public function getPriority() { return 10; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $tokenContent = $token->getContent(); if (false !== stripos($tokenContent, 'inheritdoc')) { continue; } if (false === strpos($tokenContent, "\n")) { continue; } $mainIndex = $index; $index = $tokens->getNextMeaningfulToken($index); if (null === $index) { return; } while ($tokens[$index]->isGivenKind([ T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR, ])) { $index = $tokens->getNextMeaningfulToken($index); } if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $arguments = []; foreach ($argumentsAnalyzer->getArguments($tokens, $openIndex, $index) as $start => $end) { $argumentInfo = $this->prepareArgumentInformation($tokens, $start, $end); if (!$this->configuration['only_untyped'] || '' === $argumentInfo['type']) { $arguments[$argumentInfo['name']] = $argumentInfo; } } if (!\count($arguments)) { continue; } $doc = new DocBlock($tokenContent); $lastParamLine = null; foreach ($doc->getAnnotationsOfType('param') as $annotation) { $pregMatched = Preg::match('/^[^$]+(\$\w+).*$/s', $annotation->getContent(), $matches); if (1 === $pregMatched) { unset($arguments[$matches[1]]); } $lastParamLine = max($lastParamLine, $annotation->getEnd()); } if (!\count($arguments)) { continue; } $lines = $doc->getLines(); $linesCount = \count($lines); Preg::match('/^(\s*).*$/', $lines[$linesCount - 1]->getContent(), $matches); $indent = $matches[1]; $newLines = []; foreach ($arguments as $argument) { $type = $argument['type'] ?: 'mixed'; if ('?' !== $type[0] && 'null' === strtolower($argument['default'])) { $type = 'null|'.$type; } $newLines[] = new Line(sprintf( '%s* @param %s %s%s', $indent, $type, $argument['name'], $this->whitespacesConfig->getLineEnding() )); } array_splice( $lines, $lastParamLine ? $lastParamLine + 1 : $linesCount - 1, 0, $newLines ); $tokens[$mainIndex] = new Token([T_DOC_COMMENT, implode('', $lines)]); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('only_untyped', 'Whether to add missing `@param` annotations for untyped parameters only.')) ->setDefault(true) ->setAllowedTypes(['bool']) ->getOption(), ]); } private function prepareArgumentInformation(Tokens $tokens, $start, $end) { $info = [ 'default' => '', 'name' => '', 'type' => '', ]; $sawName = false; for ($index = $start; $index <= $end; ++$index) { $token = $tokens[$index]; if ($token->isComment() || $token->isWhitespace()) { continue; } if ($token->isGivenKind(T_VARIABLE)) { $sawName = true; $info['name'] = $token->getContent(); continue; } if ($token->equals('=')) { continue; } if ($sawName) { $info['default'] .= $token->getContent(); } elseif ('&' !== $token->getContent()) { if ($token->isGivenKind(T_ELLIPSIS)) { if ('' === $info['type']) { $info['type'] = 'array'; } else { $info['type'] .= '[]'; } } else { $info['type'] .= $token->getContent(); } } } return $info; } } isTokenKindFound(T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); if (null === $nextIndex) { continue; } if ($tokens[$nextIndex]->isGivenKind(T_STATIC)) { $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); } if (!$tokens[$nextIndex]->isGivenKind([T_PRIVATE, T_PROTECTED, T_PUBLIC, T_VAR])) { continue; } $doc = new DocBlock($token->getContent()); $firstLevelLines = $this->getFirstLevelLines($doc); $annotations = $doc->getAnnotationsOfType(['type', 'var']); foreach ($annotations as $annotation) { if (isset($firstLevelLines[$annotation->getStart()])) { $this->fixLine($firstLevelLines[$annotation->getStart()]); } } $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } private function fixLine(Line $line) { $content = $line->getContent(); Preg::matchAll('/ \$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $content, $matches); if (isset($matches[0][0])) { $line->setContent(str_replace($matches[0][0], '', $content)); } } private function getFirstLevelLines(DocBlock $docBlock) { $nested = 0; $lines = $docBlock->getLines(); foreach ($lines as $index => $line) { $content = $line->getContent(); if (Preg::match('/\s*\*\s*}$/', $content)) { --$nested; } if ($nested > 0) { unset($lines[$index]); } if (Preg::match('/\s\{$/', $content)) { ++$nested; } } return $lines; } } isTokenKindFound(T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $summaryEnd = (new ShortDescription($doc))->getEnd(); if (null !== $summaryEnd) { $this->fixSummary($doc, $summaryEnd); $this->fixDescription($doc, $summaryEnd); } $this->fixAllTheRest($doc); $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); } } private function fixSummary(DocBlock $doc, $summaryEnd) { $nonBlankLineAfterSummary = $this->findNonBlankLine($doc, $summaryEnd); $this->removeExtraBlankLinesBetween($doc, $summaryEnd, $nonBlankLineAfterSummary); } private function fixDescription(DocBlock $doc, $summaryEnd) { $annotationStart = $this->findFirstAnnotationOrEnd($doc); $descriptionEnd = $this->reverseFindLastUsefulContent($doc, $annotationStart); if (null === $descriptionEnd || $summaryEnd === $descriptionEnd) { return; } if ($annotationStart === \count($doc->getLines()) - 1) { return; } $this->removeExtraBlankLinesBetween($doc, $descriptionEnd, $annotationStart); } private function fixAllTheRest(DocBlock $doc) { $annotationStart = $this->findFirstAnnotationOrEnd($doc); $lastLine = $this->reverseFindLastUsefulContent($doc, \count($doc->getLines()) - 1); if (null !== $lastLine && $annotationStart !== $lastLine) { $this->removeExtraBlankLinesBetween($doc, $annotationStart, $lastLine); } } private function removeExtraBlankLinesBetween(DocBlock $doc, $from, $to) { for ($index = $from + 1; $index < $to; ++$index) { $line = $doc->getLine($index); $next = $doc->getLine($index + 1); $this->removeExtraBlankLine($line, $next); } } private function removeExtraBlankLine(Line $current, Line $next) { if (!$current->isTheEnd() && !$current->containsUsefulContent() && !$next->isTheEnd() && !$next->containsUsefulContent()) { $current->remove(); } } private function findNonBlankLine(DocBlock $doc, $after) { foreach ($doc->getLines() as $index => $line) { if ($index <= $after) { continue; } if ($line->containsATag() || $line->containsUsefulContent() || $line->isTheEnd()) { return $index; } } return null; } private function findFirstAnnotationOrEnd(DocBlock $doc) { $index = null; foreach ($doc->getLines() as $index => $line) { if ($line->containsATag()) { return $index; } } return $index; } private function reverseFindLastUsefulContent(DocBlock $doc, $from) { for ($index = $from - 1; $index >= 0; --$index) { if ($doc->getLine($index)->containsUsefulContent()) { return $index; } } return null; } } isAnyTokenKindsFound([T_LOGICAL_AND, T_LOGICAL_OR]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isGivenKind(T_LOGICAL_AND)) { $tokens[$index] = new Token([T_BOOLEAN_AND, '&&']); } elseif ($token->isGivenKind(T_LOGICAL_OR)) { $tokens[$index] = new Token([T_BOOLEAN_OR, '||']); } } } } configuration['spacing']) { $this->fixCallback = 'fixConcatenationToSingleSpace'; } else { $this->fixCallback = 'fixConcatenationToNoSpace'; } } public function getDefinition() { return new FixerDefinition( 'Concatenation should be spaced according configuration.', [ new CodeSample( " 'none'] ), new CodeSample( " 'one'] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound('.'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $callBack = $this->fixCallback; for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokens[$index]->equals('.')) { $this->{$callBack}($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('spacing', 'Spacing to apply around concatenation operator.')) ->setAllowedValues(['one', 'none']) ->setDefault('none') ->getOption(), ]); } private function fixConcatenationToNoSpace(Tokens $tokens, $index) { $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; if (!$prevNonWhitespaceToken->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT]) || '/*' === substr($prevNonWhitespaceToken->getContent(), 0, 2)) { $tokens->removeLeadingWhitespace($index, " \t"); } if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT])) { $tokens->removeTrailingWhitespace($index, " \t"); } } private function fixConcatenationToSingleSpace(Tokens $tokens, $index) { $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1); $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1); } private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, $index, $offset) { $offsetIndex = $index + $offset; if (!$tokens[$offsetIndex]->isWhitespace()) { $tokens->insertAt($index + (1 === $offset ?: 0), new Token([T_WHITESPACE, ' '])); return; } if (false !== strpos($tokens[$offsetIndex]->getContent(), "\n")) { return; } if ($tokens[$index + $offset * 2]->isComment()) { return; } $tokens[$offsetIndex] = new Token([T_WHITESPACE, ' ']); } } isTokenKindFound('!'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ($token->equals('!')) { if (!$tokens[$index + 1]->isWhitespace()) { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } if (!$tokens[$index - 1]->isWhitespace()) { $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); } } } } } isTokenKindFound(T_NEW); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $nextTokenKinds = null; if (null === $nextTokenKinds) { $nextTokenKinds = [ '?', ';', ',', '(', ')', '[', ']', ':', '<', '>', '+', '-', '*', '/', '%', '&', '^', '|', [T_CLASS], [T_IS_SMALLER_OR_EQUAL], [T_IS_GREATER_OR_EQUAL], [T_IS_EQUAL], [T_IS_NOT_EQUAL], [T_IS_IDENTICAL], [T_IS_NOT_IDENTICAL], [T_CLOSE_TAG], [T_LOGICAL_AND], [T_LOGICAL_OR], [T_LOGICAL_XOR], [T_BOOLEAN_AND], [T_BOOLEAN_OR], [T_SL], [T_SR], [T_INSTANCEOF], [T_AS], [T_DOUBLE_ARROW], [T_POW], [CT::T_ARRAY_SQUARE_BRACE_OPEN], [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_BRACE_CLASS_INSTANTIATION_OPEN], [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE], ]; if (\defined('T_SPACESHIP')) { $nextTokenKinds[] = [T_SPACESHIP]; } } for ($index = $tokens->count() - 3; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_NEW)) { continue; } $nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds); $nextToken = $tokens[$nextIndex]; if ($nextToken->isGivenKind(T_CLASS)) { if (!$tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals('(')) { $this->insertBracesAfter($tokens, $nextIndex); } continue; } while ($nextToken->equals('[') || $nextToken->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) { $nextIndex = $tokens->findBlockEnd($tokens->detectBlockType($nextToken)['type'], $nextIndex) + 1; $nextToken = $tokens[$nextIndex]; } if ($nextToken->isWhitespace()) { $nextIndex = $tokens->getNextNonWhitespace($nextIndex); $nextToken = $tokens[$nextIndex]; } if ($nextToken->equals('(') || $nextToken->isGivenKind(T_OBJECT_OPERATOR)) { continue; } $this->insertBracesAfter($tokens, $tokens->getPrevMeaningfulToken($nextIndex)); } } private function insertBracesAfter(Tokens $tokens, $index) { $tokens->insertAt(++$index, [new Token('('), new Token(')')]); } } count() - 1; $index >= 0; --$index) { if ($tokensAnalyzer->isUnarySuccessorOperator($index)) { if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { $tokens->removeLeadingWhitespace($index); } continue; } if ($tokensAnalyzer->isUnaryPredecessorOperator($index)) { $tokens->removeTrailingWhitespace($index); continue; } } } } isAnyTokenKindsFound([T_PLUS_EQUAL, T_MINUS_EQUAL]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index > 0; --$index) { $expressionEnd = $tokens[$index]; if (!$expressionEnd->equalsAny(self::EXPRESSION_END_TOKENS)) { continue; } $numberIndex = $tokens->getPrevMeaningfulToken($index); $number = $tokens[$numberIndex]; if (!$number->isGivenKind(T_LNUMBER) || '1' !== $number->getContent()) { continue; } $operatorIndex = $tokens->getPrevMeaningfulToken($numberIndex); $operator = $tokens[$operatorIndex]; if (!$operator->isGivenKind([T_PLUS_EQUAL, T_MINUS_EQUAL])) { continue; } $startIndex = $this->findStart($tokens, $operatorIndex); $this->clearRangeLeaveComments( $tokens, $tokens->getPrevMeaningfulToken($operatorIndex) + 1, $numberIndex ); $tokens->insertAt( $startIndex, new Token($operator->isGivenKind(T_PLUS_EQUAL) ? [T_INC, '++'] : [T_DEC, '--']) ); } } private function clearRangeLeaveComments(Tokens $tokens, $indexStart, $indexEnd) { for ($i = $indexStart; $i <= $indexEnd; ++$i) { $token = $tokens[$i]; if ($token->isComment()) { continue; } if ($token->isWhitespace("\n\r")) { continue; } $tokens->clearAt($i); } } } isAllTokenKindsFound(['?', ':']); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $ternaryOperatorIndices = []; $excludedIndices = []; foreach ($tokens as $index => $token) { if ($token->isGivenKind(T_SWITCH)) { $excludedIndices = array_merge($excludedIndices, $this->getColonIndicesForSwitch($tokens, $index)); continue; } if (!$token->equalsAny(['?', ':'])) { continue; } if (\in_array($index, $excludedIndices, true)) { continue; } if ($this->belongsToAlternativeSyntax($tokens, $index)) { continue; } if ($this->belongsToGoToLabel($tokens, $index)) { continue; } $ternaryOperatorIndices[] = $index; } foreach (array_reverse($ternaryOperatorIndices) as $index) { $token = $tokens[$index]; if ($token->equals('?')) { $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index); if ($tokens[$nextNonWhitespaceIndex]->equals(':')) { $tokens->ensureWhitespaceAtIndex($index + 1, 0, ''); } else { $this->ensureWhitespaceExistence($tokens, $index + 1, true); } $this->ensureWhitespaceExistence($tokens, $index - 1, false); continue; } if ($token->equals(':')) { $this->ensureWhitespaceExistence($tokens, $index + 1, true); $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; if (!$prevNonWhitespaceToken->equals('?')) { $this->ensureWhitespaceExistence($tokens, $index - 1, false); } } } } private function belongsToAlternativeSyntax(Tokens $tokens, $index) { if (!$tokens[$index]->equals(':')) { return false; } $closeParenthesisIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$closeParenthesisIndex]->isGivenKind(T_ELSE)) { return true; } if (!$tokens[$closeParenthesisIndex]->equals(')')) { return false; } $openParenthesisIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $closeParenthesisIndex); $alternativeControlStructureIndex = $tokens->getPrevMeaningfulToken($openParenthesisIndex); return $tokens[$alternativeControlStructureIndex]->isGivenKind([T_DECLARE, T_ELSEIF, T_FOR, T_FOREACH, T_IF, T_SWITCH, T_WHILE]); } private function belongsToGoToLabel(Tokens $tokens, $index) { if (!$tokens[$index]->equals(':')) { return false; } $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_STRING)) { return false; } $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); return $tokens[$prevMeaningfulTokenIndex]->equalsAny([';', '{', '}', [T_OPEN_TAG]]); } private function getColonIndicesForSwitch(Tokens $tokens, $switchIndex) { return array_map( static function (CaseAnalysis $caseAnalysis) { return $caseAnalysis->getColonIndex(); }, (new SwitchAnalyzer())->getSwitchAnalysis($tokens, $switchIndex)->getCases() ); } private function ensureWhitespaceExistence(Tokens $tokens, $index, $after) { if ($tokens[$index]->isWhitespace()) { if ( false === strpos($tokens[$index]->getContent(), "\n") && !$tokens[$index - 1]->isComment() ) { $tokens[$index] = new Token([T_WHITESPACE, ' ']); } return; } $index += $after ? 0 : 1; $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); } } equals('=')) { $tokens[$index] = new Token(sprintf(self::ALIGNABLE_PLACEHOLDER, $this->deepestLevel).$token->getContent()); continue; } if ($token->isGivenKind(T_FUNCTION)) { ++$this->deepestLevel; continue; } if ($token->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->equals('[')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } } } } self::STYLE_POST] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_INC, T_DEC]); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('style', 'Whether to use pre- or post-increment and decrement operators.')) ->setAllowedValues([self::STYLE_PRE, self::STYLE_POST]) ->setDefault(self::STYLE_PRE) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind([T_INC, T_DEC])) { continue; } if (self::STYLE_PRE === $this->configuration['style'] && $tokensAnalyzer->isUnarySuccessorOperator($index)) { $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; if (!$nextToken->equalsAny([';', ')'])) { continue; } $startIndex = $this->findStart($tokens, $index); $prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)]; if ($prevToken->equalsAny([';', '{', '}', [T_OPEN_TAG], ')'])) { $tokens->clearAt($index); $tokens->insertAt($startIndex, clone $token); } } elseif (self::STYLE_POST === $this->configuration['style'] && $tokensAnalyzer->isUnaryPredecessorOperator($index)) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if (!$prevToken->equalsAny([';', '{', '}', [T_OPEN_TAG], ')'])) { continue; } $endIndex = $this->findEnd($tokens, $index); $nextToken = $tokens[$tokens->getNextMeaningfulToken($endIndex)]; if ($nextToken->equalsAny([';', ')'])) { $tokens->clearAt($index); $tokens->insertAt($tokens->getNextNonWhitespace($endIndex), clone $token); } } } } private function findEnd(Tokens $tokens, $index) { $nextIndex = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$nextIndex]; while ($nextToken->equalsAny([ '$', '(', '[', [CT::T_DYNAMIC_PROP_BRACE_OPEN], [CT::T_DYNAMIC_VAR_BRACE_OPEN], [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN], [T_NS_SEPARATOR], [T_STATIC], [T_STRING], [T_VARIABLE], ])) { $blockType = Tokens::detectBlockType($nextToken); if (null !== $blockType) { $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); } $index = $nextIndex; $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); $nextToken = $tokens[$nextIndex]; } if ($nextToken->isGivenKind(T_OBJECT_OPERATOR)) { return $this->findEnd($tokens, $nextIndex); } if ($nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { return $this->findEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); } return $index; } } isTokenKindFound('!'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ($token->equals('!')) { if (!$tokens[$index + 1]->isWhitespace()) { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } else { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } } } } } ` with `!=`.', [new CodeSample(" \$c;\n")] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_IS_NOT_EQUAL); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isGivenKind(T_IS_NOT_EQUAL)) { $tokens[$index] = new Token([T_IS_NOT_EQUAL, '!=']); } } } } = 7.0.', [ new VersionSpecificCodeSample( "= 70000 && $tokens->isTokenKindFound(T_ISSET); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $issetIndexes = array_keys($tokens->findGivenKind(T_ISSET)); while ($issetIndex = array_pop($issetIndexes)) { $this->fixIsset($tokens, $issetIndex); } } private function fixIsset(Tokens $tokens, $index) { $prevTokenIndex = $tokens->getPrevMeaningfulToken($index); if ($this->isHigherPrecedenceAssociativityOperator($tokens[$prevTokenIndex])) { return; } $startBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex); $ternaryQuestionMarkIndex = $tokens->getNextMeaningfulToken($endBraceIndex); if (!$tokens[$ternaryQuestionMarkIndex]->equals('?')) { return; } $issetTokens = $this->getMeaningfulSequence($tokens, $startBraceIndex, $endBraceIndex); if ($this->hasChangingContent($issetTokens)) { return; } $ternaryColonIndex = $tokens->getNextTokenOfKind($ternaryQuestionMarkIndex, [':']); $ternaryFirstOperandTokens = $this->getMeaningfulSequence($tokens, $ternaryQuestionMarkIndex, $ternaryColonIndex); if ($issetTokens->generateCode() !== $ternaryFirstOperandTokens->generateCode()) { return; } $ternaryFirstOperandIndex = $tokens->getNextMeaningfulToken($ternaryQuestionMarkIndex); $comments = []; $commentStarted = false; for ($loopIndex = $index; $loopIndex < $ternaryFirstOperandIndex; ++$loopIndex) { if ($tokens[$loopIndex]->isComment()) { $comments[] = $tokens[$loopIndex]; $commentStarted = true; } elseif ($commentStarted) { if ($tokens[$loopIndex]->isWhitespace()) { $comments[] = $tokens[$loopIndex]; } $commentStarted = false; } } $tokens[$ternaryColonIndex] = new Token([T_COALESCE, '??']); $tokens->overrideRange($index, $ternaryFirstOperandIndex - 1, $comments); } private function getMeaningfulSequence(Tokens $tokens, $start, $end) { $sequence = []; $index = $start; while ($index < $end) { $index = $tokens->getNextMeaningfulToken($index); if ($index >= $end || null === $index) { break; } $sequence[] = $tokens[$index]; } return Tokens::fromArray($sequence); } private function isHigherPrecedenceAssociativityOperator(Token $token) { static $operatorsPerId = [ T_ARRAY_CAST => true, T_BOOLEAN_AND => true, T_BOOLEAN_OR => true, T_BOOL_CAST => true, T_COALESCE => true, T_DEC => true, T_DOUBLE_CAST => true, T_INC => true, T_INT_CAST => true, T_IS_EQUAL => true, T_IS_GREATER_OR_EQUAL => true, T_IS_IDENTICAL => true, T_IS_NOT_EQUAL => true, T_IS_NOT_IDENTICAL => true, T_IS_SMALLER_OR_EQUAL => true, T_OBJECT_CAST => true, T_POW => true, T_SL => true, T_SPACESHIP => true, T_SR => true, T_STRING_CAST => true, T_UNSET_CAST => true, ]; static $operatorsPerContent = [ '!', '%', '&', '*', '+', '-', '/', ':', '^', '|', '~', '.', ]; return isset($operatorsPerId[$token->getId()]) || $token->equalsAny($operatorsPerContent); } private function hasChangingContent(Tokens $tokens) { static $operatorsPerId = [ T_DEC, T_INC, T_YIELD, T_YIELD_FROM, ]; foreach ($tokens as $token) { if ($token->isGivenKind($operatorsPerId) || $token->equals('(')) { return true; } } return false; } } ', '|', '^', '+', '-', '&', '&=', '&&', '||', '.=', '/=', '=>', '==', '>=', '===', '!=', '<>', '!==', '<=', 'and', 'or', 'xor', '-=', '%=', '*=', '|=', '+=', '<<', '<<=', '>>', '>>=', '^=', '**', '**=', '<=>', '??', '??=', ]; private $tokensAnalyzer; private $alignOperatorTokens = []; private $operators = []; public function configure(array $configuration = null) { if ( null !== $configuration && (\array_key_exists('align_equals', $configuration) || \array_key_exists('align_double_arrow', $configuration)) ) { $configuration = $this->resolveOldConfig($configuration); } parent::configure($configuration); $this->operators = $this->resolveOperatorsFromConfig(); } public function getDefinition() { return new FixerDefinition( 'Binary operators should be surrounded by space as configured.', [ new CodeSample( " ['=' => 'align', 'xor' => null]] ), new CodeSample( ' ['+=' => 'align_single_space']] ), new CodeSample( ' ['===' => 'align_single_space_minimal']] ), new CodeSample( ' ['|' => 'no_space']] ), ] ); } public function getPriority() { return -32; } public function isCandidate(Tokens $tokens) { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 2; $index > 0; --$index) { if (!$this->tokensAnalyzer->isBinaryOperator($index)) { continue; } if ('=' === $tokens[$index]->getContent()) { $isDeclare = $this->isEqualPartOfDeclareStatement($tokens, $index); if (false === $isDeclare) { $this->fixWhiteSpaceAroundOperator($tokens, $index); } else { $index = $isDeclare; } } else { $this->fixWhiteSpaceAroundOperator($tokens, $index); } --$index; } if (\count($this->alignOperatorTokens)) { $this->fixAlignment($tokens, $this->alignOperatorTokens); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('default', 'Default fix strategy.')) ->setDefault(self::SINGLE_SPACE) ->setAllowedValues(self::$allowedValues) ->getOption(), (new FixerOptionBuilder('operators', 'Dictionary of `binary operator` => `fix strategy` values that differ from the default strategy.')) ->setAllowedTypes(['array']) ->setAllowedValues([static function ($option) { foreach ($option as $operator => $value) { if (!\in_array($operator, self::$supportedOperators, true)) { throw new InvalidOptionsException( sprintf( 'Unexpected "operators" key, expected any of "%s", got "%s".', implode('", "', self::$supportedOperators), \is_object($operator) ? \get_class($operator) : \gettype($operator).'#'.$operator ) ); } if (!\in_array($value, self::$allowedValues, true)) { throw new InvalidOptionsException( sprintf( 'Unexpected value for operator "%s", expected any of "%s", got "%s".', $operator, implode('", "', self::$allowedValues), \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value) ) ); } } return true; }]) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('align_double_arrow', 'Whether to apply, remove or ignore double arrows alignment.')) ->setDefault(false) ->setAllowedValues([true, false, null]) ->setDeprecationMessage('Use options `operators` and `default` instead.') ->getOption(), (new FixerOptionBuilder('align_equals', 'Whether to apply, remove or ignore equals alignment.')) ->setDefault(false) ->setAllowedValues([true, false, null]) ->setDeprecationMessage('Use options `operators` and `default` instead.') ->getOption(), ]); } private function fixWhiteSpaceAroundOperator(Tokens $tokens, $index) { $tokenContent = strtolower($tokens[$index]->getContent()); if (!\array_key_exists($tokenContent, $this->operators)) { return; } if (self::SINGLE_SPACE === $this->operators[$tokenContent]) { $this->fixWhiteSpaceAroundOperatorToSingleSpace($tokens, $index); return; } if (self::NO_SPACE === $this->operators[$tokenContent]) { $this->fixWhiteSpaceAroundOperatorToNoSpace($tokens, $index); return; } $this->alignOperatorTokens[$tokenContent] = $this->operators[$tokenContent]; if (self::ALIGN === $this->operators[$tokenContent]) { return; } if ($tokens[$index + 1]->isWhitespace()) { if (self::ALIGN_SINGLE_SPACE_MINIMAL === $this->operators[$tokenContent]) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } return; } $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } private function fixWhiteSpaceAroundOperatorToSingleSpace(Tokens $tokens, $index) { if ($tokens[$index + 1]->isWhitespace()) { $content = $tokens[$index + 1]->getContent(); if (' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } } else { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } if ($tokens[$index - 1]->isWhitespace()) { $content = $tokens[$index - 1]->getContent(); if (' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); } } else { $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); } } private function fixWhiteSpaceAroundOperatorToNoSpace(Tokens $tokens, $index) { if ($tokens[$index + 1]->isWhitespace()) { $content = $tokens[$index + 1]->getContent(); if (false === strpos($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { $tokens->clearAt($index + 1); } } if ($tokens[$index - 1]->isWhitespace()) { $content = $tokens[$index - 1]->getContent(); if (false === strpos($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { $tokens->clearAt($index - 1); } } } private function isEqualPartOfDeclareStatement(Tokens $tokens, $index) { $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_STRING)) { $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); if ($tokens[$prevMeaningfulIndex]->equals('(')) { $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_DECLARE)) { return $prevMeaningfulIndex; } } } return false; } private function resolveOperatorsFromConfig() { $operators = []; if (null !== $this->configuration['default']) { foreach (self::$supportedOperators as $operator) { $operators[$operator] = $this->configuration['default']; } } foreach ($this->configuration['operators'] as $operator => $value) { if (null === $value) { unset($operators[$operator]); } else { $operators[$operator] = $value; } } if (!\defined('T_SPACESHIP')) { unset($operators['<=>']); } if (!\defined('T_COALESCE')) { unset($operators['??']); } if (!\defined('T_COALESCE_EQUAL')) { unset($operators['??=']); } return $operators; } private function resolveOldConfig(array $configuration) { $newConfig = [ 'operators' => [], ]; foreach ($configuration as $name => $setting) { if ('align_double_arrow' === $name) { if (true === $configuration[$name]) { $newConfig['operators']['=>'] = self::ALIGN; } elseif (false === $configuration[$name]) { $newConfig['operators']['=>'] = self::SINGLE_SPACE; } elseif (null !== $configuration[$name]) { throw new InvalidFixerConfigurationException( $this->getName(), sprintf( 'Invalid configuration: The option "align_double_arrow" with value %s is invalid. Accepted values are: true, false, null.', $configuration[$name] ) ); } } elseif ('align_equals' === $name) { if (true === $configuration[$name]) { $newConfig['operators']['='] = self::ALIGN; } elseif (false === $configuration[$name]) { $newConfig['operators']['='] = self::SINGLE_SPACE; } elseif (null !== $configuration[$name]) { throw new InvalidFixerConfigurationException( $this->getName(), sprintf( 'Invalid configuration: The option "align_equals" with value %s is invalid. Accepted values are: true, false, null.', $configuration[$name] ) ); } } else { throw new InvalidFixerConfigurationException($this->getName(), 'Mixing old configuration with new configuration is not allowed.'); } } $message = sprintf( 'Given configuration is deprecated and will be removed in 3.0. Use configuration %s as replacement for %s.', HelpCommand::toString($newConfig), HelpCommand::toString($configuration) ); if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { throw new InvalidFixerConfigurationException($this->getName(), "{$message} This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set."); } @trigger_error($message, E_USER_DEPRECATED); return $newConfig; } private function fixAlignment(Tokens $tokens, array $toAlign) { $this->deepestLevel = 0; $this->currentLevel = 0; foreach ($toAlign as $tokenContent => $alignStrategy) { $tokensClone = clone $tokens; if ('=>' === $tokenContent) { $this->injectAlignmentPlaceholdersForArrow($tokensClone, 0, \count($tokens)); } else { $this->injectAlignmentPlaceholders($tokensClone, 0, \count($tokens), $tokenContent); } if (self::ALIGN_SINGLE_SPACE === $alignStrategy || self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy) { if ('=>' === $tokenContent) { for ($index = $tokens->count() - 2; $index > 0; --$index) { if ($tokens[$index]->isGivenKind(T_DOUBLE_ARROW)) { $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); } } } elseif ('=' === $tokenContent) { for ($index = $tokens->count() - 2; $index > 0; --$index) { if ('=' === $tokens[$index]->getContent() && !$this->isEqualPartOfDeclareStatement($tokens, $index) && $this->tokensAnalyzer->isBinaryOperator($index)) { $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); } } } else { for ($index = $tokens->count() - 2; $index > 0; --$index) { $content = $tokens[$index]->getContent(); if (strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index)) { $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); } } } } $tokens->setCode($this->replacePlaceholders($tokensClone, $alignStrategy)); } } private function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt, $tokenContent) { for ($index = $startAt; $index < $endAt; ++$index) { $token = $tokens[$index]; $content = $token->getContent(); if ( strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index) && ('=' !== $content || !$this->isEqualPartOfDeclareStatement($tokens, $index)) ) { $tokens[$index] = new Token(sprintf(self::ALIGN_PLACEHOLDER, $this->deepestLevel).$content); continue; } if ($token->isGivenKind(T_FUNCTION)) { ++$this->deepestLevel; continue; } if ($token->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->equals('[')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } } } private function injectAlignmentPlaceholdersForArrow(Tokens $tokens, $startAt, $endAt) { for ($index = $startAt; $index < $endAt; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind([T_FOREACH, T_FOR, T_WHILE, T_IF, T_SWITCH])) { $index = $tokens->getNextMeaningfulToken($index); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(T_ARRAY)) { $from = $tokens->getNextMeaningfulToken($index); $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from); $index = $until; $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $from = $index; $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $from); $index = $until; $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); continue; } if ($token->isGivenKind(T_DOUBLE_ARROW)) { $tokenContent = sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$token->getContent(); $nextToken = $tokens[$index + 1]; if (!$nextToken->isWhitespace()) { $tokenContent .= ' '; } elseif ($nextToken->isWhitespace(" \t")) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } $tokens[$index] = new Token([T_DOUBLE_ARROW, $tokenContent]); continue; } if ($token->equals(';')) { ++$this->deepestLevel; ++$this->currentLevel; continue; } if ($token->equals(',')) { for ($i = $index; $i < $endAt - 1; ++$i) { if (false !== strpos($tokens[$i - 1]->getContent(), "\n")) { break; } if ($tokens[$i + 1]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $arrayStartIndex = $tokens[$i + 1]->isGivenKind(T_ARRAY) ? $tokens->getNextMeaningfulToken($i + 1) : $i + 1 ; $blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]); $arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex); if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) { break; } } ++$index; } } } } private function injectArrayAlignmentPlaceholders(Tokens $tokens, $from, $until) { if ($tokens->isPartialCodeMultiline($from, $until)) { ++$this->deepestLevel; ++$this->currentLevel; $this->injectAlignmentPlaceholdersForArrow($tokens, $from, $until); --$this->currentLevel; } } private function fixWhiteSpaceBeforeOperator(Tokens $tokens, $index, $alignStrategy) { if (!$tokens[$index - 1]->isWhitespace()) { $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); return; } if (self::ALIGN_SINGLE_SPACE_MINIMAL !== $alignStrategy || $tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { return; } $content = $tokens[$index - 1]->getContent(); if (' ' !== $content && false === strpos($content, "\n")) { $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); } } private function replacePlaceholders(Tokens $tokens, $alignStrategy) { $tmpCode = $tokens->generateCode(); for ($j = 0; $j <= $this->deepestLevel; ++$j) { $placeholder = sprintf(self::ALIGN_PLACEHOLDER, $j); if (false === strpos($tmpCode, $placeholder)) { continue; } $lines = explode("\n", $tmpCode); $groups = []; $groupIndex = 0; $groups[$groupIndex] = []; foreach ($lines as $index => $line) { if (substr_count($line, $placeholder) > 0) { $groups[$groupIndex][] = $index; } else { ++$groupIndex; $groups[$groupIndex] = []; } } foreach ($groups as $group) { if (\count($group) < 1) { continue; } if (self::ALIGN !== $alignStrategy) { foreach ($group as $index) { $currentPosition = strpos($lines[$index], $placeholder); $before = substr($lines[$index], 0, $currentPosition); if (self::ALIGN_SINGLE_SPACE === $alignStrategy) { if (1 > \strlen($before) || ' ' !== substr($before, -1)) { $before .= ' '; } } elseif (self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy) { if (1 !== Preg::match('/^\h+$/', $before)) { $before = rtrim($before).' '; } } $lines[$index] = $before.substr($lines[$index], $currentPosition); } } $rightmostSymbol = 0; foreach ($group as $index) { $rightmostSymbol = max($rightmostSymbol, strpos(utf8_decode($lines[$index]), $placeholder)); } foreach ($group as $index) { $line = $lines[$index]; $currentSymbol = strpos(utf8_decode($line), $placeholder); $delta = abs($rightmostSymbol - $currentSymbol); if ($delta > 0) { $line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line); $lines[$index] = $line; } } } $tmpCode = str_replace($placeholder, '', implode("\n", $lines)); } return $tmpCode; } } `.', [new CodeSample(" b;\n")] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_OBJECT_OPERATOR); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_OBJECT_OPERATOR)) { continue; } if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { $tokens->clearAt($index - 1); } if ($tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment()) { $tokens->clearAt($index + 1); } } } } isGivenKind([T_FOREACH, T_FOR, T_WHILE, T_IF, T_SWITCH])) { $index = $tokens->getNextMeaningfulToken($index); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(T_ARRAY)) { $from = $tokens->getNextMeaningfulToken($index); $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from); $index = $until; $this->injectArrayAlignmentPlaceholders($tokens, $from, $until); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ($prevToken->isGivenKind([T_STRING, T_VARIABLE])) { continue; } $from = $index; $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $from); $index = $until; $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); continue; } if ($token->isGivenKind(T_DOUBLE_ARROW)) { $tokenContent = sprintf(self::ALIGNABLE_PLACEHOLDER, $this->currentLevel).$token->getContent(); $nextIndex = $index + 1; $nextToken = $tokens[$nextIndex]; if (!$nextToken->isWhitespace()) { $tokenContent .= ' '; } elseif ($nextToken->isWhitespace(" \t")) { $tokens[$nextIndex] = new Token([T_WHITESPACE, ' ']); } $tokens[$index] = new Token([T_DOUBLE_ARROW, $tokenContent]); continue; } if ($token->equals(';')) { ++$this->deepestLevel; ++$this->currentLevel; continue; } if ($token->equals(',')) { for ($i = $index; $i < $endAt - 1; ++$i) { if (false !== strpos($tokens[$i - 1]->getContent(), "\n")) { break; } if ($tokens[$i + 1]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $arrayStartIndex = $tokens[$i + 1]->isGivenKind(T_ARRAY) ? $tokens->getNextMeaningfulToken($i + 1) : $i + 1 ; $blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]); $arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex); if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) { break; } } ++$index; } } } } private function injectArrayAlignmentPlaceholders(Tokens $tokens, $from, $until) { if ($tokens->isPartialCodeMultiline($from, $until)) { ++$this->deepestLevel; ++$this->currentLevel; $this->injectAlignmentPlaceholders($tokens, $from, $until); --$this->currentLevel; } } } proxyFixers); } protected function createProxyFixers() { $fixer = new IncrementStyleFixer(); $fixer->configure(['style' => 'pre']); return [$fixer]; } } isAnyTokenKindsFound([T_CLASS, T_INTERFACE]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); foreach ((new NamespacesAnalyzer())->getDeclarations($tokens) as $namespace) { for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { if (!$tokens[$index]->isGivenKind([T_CLASS, T_INTERFACE]) || $tokensAnalyzer->isAnonymousClass($index)) { continue; } $nameIndex = $tokens->getNextTokenOfKind($index, [[T_STRING]]); $startIndex = $tokens->getNextTokenOfKind($nameIndex, ['{']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); $name = $tokens[$nameIndex]->getContent(); $this->replaceNameOccurrences($tokens, $namespace->getFullName(), $name, $startIndex, $endIndex); $index = $endIndex; } } } private function replaceNameOccurrences(Tokens $tokens, $namespace, $name, $startIndex, $endIndex) { $tokensAnalyzer = new TokensAnalyzer($tokens); $insideMethodSignatureUntil = null; for ($i = $startIndex; $i < $endIndex; ++$i) { if ($i === $insideMethodSignatureUntil) { $insideMethodSignatureUntil = null; } $token = $tokens[$i]; if ($token->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) { $i = $tokens->getNextTokenOfKind($i, ['{']); $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); continue; } if ($token->isGivenKind(T_FUNCTION)) { $i = $tokens->getNextTokenOfKind($i, ['(']); $insideMethodSignatureUntil = $tokens->getNextTokenOfKind($i, ['{', ';']); continue; } if (!$token->equals([T_STRING, $name], false)) { continue; } $nextToken = $tokens[$tokens->getNextMeaningfulToken($i)]; if ($nextToken->isGivenKind(T_NS_SEPARATOR)) { continue; } $classStartIndex = $i; $prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)]; if ($prevToken->isGivenKind(T_NS_SEPARATOR)) { $classStartIndex = $this->getClassStart($tokens, $i, $namespace); if (null === $classStartIndex) { continue; } $prevToken = $tokens[$tokens->getPrevMeaningfulToken($classStartIndex)]; } if ($prevToken->isGivenKind([T_OBJECT_OPERATOR, T_STRING])) { continue; } if ( $prevToken->isGivenKind([T_INSTANCEOF, T_NEW]) || $nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM) || ( null !== $insideMethodSignatureUntil && $i < $insideMethodSignatureUntil && $prevToken->equalsAny(['(', ',', [CT::T_TYPE_COLON], [CT::T_NULLABLE_TYPE]]) ) ) { for ($j = $classStartIndex; $j < $i; ++$j) { $tokens->clearTokenAndMergeSurroundingWhitespace($j); } $tokens[$i] = new Token([T_STRING, 'self']); } } } private function getClassStart(Tokens $tokens, $index, $namespace) { $namespace = ('' !== $namespace ? '\\'.$namespace : '').'\\'; foreach (array_reverse(Preg::split('/(\\\\)/', $namespace, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)) as $piece) { $index = $tokens->getPrevMeaningfulToken($index); if ('\\' === $piece) { if (!$tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { return null; } } elseif (!$tokens[$index]->equals([T_STRING, $piece], false)) { return null; } } return $index; } } isAllTokenKindsFound([T_CLASS, T_FINAL]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensCount = \count($tokens); for ($index = 0; $index < $tokensCount; ++$index) { if (!$tokens[$index]->isGivenKind(T_CLASS)) { continue; } $classOpen = $tokens->getNextTokenOfKind($index, ['{']); $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; $classIsFinal = $prevToken->isGivenKind(T_FINAL); $this->fixClass($tokens, $classOpen, $classIsFinal); } } private function fixClass(Tokens $tokens, $classOpenIndex, $classIsFinal) { $tokensCount = \count($tokens); for ($index = $classOpenIndex + 1; $index < $tokensCount; ++$index) { if ($tokens[$index]->equals('}')) { return; } if ($tokens[$index]->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if (!$tokens[$index]->isGivenKind(T_FINAL)) { continue; } if (!$classIsFinal && !$this->isPrivateMethodOtherThanConstructor($tokens, $index, $classOpenIndex)) { continue; } $tokens->clearAt($index); ++$index; if ($tokens[$index]->isWhitespace()) { $tokens->clearAt($index); } } } private function isPrivateMethodOtherThanConstructor(Tokens $tokens, $index, $classOpenIndex) { $index = max($classOpenIndex + 1, $tokens->getPrevTokenOfKind($index, [';', '{', '}'])); $private = false; while (!$tokens[$index]->isGivenKind(T_FUNCTION)) { if ($tokens[$index]->isGivenKind(T_PRIVATE)) { $private = true; } $index = $tokens->getNextMeaningfulToken($index); } return $private && '__construct' !== strtolower($tokens[$tokens->getNextMeaningfulToken($index)]->getContent()); } } self::DIRECTION_DESCEND] ), new CodeSample( " self::ORDER_LENGTH] ), new CodeSample( " self::ORDER_LENGTH, self::OPTION_DIRECTION => self::DIRECTION_DESCEND, ] ), ], null, "Risky for `implements` when specifying both an interface and its parent interface, because PHP doesn't break on `parent, child` but does on `child, parent`." ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_IMPLEMENTS) || $tokens->isAllTokenKindsFound([T_INTERFACE, T_EXTENDS]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_IMPLEMENTS)) { if (!$token->isGivenKind(T_EXTENDS)) { continue; } $nameTokenIndex = $tokens->getPrevMeaningfulToken($index); $interfaceTokenIndex = $tokens->getPrevMeaningfulToken($nameTokenIndex); $interfaceToken = $tokens[$interfaceTokenIndex]; if (!$interfaceToken->isGivenKind(T_INTERFACE)) { continue; } } $interfaceIndex = 0; $interfaces = [['tokens' => []]]; $implementsStart = $index + 1; $classStart = $tokens->getNextTokenOfKind($implementsStart, ['{']); $implementsEnd = $tokens->getPrevNonWhitespace($classStart); for ($i = $implementsStart; $i <= $implementsEnd; ++$i) { if ($tokens[$i]->equals(',')) { ++$interfaceIndex; $interfaces[$interfaceIndex] = ['tokens' => []]; continue; } $interfaces[$interfaceIndex]['tokens'][] = $tokens[$i]; } if (1 === \count($interfaces)) { continue; } foreach ($interfaces as $interfaceIndex => $interface) { $interfaceTokens = Tokens::fromArray($interface['tokens'], false); $normalized = ''; $actualInterfaceIndex = $interfaceTokens->getNextMeaningfulToken(-1); while ($interfaceTokens->offsetExists($actualInterfaceIndex)) { $token = $interfaceTokens[$actualInterfaceIndex]; if (null === $token || $token->isComment() || $token->isWhitespace()) { break; } $normalized .= str_replace('\\', ' ', $token->getContent()); ++$actualInterfaceIndex; } $interfaces[$interfaceIndex]['normalized'] = $normalized; $interfaces[$interfaceIndex]['originalIndex'] = $interfaceIndex; } usort($interfaces, function (array $first, array $second) { $score = self::ORDER_LENGTH === $this->configuration[self::OPTION_ORDER] ? \strlen($first['normalized']) - \strlen($second['normalized']) : strcasecmp($first['normalized'], $second['normalized']); if (self::DIRECTION_DESCEND === $this->configuration[self::OPTION_DIRECTION]) { $score *= -1; } return $score; }); $changed = false; foreach ($interfaces as $interfaceIndex => $interface) { if ($interface['originalIndex'] !== $interfaceIndex) { $changed = true; break; } } if (!$changed) { continue; } $newTokens = array_shift($interfaces)['tokens']; foreach ($interfaces as $interface) { array_push($newTokens, new Token(','), ...$interface['tokens']); } $tokens->overrideRange($implementsStart, $implementsEnd, $newTokens); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder(self::OPTION_ORDER, 'How the interfaces should be ordered')) ->setAllowedValues($this->supportedOrderOptions) ->setDefault(self::ORDER_ALPHA) ->getOption(), (new FixerOptionBuilder(self::OPTION_DIRECTION, 'Which direction the interfaces should be ordered')) ->setAllowedValues($this->supportedDirectionOptions) ->setDefault(self::DIRECTION_ASCEND) ->getOption(), ]); } } isAllTokenKindsFound([T_CLASS, T_FINAL, T_PROTECTED]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $end = \count($tokens) - 3; for ($index = 0; $index < $end; ++$index) { if (!$tokens[$index]->isGivenKind(T_CLASS)) { continue; } $classOpen = $tokens->getNextTokenOfKind($index, ['{']); $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); if (!$this->skipClass($tokens, $index, $classOpen, $classClose)) { $this->fixClass($tokens, $classOpen, $classClose); } $index = $classClose; } } private function fixClass(Tokens $tokens, $classOpenIndex, $classCloseIndex) { for ($index = $classOpenIndex + 1; $index < $classCloseIndex; ++$index) { if ($tokens[$index]->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if (!$tokens[$index]->isGivenKind(T_PROTECTED)) { continue; } $tokens[$index] = new Token([T_PRIVATE, 'private']); } } private function skipClass(Tokens $tokens, $classIndex, $classOpenIndex, $classCloseIndex) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($classIndex)]; if (!$prevToken->isGivenKind(T_FINAL)) { return true; } for ($index = $classIndex; $index < $classOpenIndex; ++$index) { if ($tokens[$index]->isGivenKind(T_EXTENDS)) { return true; } } $useIndex = $tokens->getNextTokenOfKind($classIndex, [[CT::T_USE_TRAIT]]); return $useIndex && $useIndex < $classCloseIndex; } } ['const']] ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('elements', [ (new FixerOptionBuilder('elements', 'The structural elements to fix (PHP >= 7.1 required for `const`).')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(['property', 'method', 'const'])]) ->setDefault(['property', 'method']) ->getOption(), ], $this->getName()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $elements = $tokensAnalyzer->getClassyElements(); $propertyTypeDeclarationKinds = [T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT]; foreach (array_reverse($elements, true) as $index => $element) { if (!\in_array($element['type'], $this->configuration['elements'], true)) { continue; } if (\PHP_VERSION_ID < 70100 && 'const' === $element['type']) { continue; } $abstractFinalIndex = null; $visibilityIndex = null; $staticIndex = null; $typeIndex = null; $prevIndex = $tokens->getPrevMeaningfulToken($index); $expectedKinds = [T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR]; if ('property' === $element['type']) { $expectedKinds = array_merge($expectedKinds, $propertyTypeDeclarationKinds); } while ($tokens[$prevIndex]->isGivenKind($expectedKinds)) { if ($tokens[$prevIndex]->isGivenKind([T_ABSTRACT, T_FINAL])) { $abstractFinalIndex = $prevIndex; } elseif ($tokens[$prevIndex]->isGivenKind(T_STATIC)) { $staticIndex = $prevIndex; } elseif ($tokens[$prevIndex]->isGivenKind($propertyTypeDeclarationKinds)) { $typeIndex = $prevIndex; } else { $visibilityIndex = $prevIndex; } $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); } if (null !== $typeIndex) { $index = $typeIndex; } if ($tokens[$prevIndex]->equals(',')) { continue; } if (null !== $staticIndex) { if ($this->isKeywordPlacedProperly($tokens, $staticIndex, $index)) { $index = $staticIndex; } else { $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $staticIndex, $index); } } if (null === $visibilityIndex) { $tokens->insertAt($index, [new Token([T_PUBLIC, 'public']), new Token([T_WHITESPACE, ' '])]); } else { if ($tokens[$visibilityIndex]->isGivenKind(T_VAR)) { $tokens[$visibilityIndex] = new Token([T_PUBLIC, 'public']); } if ($this->isKeywordPlacedProperly($tokens, $visibilityIndex, $index)) { $index = $visibilityIndex; } else { $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilityIndex, $index); } } if (null === $abstractFinalIndex) { continue; } if ($this->isKeywordPlacedProperly($tokens, $abstractFinalIndex, $index)) { continue; } $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $abstractFinalIndex, $index); } } private function isKeywordPlacedProperly(Tokens $tokens, $keywordIndex, $comparedIndex) { return $keywordIndex + 2 === $comparedIndex && ' ' === $tokens[$keywordIndex + 1]->getContent(); } private function moveTokenAndEnsureSingleSpaceFollows(Tokens $tokens, $fromIndex, $toIndex) { $tokens->insertAt($toIndex, [$tokens[$fromIndex], new Token([T_WHITESPACE, ' '])]); $tokens->clearAt($fromIndex); if ($tokens[$fromIndex + 1]->isWhitespace()) { $tokens->clearAt($fromIndex + 1); } } } proxyFixers); } protected function createProxyFixers() { $fixer = new ClassAttributesSeparationFixer(); $fixer->configure(['elements' => ['method']]); return [$fixer]; } } isAllTokenKindsFound([T_CLASS, T_STATIC]) && $tokens->isAnyTokenKindsFound([T_DOUBLE_COLON, T_NEW, T_INSTANCEOF]); } public function getPriority() { return -10; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->tokensAnalyzer = $tokensAnalyzer = new TokensAnalyzer($tokens); $classIndex = $tokens->getNextTokenOfKind(0, [[T_CLASS]]); while (null !== $classIndex) { if ( $tokens[$tokens->getPrevMeaningfulToken($classIndex)]->isGivenKind(T_FINAL) || $tokensAnalyzer->isAnonymousClass($classIndex) ) { $classIndex = $this->fixClass($tokens, $classIndex); } $classIndex = $tokens->getNextTokenOfKind($classIndex, [[T_CLASS]]); } } private function fixClass(Tokens $tokens, $index) { $index = $tokens->getNextTokenOfKind($index, ['{']); $classOpenCount = 1; while ($classOpenCount > 0) { ++$index; if ($tokens[$index]->equals('{')) { ++$classOpenCount; continue; } if ($tokens[$index]->equals('}')) { --$classOpenCount; continue; } if ($tokens[$index]->isGivenKind(T_FUNCTION)) { if ($this->tokensAnalyzer->isLambda($index)) { $index = $tokens->getNextTokenOfKind($index, ['{']); $openCount = 1; do { $index = $tokens->getNextTokenOfKind($index, ['}', '{', [T_CLASS]]); if ($tokens[$index]->equals('}')) { --$openCount; } elseif ($tokens[$index]->equals('{')) { ++$openCount; } else { $index = $this->fixClass($tokens, $index); } } while ($openCount > 0); } continue; } if ($tokens[$index]->isGivenKind([T_NEW, T_INSTANCEOF])) { $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->isGivenKind(T_STATIC)) { $tokens[$index] = new Token([T_STRING, 'self']); } continue; } if (!$tokens[$index]->isGivenKind(T_STATIC)) { continue; } $staticIndex = $index; $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { continue; } $tokens[$staticIndex] = new Token([T_STRING, 'self']); } return $index; } } isTokenKindFound(CT::T_USE_TRAIT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; 1 < $index; --$index) { if ($tokens[$index]->isGivenKind(CT::T_USE_TRAIT)) { $candidates = $this->getCandidates($tokens, $index); if (\count($candidates) > 0) { $this->fixTraitUse($tokens, $index, $candidates); } } } } private function fixTraitUse(Tokens $tokens, $useTraitIndex, array $candidates) { foreach ($candidates as $commaIndex) { $inserts = [ new Token([CT::T_USE_TRAIT, 'use']), new Token([T_WHITESPACE, ' ']), ]; $nextImportStartIndex = $tokens->getNextMeaningfulToken($commaIndex); if ($tokens[$nextImportStartIndex - 1]->isWhitespace()) { if (1 === Preg::match('/\R/', $tokens[$nextImportStartIndex - 1]->getContent())) { array_unshift($inserts, clone $tokens[$useTraitIndex - 1]); } $tokens->clearAt($nextImportStartIndex - 1); } $tokens[$commaIndex] = new Token(';'); $tokens->insertAt($nextImportStartIndex, $inserts); } } private function getCandidates(Tokens $tokens, $index) { $indexes = []; $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); while (!$tokens[$index]->equals(';')) { if ($tokens[$index]->equals('{')) { return []; } $indexes[] = $index; $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); } return array_reverse($indexes); } } null, 'public' => null, 'protected' => null, 'private' => null, 'constant' => null, 'constant_public' => ['constant', 'public'], 'constant_protected' => ['constant', 'protected'], 'constant_private' => ['constant', 'private'], 'property' => null, 'property_static' => ['property'], 'property_public' => ['property', 'public'], 'property_protected' => ['property', 'protected'], 'property_private' => ['property', 'private'], 'property_public_static' => ['property_static', 'property_public'], 'property_protected_static' => ['property_static', 'property_protected'], 'property_private_static' => ['property_static', 'property_private'], 'method' => null, 'method_static' => ['method'], 'method_public' => ['method', 'public'], 'method_protected' => ['method', 'protected'], 'method_private' => ['method', 'private'], 'method_public_static' => ['method_static', 'method_public'], 'method_protected_static' => ['method_static', 'method_protected'], 'method_private_static' => ['method_static', 'method_private'], ]; private static $specialTypes = [ 'construct' => null, 'destruct' => null, 'magic' => null, 'phpunit' => null, ]; private $supportedSortAlgorithms = [ self::SORT_NONE, self::SORT_ALPHA, ]; private $typePosition; public function configure(array $configuration = null) { parent::configure($configuration); $this->typePosition = []; $pos = 0; foreach ($this->configuration['order'] as $type) { $this->typePosition[$type] = $pos++; } foreach (self::$typeHierarchy as $type => $parents) { if (isset($this->typePosition[$type])) { continue; } if (!$parents) { $this->typePosition[$type] = null; continue; } foreach ($parents as $parent) { if (isset($this->typePosition[$parent])) { $this->typePosition[$type] = $this->typePosition[$parent]; continue 2; } } $this->typePosition[$type] = null; } $lastPosition = \count($this->configuration['order']); foreach ($this->typePosition as &$pos) { if (null === $pos) { $pos = $lastPosition; } $pos *= 10; } } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } public function getDefinition() { return new FixerDefinition( 'Orders the elements of classes/interfaces/traits.', [ new CodeSample( ' ['method_private', 'method_public']] ), new CodeSample( ' ['method_public'], 'sortAlgorithm' => 'alpha'] ), ] ); } public function getPriority() { return 65; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($i = 1, $count = $tokens->count(); $i < $count; ++$i) { if (!$tokens[$i]->isClassy()) { continue; } $i = $tokens->getNextTokenOfKind($i, ['{']); $elements = $this->getElements($tokens, $i); if (0 === \count($elements)) { continue; } $sorted = $this->sortElements($elements); $endIndex = $elements[\count($elements) - 1]['end']; if ($sorted !== $elements) { $this->sortTokens($tokens, $i, $endIndex, $sorted); } $i = $endIndex; } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('order', [ (new FixerOptionBuilder('order', 'List of strings defining order of elements.')) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset(array_keys(array_merge(self::$typeHierarchy, self::$specialTypes)))]) ->setDefault([ 'use_trait', 'constant_public', 'constant_protected', 'constant_private', 'property_public', 'property_protected', 'property_private', 'construct', 'destruct', 'magic', 'phpunit', 'method_public', 'method_protected', 'method_private', ]) ->getOption(), (new FixerOptionBuilder('sortAlgorithm', 'How multiple occurrences of same type statements should be sorted')) ->setAllowedValues($this->supportedSortAlgorithms) ->setDefault(self::SORT_NONE) ->getOption(), ], $this->getName()); } private function getElements(Tokens $tokens, $startIndex) { static $elementTokenKinds = [CT::T_USE_TRAIT, T_CONST, T_VARIABLE, T_FUNCTION]; ++$startIndex; $elements = []; while (true) { $element = [ 'start' => $startIndex, 'visibility' => 'public', 'static' => false, ]; for ($i = $startIndex;; ++$i) { $token = $tokens[$i]; if ($token->equals('}')) { return $elements; } if ($token->isGivenKind(T_STATIC)) { $element['static'] = true; continue; } if ($token->isGivenKind([T_PROTECTED, T_PRIVATE])) { $element['visibility'] = strtolower($token->getContent()); continue; } if (!$token->isGivenKind($elementTokenKinds)) { continue; } $type = $this->detectElementType($tokens, $i); if (\is_array($type)) { $element['type'] = $type[0]; $element['name'] = $type[1]; } else { $element['type'] = $type; } if ('property' === $element['type']) { $element['name'] = $tokens[$i]->getContent(); } elseif (\in_array($element['type'], ['use_trait', 'constant', 'method', 'magic', 'construct', 'destruct'], true)) { $element['name'] = $tokens[$tokens->getNextMeaningfulToken($i)]->getContent(); } $element['end'] = $this->findElementEnd($tokens, $i); break; } $elements[] = $element; $startIndex = $element['end'] + 1; } } private function detectElementType(Tokens $tokens, $index) { $token = $tokens[$index]; if ($token->isGivenKind(CT::T_USE_TRAIT)) { return 'use_trait'; } if ($token->isGivenKind(T_CONST)) { return 'constant'; } if ($token->isGivenKind(T_VARIABLE)) { return 'property'; } $nameToken = $tokens[$tokens->getNextMeaningfulToken($index)]; if ($nameToken->equals([T_STRING, '__construct'], false)) { return 'construct'; } if ($nameToken->equals([T_STRING, '__destruct'], false)) { return 'destruct'; } if ( $nameToken->equalsAny([ [T_STRING, 'setUpBeforeClass'], [T_STRING, 'doSetUpBeforeClass'], [T_STRING, 'tearDownAfterClass'], [T_STRING, 'doTearDownAfterClass'], [T_STRING, 'setUp'], [T_STRING, 'doSetUp'], [T_STRING, 'tearDown'], [T_STRING, 'doTearDown'], ], false) ) { return ['phpunit', strtolower($nameToken->getContent())]; } if ('__' === substr($nameToken->getContent(), 0, 2)) { return 'magic'; } return 'method'; } private function findElementEnd(Tokens $tokens, $index) { $index = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$index]->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); } for (++$index; $tokens[$index]->isWhitespace(" \t") || $tokens[$index]->isComment(); ++$index); --$index; return $tokens[$index]->isWhitespace() ? $index - 1 : $index; } private function sortElements(array $elements) { static $phpunitPositions = [ 'setupbeforeclass' => 1, 'dosetupbeforeclass' => 2, 'teardownafterclass' => 3, 'doteardownafterclass' => 4, 'setup' => 5, 'dosetup' => 6, 'teardown' => 7, 'doteardown' => 8, ]; foreach ($elements as &$element) { $type = $element['type']; if (\array_key_exists($type, self::$specialTypes)) { if (isset($this->typePosition[$type])) { $element['position'] = $this->typePosition[$type]; if ('phpunit' === $type) { $element['position'] += $phpunitPositions[$element['name']]; } continue; } $type = 'method'; } if (\in_array($type, ['constant', 'property', 'method'], true)) { $type .= '_'.$element['visibility']; if ($element['static']) { $type .= '_static'; } } $element['position'] = $this->typePosition[$type]; } unset($element); usort($elements, function (array $a, array $b) { if ($a['position'] === $b['position']) { return $this->sortGroupElements($a, $b); } return $a['position'] > $b['position'] ? 1 : -1; }); return $elements; } private function sortGroupElements(array $a, array $b) { $selectedSortAlgorithm = $this->configuration['sortAlgorithm']; if (self::SORT_ALPHA === $selectedSortAlgorithm) { return strcasecmp($a['name'], $b['name']); } return $a['start'] > $b['start'] ? 1 : -1; } private function sortTokens(Tokens $tokens, $startIndex, $endIndex, array $elements) { $replaceTokens = []; foreach ($elements as $element) { for ($i = $element['start']; $i <= $element['end']; ++$i) { $replaceTokens[] = clone $tokens[$i]; } } $tokens->overrideRange($startIndex + 1, $endIndex, $replaceTokens); } } true] ), new CodeSample( ' true] ), new CodeSample( ' true] ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->getSize() - 4; $index > 0; --$index) { if ($tokens[$index]->isClassy()) { $this->fixClassyDefinition($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new AliasedFixerOptionBuilder( new FixerOptionBuilder('multi_line_extends_each_single_line', 'Whether definitions should be multiline.'), 'multiLineExtendsEachSingleLine' )) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new AliasedFixerOptionBuilder( new FixerOptionBuilder('single_item_single_line', 'Whether definitions should be single line when including a single item.'), 'singleItemSingleLine' )) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new AliasedFixerOptionBuilder( new FixerOptionBuilder('single_line', 'Whether definitions should be single line.'), 'singleLine' )) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function fixClassyDefinition(Tokens $tokens, $classyIndex) { $classDefInfo = $this->getClassyDefinitionInfo($tokens, $classyIndex); if (false !== $classDefInfo['implements']) { $classDefInfo['implements'] = $this->fixClassyDefinitionImplements( $tokens, $classDefInfo['open'], $classDefInfo['implements'] ); } if (false !== $classDefInfo['extends']) { $classDefInfo['extends'] = $this->fixClassyDefinitionExtends( $tokens, false === $classDefInfo['implements'] ? $classDefInfo['open'] : $classDefInfo['implements']['start'], $classDefInfo['extends'] ); } $classDefInfo['open'] = $this->fixClassyDefinitionOpenSpacing($tokens, $classDefInfo); if ($classDefInfo['implements']) { $end = $classDefInfo['implements']['start']; } elseif ($classDefInfo['extends']) { $end = $classDefInfo['extends']['start']; } else { $end = $tokens->getPrevNonWhitespace($classDefInfo['open']); } $this->makeClassyDefinitionSingleLine( $tokens, $classDefInfo['anonymousClass'] ? $tokens->getPrevMeaningfulToken($classyIndex) : $classDefInfo['start'], $end ); } private function fixClassyDefinitionExtends(Tokens $tokens, $classOpenIndex, array $classExtendsInfo) { $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); if ($this->configuration['single_line'] || false === $classExtendsInfo['multiLine']) { $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); $classExtendsInfo['multiLine'] = false; } elseif ($this->configuration['single_item_single_line'] && 1 === $classExtendsInfo['numberOfExtends']) { $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); $classExtendsInfo['multiLine'] = false; } elseif ($this->configuration['multi_line_extends_each_single_line'] && $classExtendsInfo['multiLine']) { $this->makeClassyInheritancePartMultiLine($tokens, $classExtendsInfo['start'], $endIndex); $classExtendsInfo['multiLine'] = true; } return $classExtendsInfo; } private function fixClassyDefinitionImplements(Tokens $tokens, $classOpenIndex, array $classImplementsInfo) { $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); if ($this->configuration['single_line'] || false === $classImplementsInfo['multiLine']) { $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); $classImplementsInfo['multiLine'] = false; } elseif ($this->configuration['single_item_single_line'] && 1 === $classImplementsInfo['numberOfImplements']) { $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); $classImplementsInfo['multiLine'] = false; } else { $this->makeClassyInheritancePartMultiLine($tokens, $classImplementsInfo['start'], $endIndex); $classImplementsInfo['multiLine'] = true; } return $classImplementsInfo; } private function fixClassyDefinitionOpenSpacing(Tokens $tokens, array $classDefInfo) { if ($classDefInfo['anonymousClass']) { if (false !== $classDefInfo['implements']) { $spacing = $classDefInfo['implements']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; } elseif (false !== $classDefInfo['extends']) { $spacing = $classDefInfo['extends']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; } else { $spacing = ' '; } } else { $spacing = $this->whitespacesConfig->getLineEnding(); } $openIndex = $tokens->getNextTokenOfKind($classDefInfo['classy'], ['{']); if (' ' !== $spacing && false !== strpos($tokens[$openIndex - 1]->getContent(), "\n")) { return $openIndex; } if ($tokens[$openIndex - 1]->isWhitespace()) { if (' ' !== $spacing || !$tokens[$tokens->getPrevNonWhitespace($openIndex - 1)]->isComment()) { $tokens[$openIndex - 1] = new Token([T_WHITESPACE, $spacing]); } return $openIndex; } $tokens->insertAt($openIndex, new Token([T_WHITESPACE, $spacing])); return $openIndex + 1; } private function getClassyDefinitionInfo(Tokens $tokens, $classyIndex) { $openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']); $prev = $tokens->getPrevMeaningfulToken($classyIndex); $startIndex = $tokens[$prev]->isGivenKind([T_FINAL, T_ABSTRACT]) ? $prev : $classyIndex; $extends = false; $implements = false; $anonymousClass = false; if (!$tokens[$classyIndex]->isGivenKind(T_TRAIT)) { $extends = $tokens->findGivenKind(T_EXTENDS, $classyIndex, $openIndex); $extends = \count($extends) ? $this->getClassyInheritanceInfo($tokens, key($extends), 'numberOfExtends') : false; if (!$tokens[$classyIndex]->isGivenKind(T_INTERFACE)) { $implements = $tokens->findGivenKind(T_IMPLEMENTS, $classyIndex, $openIndex); $implements = \count($implements) ? $this->getClassyInheritanceInfo($tokens, key($implements), 'numberOfImplements') : false; $tokensAnalyzer = new TokensAnalyzer($tokens); $anonymousClass = $tokensAnalyzer->isAnonymousClass($classyIndex); } } return [ 'start' => $startIndex, 'classy' => $classyIndex, 'open' => $openIndex, 'extends' => $extends, 'implements' => $implements, 'anonymousClass' => $anonymousClass, ]; } private function getClassyInheritanceInfo(Tokens $tokens, $startIndex, $label) { $implementsInfo = ['start' => $startIndex, $label => 1, 'multiLine' => false]; ++$startIndex; $endIndex = $tokens->getNextTokenOfKind($startIndex, ['{', [T_IMPLEMENTS], [T_EXTENDS]]); $endIndex = $tokens[$endIndex]->equals('{') ? $tokens->getPrevNonWhitespace($endIndex) : $endIndex; for ($i = $startIndex; $i < $endIndex; ++$i) { if ($tokens[$i]->equals(',')) { ++$implementsInfo[$label]; continue; } if (!$implementsInfo['multiLine'] && false !== strpos($tokens[$i]->getContent(), "\n")) { $implementsInfo['multiLine'] = true; } } return $implementsInfo; } private function makeClassyDefinitionSingleLine(Tokens $tokens, $startIndex, $endIndex) { for ($i = $endIndex; $i >= $startIndex; --$i) { if ($tokens[$i]->isWhitespace()) { $prevNonWhite = $tokens->getPrevNonWhitespace($i); $nextNonWhite = $tokens->getNextNonWhitespace($i); if ($tokens[$prevNonWhite]->isComment() || $tokens[$nextNonWhite]->isComment()) { $content = $tokens[$prevNonWhite]->getContent(); if (!('#' === $content || '//' === substr($content, 0, 2))) { $content = $tokens[$nextNonWhite]->getContent(); if (!('#' === $content || '//' === substr($content, 0, 2))) { $tokens[$i] = new Token([T_WHITESPACE, ' ']); } } continue; } if ($tokens[$i + 1]->equalsAny([',', '(', ')']) || $tokens[$i - 1]->equals('(')) { $tokens->clearAt($i); continue; } $tokens[$i] = new Token([T_WHITESPACE, ' ']); continue; } if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) { $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); continue; } if (!$tokens[$i]->isComment()) { continue; } if (!$tokens[$i + 1]->isWhitespace() && !$tokens[$i + 1]->isComment() && false === strpos($tokens[$i]->getContent(), "\n")) { $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); } if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i - 1]->isComment()) { $tokens->insertAt($i, new Token([T_WHITESPACE, ' '])); } } } private function makeClassyInheritancePartMultiLine(Tokens $tokens, $startIndex, $endIndex) { for ($i = $endIndex; $i > $startIndex; --$i) { $previousInterfaceImplementingIndex = $tokens->getPrevTokenOfKind($i, [',', [T_IMPLEMENTS], [T_EXTENDS]]); $breakAtIndex = $tokens->getNextMeaningfulToken($previousInterfaceImplementingIndex); $this->makeClassyDefinitionSingleLine( $tokens, $breakAtIndex, $i ); $isOnOwnLine = false; for ($j = $breakAtIndex; $j > $previousInterfaceImplementingIndex; --$j) { if (false !== strpos($tokens[$j]->getContent(), "\n")) { $isOnOwnLine = true; break; } } if (!$isOnOwnLine) { if ($tokens[$breakAtIndex - 1]->isWhitespace()) { $tokens[$breakAtIndex - 1] = new Token([ T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent(), ]); } else { $tokens->insertAt($breakAtIndex, new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent()])); } } $i = $previousInterfaceImplementingIndex + 1; } } } isTokenKindFound(T_CLASS); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $classes = array_keys($tokens->findGivenKind(T_CLASS)); $numClasses = \count($classes); for ($i = 0; $i < $numClasses; ++$i) { $index = $classes[$i]; if ($tokensAnalyzer->isAnonymousClass($index)) { continue; } $nspIndex = $tokens->getPrevTokenOfKind($index, [[T_NAMESPACE, 'namespace']]); if (null !== $nspIndex) { $nspIndex = $tokens->getNextMeaningfulToken($nspIndex); if (!$tokens[$nspIndex]->equals('{')) { $nspIndex = $tokens->getNextTokenOfKind($nspIndex, [';', '{']); if ($tokens[$nspIndex]->equals(';')) { break; } $nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex); if ($index < $nspEnd) { for ($j = $i + 1; $j < $numClasses; ++$j) { if ($classes[$j] < $nspEnd) { ++$i; } } continue; } } } $classNameIndex = $tokens->getNextMeaningfulToken($index); $className = $tokens[$classNameIndex]->getContent(); $classStart = $tokens->getNextTokenOfKind($classNameIndex, ['{']); $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart); $this->fixConstructor($tokens, $className, $classStart, $classEnd); $this->fixParent($tokens, $classStart, $classEnd); } } private function fixConstructor(Tokens $tokens, $className, $classStart, $classEnd) { $php4 = $this->findFunction($tokens, $className, $classStart, $classEnd); if (null === $php4) { return; } if (!empty($php4['modifiers'][T_ABSTRACT]) || !empty($php4['modifiers'][T_STATIC])) { return; } $php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd); if (null === $php5) { $tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']); $this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']); return; } list($seq, $case) = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']); if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) { for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) { $tokens->clearAt($i); } return; } list($seq, $case) = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']); if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) { for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) { $tokens->clearAt($i); } $tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']); } } private function fixParent(Tokens $tokens, $classStart, $classEnd) { foreach ($tokens->findGivenKind(T_EXTENDS) as $index => $token) { $parentIndex = $tokens->getNextMeaningfulToken($index); $parentClass = $tokens[$parentIndex]->getContent(); $parentSeq = $tokens->findSequence([ [T_STRING], [T_DOUBLE_COLON], [T_STRING, $parentClass], '(', ], $classStart, $classEnd, [2 => false]); if (null !== $parentSeq) { $parentSeq = array_keys($parentSeq); if ($tokens[$parentSeq[0]]->equalsAny([[T_STRING, 'parent'], [T_STRING, $parentClass]], false)) { $tokens[$parentSeq[0]] = new Token([T_STRING, 'parent']); $tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']); } } $parentSeq = $tokens->findSequence([ [T_VARIABLE, '$this'], [T_OBJECT_OPERATOR], [T_STRING, $parentClass], '(', ], $classStart, $classEnd, [2 => false]); if (null !== $parentSeq) { $parentSeq = array_keys($parentSeq); $tokens[$parentSeq[0]] = new Token([ T_STRING, 'parent', ]); $tokens[$parentSeq[1]] = new Token([ T_DOUBLE_COLON, '::', ]); $tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']); } } } private function fixInfiniteRecursion(Tokens $tokens, $start, $end) { $seq = [ [T_VARIABLE, '$this'], [T_OBJECT_OPERATOR], [T_STRING, '__construct'], ]; while (true) { $callSeq = $tokens->findSequence($seq, $start, $end, [2 => false]); if (null === $callSeq) { return; } $callSeq = array_keys($callSeq); $tokens[$callSeq[0]] = new Token([T_STRING, 'parent']); $tokens[$callSeq[1]] = new Token([T_DOUBLE_COLON, '::']); } } private function getWrapperMethodSequence(Tokens $tokens, $method, $startIndex, $bodyIndex) { $seq = [ '{', [T_VARIABLE, '$this'], [T_OBJECT_OPERATOR], [T_STRING, $method], '(', ]; $case = [3 => false]; $index = $startIndex; while (true) { $index = $tokens->getNextTokenOfKind($index, [[T_VARIABLE]]); if (null === $index || $index >= $bodyIndex) { break; } if (\count($seq) > 5) { $seq[] = ','; } $seq[] = [T_VARIABLE, $tokens[$index]->getContent()]; } $seq[] = ')'; $seq[] = ';'; $seq[] = '}'; return [$seq, $case]; } private function findFunction(Tokens $tokens, $name, $startIndex, $endIndex) { $function = $tokens->findSequence([ [T_FUNCTION], [T_STRING, $name], '(', ], $startIndex, $endIndex, false); if (null === $function) { return null; } $function = array_keys($function); $possibleModifiers = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_ABSTRACT, T_FINAL]; $modifiers = []; $prevBlock = $tokens->getPrevMeaningfulToken($function[0]); while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) { $modifiers[$tokens[$prevBlock]->getId()] = $prevBlock; $prevBlock = $tokens->getPrevMeaningfulToken($prevBlock); } if (isset($modifiers[T_ABSTRACT])) { $bodyStart = null; $funcEnd = $tokens->getNextTokenOfKind($function[2], [';']); } else { $bodyStart = $tokens->getNextTokenOfKind($function[2], ['{']); $funcEnd = null !== $bodyStart ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null; } return [ 'nameIndex' => $function[1], 'startIndex' => $prevBlock + 1, 'endIndex' => $funcEnd, 'bodyIndex' => $bodyStart, 'modifiers' => $modifiers, ]; } } isAnyTokenKindsFound(Token::getClassyTokenKinds()); } public function getPriority() { return 56; } public function getDefinition() { return new FixerDefinition( 'There MUST NOT be more than one property or constant declared per statement.', [ new CodeSample( ' ['property']] ), ] ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $analyzer = new TokensAnalyzer($tokens); $elements = array_reverse($analyzer->getClassyElements(), true); foreach ($elements as $index => $element) { if (!\in_array($element['type'], $this->configuration['elements'], true)) { continue; } $this->fixElement($tokens, $element['type'], $index); } } protected function createConfigurationDefinition() { $values = ['const', 'property']; return new FixerConfigurationResolverRootless('elements', [ (new FixerOptionBuilder('elements', 'List of strings which element should be modified.')) ->setDefault($values) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($values)]) ->getOption(), ], $this->getName()); } private function fixElement(Tokens $tokens, $type, $index) { $tokensAnalyzer = new TokensAnalyzer($tokens); $repeatIndex = $index; while (true) { $repeatIndex = $tokens->getNextMeaningfulToken($repeatIndex); $repeatToken = $tokens[$repeatIndex]; if ($tokensAnalyzer->isArray($repeatIndex)) { if ($repeatToken->isGivenKind(T_ARRAY)) { $repeatIndex = $tokens->getNextTokenOfKind($repeatIndex, ['(']); $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $repeatIndex); } else { $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $repeatIndex); } continue; } if ($repeatToken->equals(';')) { return; } if ($repeatToken->equals(',')) { break; } } $start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']); $this->expandElement( $tokens, $type, $tokens->getNextMeaningfulToken($start), $tokens->getNextTokenOfKind($index, [';']) ); } private function expandElement(Tokens $tokens, $type, $startIndex, $endIndex) { $divisionContent = null; if ($tokens[$startIndex - 1]->isWhitespace()) { $divisionContent = $tokens[$startIndex - 1]->getContent(); if (Preg::match('#(\n|\r\n)#', $divisionContent, $matches)) { $divisionContent = $matches[0].trim($divisionContent, "\r\n"); } } for ($i = $endIndex - 1; $i > $startIndex; --$i) { $token = $tokens[$i]; if ($token->equals(')')) { $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $i); continue; } if (!$tokens[$i]->equals(',')) { continue; } $tokens[$i] = new Token(';'); if ($tokens[$i + 1]->isWhitespace()) { $tokens->clearAt($i + 1); } if (null !== $divisionContent && '' !== $divisionContent) { $tokens->insertAt($i + 1, new Token([T_WHITESPACE, $divisionContent])); } $sequence = $this->getModifiersSequences($tokens, $type, $startIndex, $endIndex); $tokens->insertAt($i + 2, $sequence); } } private function getModifiersSequences(Tokens $tokens, $type, $startIndex, $endIndex) { if ('property' === $type) { $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_VAR, T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT]; } else { $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_CONST]; } $sequence = []; for ($i = $startIndex; $i < $endIndex - 1; ++$i) { if ($tokens[$i]->isComment()) { continue; } if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isGivenKind($tokenKinds)) { break; } $sequence[] = clone $tokens[$i]; } return $sequence; } } isAnyTokenKindsFound([T_CLASS, T_TRAIT]) && $tokens->isAnyTokenKindsFound([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR])) { continue; } while (true) { $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { break; } $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->equals('=')) { $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { $index = $tokens->getNextMeaningfulToken($index); } if ($tokens[$index]->equals([T_STRING, 'null'], false)) { for ($i = $varTokenIndex + 1; $i <= $index; ++$i) { if ( !($tokens[$i]->isWhitespace() && false !== strpos($tokens[$i]->getContent(), "\n")) && !$tokens[$i]->isComment() ) { $tokens->clearAt($i); } } } ++$index; } if (!$tokens[$index]->equals(',')) { break; } } } } } configure([ 'annotation-white-list' => [], 'consider-absent-docblock-as-internal-class' => true, ]); return [$fixer]; } } classElementTypes = []; foreach ($this->configuration['elements'] as $element) { $this->classElementTypes[$element] = true; } } public function getDefinition() { return new FixerDefinition( 'Class, trait and interface elements must be separated with one blank line.', [ new CodeSample( ' ['property']] ), new CodeSample( ' ['const']] ), ] ); } public function getPriority() { return 55; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } protected function applyFix(SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); $class = $classStart = $classEnd = false; foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) { if (!isset($this->classElementTypes[$element['type']])) { continue; } if ($element['classIndex'] !== $class) { $class = $element['classIndex']; $classStart = $tokens->getNextTokenOfKind($class, ['{']); $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart); } if ('method' === $element['type'] && !$tokens[$class]->isGivenKind(T_INTERFACE)) { $attributes = $tokensAnalyzer->getMethodAttributes($index); $methodEnd = true === $attributes['abstract'] ? $tokens->getNextTokenOfKind($index, [';']) : $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($index, ['{'])) ; $this->fixSpaceBelowClassMethod($tokens, $classEnd, $methodEnd); $this->fixSpaceAboveClassElement($tokens, $classStart, $index); continue; } $this->fixSpaceBelowClassElement($tokens, $classEnd, $tokens->getNextTokenOfKind($index, [';'])); $this->fixSpaceAboveClassElement($tokens, $classStart, $index); } } protected function createConfigurationDefinition() { $types = ['const', 'method', 'property']; return new FixerConfigurationResolver([ (new FixerOptionBuilder('elements', sprintf('List of classy elements; \'%s\'.', implode("', '", $types)))) ->setAllowedTypes(['array']) ->setAllowedValues([new AllowedValueSubset($types)]) ->setDefault(['const', 'method', 'property']) ->getOption(), ]); } private function fixSpaceBelowClassElement(Tokens $tokens, $classEndIndex, $elementEndIndex) { for ($nextNotWhite = $elementEndIndex + 1;; ++$nextNotWhite) { if (($tokens[$nextNotWhite]->isComment() || $tokens[$nextNotWhite]->isWhitespace()) && false === strpos($tokens[$nextNotWhite]->getContent(), "\n")) { continue; } break; } if ($tokens[$nextNotWhite]->isWhitespace()) { $nextNotWhite = $tokens->getNextNonWhitespace($nextNotWhite); } $this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex ? 1 : 2); } private function fixSpaceBelowClassMethod(Tokens $tokens, $classEndIndex, $elementEndIndex) { $nextNotWhite = $tokens->getNextNonWhitespace($elementEndIndex); $this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex ? 1 : 2); } private function fixSpaceAboveClassElement(Tokens $tokens, $classStartIndex, $elementIndex) { static $methodAttr = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_ABSTRACT, T_FINAL, T_STATIC, T_STRING, T_NS_SEPARATOR, T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT]; $nonWhiteAbove = null; $firstElementAttributeIndex = $elementIndex; for ($i = $elementIndex; $i > $classStartIndex; --$i) { $nonWhiteAbove = $tokens->getNonWhitespaceSibling($i, -1); if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind($methodAttr)) { $firstElementAttributeIndex = $nonWhiteAbove; } else { break; } } if ($tokens[$nonWhiteAbove]->isGivenKind(T_COMMENT)) { if (1 === $firstElementAttributeIndex - $nonWhiteAbove) { $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1); return; } if (substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) { $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 2); return; } if ($tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0) { $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1); $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove); $nonWhiteAboveComment = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1); $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $classStartIndex ? 1 : 2); } else { $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 2); } return; } if (false === $tokens[$nonWhiteAbove]->isGivenKind(T_DOC_COMMENT)) { $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, $nonWhiteAbove === $classStartIndex ? 1 : 2); return; } $this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1); $nonWhiteAbovePHPDoc = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1); $this->correctLineBreaks($tokens, $nonWhiteAbovePHPDoc, $nonWhiteAbove, $nonWhiteAbovePHPDoc === $classStartIndex ? 1 : 2); } private function correctLineBreaks(Tokens $tokens, $startIndex, $endIndex, $reqLineCount = 2) { $lineEnding = $this->whitespacesConfig->getLineEnding(); ++$startIndex; $numbOfWhiteTokens = $endIndex - $startIndex; if (0 === $numbOfWhiteTokens) { $tokens->insertAt($startIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)])); return; } $lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex); if ($reqLineCount === $lineBreakCount) { return; } if ($lineBreakCount < $reqLineCount) { $tokens[$startIndex] = new Token([ T_WHITESPACE, str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(), ]); return; } if (1 === $numbOfWhiteTokens) { $tokens[$startIndex] = new Token([ T_WHITESPACE, Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount), ]); return; } $toReplaceCount = $lineBreakCount - $reqLineCount; for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) { $tokenLineCount = substr_count($tokens[$i]->getContent(), "\n"); if ($tokenLineCount > 0) { $tokens[$i] = new Token([ T_WHITESPACE, Preg::replace('/\r\n|\n/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)), ]); $toReplaceCount -= $tokenLineCount; } } } private function getLineBreakCount(Tokens $tokens, $whiteSpaceStartIndex, $whiteSpaceEndIndex) { $lineCount = 0; for ($i = $whiteSpaceStartIndex; $i < $whiteSpaceEndIndex; ++$i) { $lineCount += substr_count($tokens[$i]->getContent(), "\n"); } return $lineCount; } private function findCommentBlockStart(Tokens $tokens, $commentIndex) { $start = $commentIndex; for ($i = $commentIndex - 1; $i > 0; --$i) { if ($tokens[$i]->isComment()) { $start = $i; continue; } if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) { break; } } return $start; } } isAllTokenKindsFound([T_FINAL, T_CLASS, T_STATIC]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if (!$tokens[$index]->isGivenKind(T_FINAL)) { continue; } $classTokenIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$classTokenIndex]->isGivenKind(T_CLASS)) { continue; } $startClassIndex = $tokens->getNextTokenOfKind( $classTokenIndex, ['{'] ); $endClassIndex = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $startClassIndex ); $this->replaceStaticAccessWithSelfAccessBetween( $tokens, $startClassIndex, $endClassIndex ); } } private function replaceStaticAccessWithSelfAccessBetween( Tokens $tokens, $startIndex, $endIndex ) { for ($index = $startIndex; $index <= $endIndex; ++$index) { if ($tokens[$index]->isGivenKind(T_CLASS)) { $index = $this->getEndOfAnonymousClass($tokens, $index); continue; } if (!$tokens[$index]->isGivenKind(T_STATIC)) { continue; } $newIndex = $tokens->getPrevMeaningfulToken($index); $doubleColonIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$newIndex]->isGivenKind(T_NEW) && !$tokens[$doubleColonIndex]->isGivenKind(T_DOUBLE_COLON)) { continue; } $tokens[$index] = new Token([T_STRING, 'self']); } } private function getEndOfAnonymousClass(Tokens $tokens, $index) { $instantiationBraceStart = $tokens->getNextMeaningfulToken($index); if ($tokens[$instantiationBraceStart]->equals('(')) { $index = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $instantiationBraceStart ); } $bodyBraceStart = $tokens->getNextTokenOfKind($index, ['{']); return $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyBraceStart ); } } isAnyTokenKindsFound(Token::getClassyTokenKinds()); } public function getDefinition() { return new FixerDefinition( 'There should be no empty lines after class opening brace.', [ new CodeSample( ' $token) { if (!$token->isClassy()) { continue; } $startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); if (!$tokens[$startBraceIndex + 1]->isWhitespace()) { continue; } $this->fixWhitespace($tokens, $startBraceIndex + 1); } } private function fixWhitespace(Tokens $tokens, $index) { $content = $tokens[$index]->getContent(); if (substr_count($content, "\n") > 1) { $tokens[$index] = new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding().substr($content, strrpos($content, "\n") + 1)]); } } } configuration['annotation-white-list'], $this->configuration['annotation-black-list'] ); if (\count($intersect)) { throw new InvalidFixerConfigurationException($this->getName(), sprintf('Annotation cannot be used in both the include and exclude list, got duplicates: "%s".', implode('", "', array_keys($intersect)))); } } public function getDefinition() { return new FixerDefinition( 'Internal classes should be `final`.', [ new CodeSample(" ['@Custom'], ] ), ], null, 'Changing classes to `final` might cause code execution to break.' ); } public function getPriority() { return 67; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_CLASS); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isClassCandidate($tokens, $index)) { continue; } $tokens->insertAt( $index, [ new Token([T_FINAL, 'final']), new Token([T_WHITESPACE, ' ']), ] ); } } protected function createConfigurationDefinition() { $annotationsAsserts = [static function (array $values) { foreach ($values as $value) { if (!\is_string($value) || '' === $value) { return false; } } return true; }]; $annotationsNormalizer = static function (Options $options, array $value) { $newValue = []; foreach ($value as $key) { if ('@' === $key[0]) { $key = substr($key, 1); } $newValue[strtolower($key)] = true; } return $newValue; }; return new FixerConfigurationResolver([ (new FixerOptionBuilder('annotation-white-list', 'Class level annotations tags that must be set in order to fix the class. (case insensitive)')) ->setAllowedTypes(['array']) ->setAllowedValues($annotationsAsserts) ->setDefault(['@internal']) ->setNormalizer($annotationsNormalizer) ->getOption(), (new FixerOptionBuilder('annotation-black-list', 'Class level annotations tags that must be omitted to fix the class, even if all of the excluded ones are used as well. (case insensitive)')) ->setAllowedTypes(['array']) ->setAllowedValues($annotationsAsserts) ->setDefault([ '@final', '@Entity', '@ORM\Entity', '@ORM\Mapping\Entity', '@Mapping\Entity', ]) ->setNormalizer($annotationsNormalizer) ->getOption(), (new FixerOptionBuilder('consider-absent-docblock-as-internal-class', 'Should classes without any DocBlock be fixed to final?')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function isClassCandidate(Tokens $tokens, $index) { if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_ABSTRACT, T_FINAL, T_NEW])) { return false; } $docToken = $tokens[$tokens->getPrevNonWhitespace($index)]; if (!$docToken->isGivenKind(T_DOC_COMMENT)) { return $this->configuration['consider-absent-docblock-as-internal-class']; } $doc = new DocBlock($docToken->getContent()); $tags = []; foreach ($doc->getAnnotations() as $annotation) { Preg::match('/@\S+(?=\s|$)/', $annotation->getContent(), $matches); $tag = strtolower(substr(array_shift($matches), 1)); foreach ($this->configuration['annotation-black-list'] as $tagStart => $true) { if (0 === strpos($tag, $tagStart)) { return false; } } $tags[$tag] = true; } foreach ($this->configuration['annotation-white-list'] as $tag => $true) { if (!isset($tags[$tag])) { return false; } } return true; } } true, '__destruct' => true, '__call' => true, '__callstatic' => true, '__get' => true, '__set' => true, '__isset' => true, '__unset' => true, '__sleep' => true, '__wakeup' => true, '__tostring' => true, '__invoke' => true, '__set_state' => true, '__clone' => true, '__debuginfo' => true, ]; public function getDefinition() { return new FixerDefinition( 'All `public` methods of `abstract` classes should be `final`.', [ new CodeSample( 'isAllTokenKindsFound([T_CLASS, T_ABSTRACT, T_PUBLIC, T_FUNCTION]); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $classes = array_keys($tokens->findGivenKind(T_CLASS)); while ($classIndex = array_pop($classes)) { $prevToken = $tokens[$tokens->getPrevMeaningfulToken($classIndex)]; if (!$prevToken->isGivenKind([T_ABSTRACT])) { continue; } $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); $this->fixClass($tokens, $classOpen, $classClose); } } private function fixClass(Tokens $tokens, $classOpenIndex, $classCloseIndex) { for ($index = $classCloseIndex - 1; $index > $classOpenIndex; --$index) { if ($tokens[$index]->equals('}')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if (!$tokens[$index]->isGivenKind(T_PUBLIC)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$nextIndex]; if ($nextToken->isGivenKind(T_STATIC)) { $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); $nextToken = $tokens[$nextIndex]; } if (!$nextToken->isGivenKind(T_FUNCTION)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); $nextToken = $tokens[$nextIndex]; if (isset($this->magicMethods[strtolower($nextToken->getContent())])) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->isGivenKind(T_STATIC)) { $index = $prevIndex; $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; } if ($prevToken->isGivenKind([T_ABSTRACT, T_FINAL])) { $index = $prevIndex; continue; } $tokens->insertAt( $index, [ new Token([T_FINAL, 'final']), new Token([T_WHITESPACE, ' ']), ] ); } } } isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $isInNamespace = false; $isImported = false; for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_NAMESPACE)) { $isInNamespace = true; continue; } if ($token->isGivenKind(T_USE) && $isInNamespace) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ('datetime' !== strtolower($tokens[$nextIndex]->getContent())) { continue; } $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if ($tokens[$nextNextIndex]->equals(';')) { $isImported = true; } $index = $nextNextIndex; continue; } if (!$token->isGivenKind(T_STRING)) { continue; } $lowercaseContent = strtolower($token->getContent()); if ('datetime' === $lowercaseContent) { $this->fixClassUsage($tokens, $index, $isInNamespace, $isImported); $limit = $tokens->count(); } 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'); } } } private function fixClassUsage(Tokens $tokens, $index, $isInNamespace, $isImported) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind(T_DOUBLE_COLON)) { $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if ($tokens[$nextNextIndex]->isGivenKind(T_STRING)) { $nextNextNextIndex = $tokens->getNextMeaningfulToken($nextNextIndex); if (!$tokens[$nextNextNextIndex]->equals('(')) { return; } } } $isUsedAlone = false; $isUsedWithLeadingBackslash = false; $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); if (!$tokens[$prevPrevIndex]->isGivenKind(T_STRING)) { $isUsedWithLeadingBackslash = true; } } elseif (!$tokens[$prevIndex]->isGivenKind([T_DOUBLE_COLON, T_OBJECT_OPERATOR])) { $isUsedAlone = true; } if ($isUsedWithLeadingBackslash || $isUsedAlone && ($isInNamespace && $isImported || !$isInNamespace)) { $tokens[$index] = new Token([T_STRING, \DateTimeImmutable::class]); if ($isInNamespace && $isUsedAlone) { $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } } private function fixFunctionUsage(Tokens $tokens, $index, $replacement) { $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind([T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR])) { 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]); } } isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_START_HEREDOC]); } public function getDefinition() { return new FixerDefinition( 'There should not be a binary flag before strings.', [ new CodeSample(" $token) { if (!$token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_START_HEREDOC])) { continue; } $content = $token->getContent(); if ('b' === strtolower($content[0])) { $tokens[$index] = new Token([$token->getId(), substr($content, 1)]); } } } } isTokenKindFound(T_DOLLAR_OPEN_CURLY_BRACES); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 3; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_DOLLAR_OPEN_CURLY_BRACES)) { continue; } $varnameToken = $tokens[$index + 1]; if (!$varnameToken->isGivenKind(T_STRING_VARNAME)) { continue; } $dollarCloseToken = $tokens[$index + 2]; if (!$dollarCloseToken->isGivenKind(CT::T_DOLLAR_CLOSE_CURLY_BRACES)) { continue; } $tokenOfStringBeforeToken = $tokens[$index - 1]; $stringContent = $tokenOfStringBeforeToken->getContent(); if ('$' === substr($stringContent, -1) && '\\$' !== substr($stringContent, -2)) { $newContent = substr($stringContent, 0, -1).'\\$'; $tokenOfStringBeforeToken = new Token([T_ENCAPSED_AND_WHITESPACE, $newContent]); } $tokens->overrideRange($index - 1, $index + 2, [ $tokenOfStringBeforeToken, new Token([T_CURLY_OPEN, '{']), new Token([T_VARIABLE, '$'.$varnameToken->getContent()]), new Token([CT::T_CURLY_CLOSE, '}']), ]); } } } isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML]); } public function isRisky() { return true; } public function getDefinition() { return new FixerDefinition( 'All multi-line strings must use correct line ending.', [ new CodeSample( "whitespacesConfig->getLineEnding(); foreach ($tokens as $tokenIndex => $token) { if (!$token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML])) { continue; } $tokens[$tokenIndex] = new Token([ $token->getId(), Preg::replace( '#\R#u', $ending, $token->getContent() ), ]); } } } true] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_CONSTANT_ENCAPSED_STRING); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { continue; } $content = $token->getContent(); $prefix = ''; if ('b' === strtolower($content[0])) { $prefix = $content[0]; $content = substr($content, 1); } if ( '"' === $content[0] && (true === $this->configuration['strings_containing_single_quote_chars'] || false === strpos($content, "'")) && !Preg::match('/(?setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } } true] ), new CodeSample( $codeSample, ['double_quoted' => false] ), new CodeSample( $codeSample, ['heredoc_syntax' => false] ), ], 'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash ' .'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain ' .'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes ' ."that do not start a special interpretation with the char after them.\n" .'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash ' .'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted ' .'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.' ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_ENCAPSED_AND_WHITESPACE, T_CONSTANT_ENCAPSED_STRING]); } public function getPriority() { return 1; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $singleQuotedRegex = '/(? $token) { $content = $token->getContent(); if ($token->equalsAny(['"', 'b"', 'B"'])) { $doubleQuoteOpened = !$doubleQuoteOpened; } if (!$token->isGivenKind([T_ENCAPSED_AND_WHITESPACE, T_CONSTANT_ENCAPSED_STRING]) || false === strpos($content, '\\')) { continue; } if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) && '\'' === substr(rtrim($tokens[$index - 1]->getContent()), -1)) { continue; } $firstTwoCharacters = strtolower(substr($content, 0, 2)); $isSingleQuotedString = $token->isGivenKind(T_CONSTANT_ENCAPSED_STRING) && ('\'' === $content[0] || 'b\'' === $firstTwoCharacters); $isDoubleQuotedString = ($token->isGivenKind(T_CONSTANT_ENCAPSED_STRING) && ('"' === $content[0] || 'b"' === $firstTwoCharacters)) || ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) && $doubleQuoteOpened) ; $isHeredocSyntax = !$isSingleQuotedString && !$isDoubleQuotedString; if ( (false === $this->configuration['single_quoted'] && $isSingleQuotedString) || (false === $this->configuration['double_quoted'] && $isDoubleQuotedString) || (false === $this->configuration['heredoc_syntax'] && $isHeredocSyntax) ) { continue; } $regex = $heredocSyntaxRegex; if ($isSingleQuotedString) { $regex = $singleQuotedRegex; } elseif ($isDoubleQuotedString) { $regex = $doubleQuotedRegex; } $newContent = Preg::replace($regex, '\\\\\\\\$1', $content); if ($newContent !== $content) { $tokens[$index] = new Token([$token->getId(), $newContent]); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('single_quoted', 'Whether to fix single-quoted strings.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('double_quoted', 'Whether to fix double-quoted strings.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('heredoc_syntax', 'Whether to fix heredoc syntax.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } } isTokenKindFound(T_START_HEREDOC); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_START_HEREDOC) || false !== strpos($token->getContent(), "'")) { continue; } if ($tokens[$index + 1]->isGivenKind(T_END_HEREDOC)) { $tokens[$index] = $this->convertToNowdoc($token); continue; } if ( !$tokens[$index + 1]->isGivenKind(T_ENCAPSED_AND_WHITESPACE) || !$tokens[$index + 2]->isGivenKind(T_END_HEREDOC) ) { continue; } $content = $tokens[$index + 1]->getContent(); if (Preg::match('/(?convertToNowdoc($token); $content = str_replace(['\\\\', '\\$'], ['\\', '$'], $content); $tokens[$index + 1] = new Token([ $tokens[$index + 1]->getId(), $content, ]); } } private function convertToNowdoc(Token $token) { return new Token([ $token->getId(), Preg::replace('/^([Bb]?<<<)(\h*)"?([^\s"]+)"?/', '$1$2\'$3\'', $token->getContent()), ]); } } country !"; $c = "I have $farm[0] chickens !"; EOT )], 'The reasoning behind this rule is the following:' ."\n".'- When there are two valid ways of doing the same thing, using both is confusing, there should be a coding standard to follow' ."\n".'- PHP manual marks `"$var"` syntax as implicit and `"${var}"` syntax as explicit: explicit code should always be preferred' ."\n".'- Explicit syntax allows word concatenation inside strings, e.g. `"${var}IsAVar"`, implicit doesn\'t' ."\n".'- Explicit syntax is easier to detect for IDE/editors and therefore has colors/highlight with higher contrast, which is easier to read' ."\n".'Backtick operator is skipped because it is harder to handle; you can use `backtick_to_shell_exec` fixer to normalize backticks to strings' ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_VARIABLE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $backtickStarted = false; for ($index = \count($tokens) - 1; $index > 0; --$index) { $token = $tokens[$index]; if ($token->equals('`')) { $backtickStarted = !$backtickStarted; continue; } if ($backtickStarted || !$token->isGivenKind(T_VARIABLE)) { continue; } $prevToken = $tokens[$index - 1]; if (!$this->isStringPartToken($prevToken)) { continue; } $distinctVariableIndex = $index; $variableTokens = [ $distinctVariableIndex => [ 'tokens' => [$index => $token], 'firstVariableTokenIndex' => $index, 'lastVariableTokenIndex' => $index, ], ]; $nextIndex = $index + 1; $squareBracketCount = 0; while (!$this->isStringPartToken($tokens[$nextIndex])) { if ($tokens[$nextIndex]->isGivenKind(T_CURLY_OPEN)) { $nextIndex = $tokens->getNextTokenOfKind($nextIndex, [[CT::T_CURLY_CLOSE]]); } elseif ($tokens[$nextIndex]->isGivenKind(T_VARIABLE) && 1 !== $squareBracketCount) { $distinctVariableIndex = $nextIndex; $variableTokens[$distinctVariableIndex] = [ 'tokens' => [$nextIndex => $tokens[$nextIndex]], 'firstVariableTokenIndex' => $nextIndex, 'lastVariableTokenIndex' => $nextIndex, ]; } else { $variableTokens[$distinctVariableIndex]['tokens'][$nextIndex] = $tokens[$nextIndex]; $variableTokens[$distinctVariableIndex]['lastVariableTokenIndex'] = $nextIndex; if ($tokens[$nextIndex]->equalsAny(['[', ']'])) { ++$squareBracketCount; } } ++$nextIndex; } krsort($variableTokens, SORT_NUMERIC); foreach ($variableTokens as $distinctVariableSet) { if (1 === \count($distinctVariableSet['tokens'])) { $singleVariableIndex = key($distinctVariableSet['tokens']); $singleVariableToken = current($distinctVariableSet['tokens']); $tokens->overrideRange($singleVariableIndex, $singleVariableIndex, [ new Token([T_DOLLAR_OPEN_CURLY_BRACES, '${']), new Token([T_STRING_VARNAME, substr($singleVariableToken->getContent(), 1)]), new Token([CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}']), ]); } else { foreach ($distinctVariableSet['tokens'] as $variablePartIndex => $variablePartToken) { if ($variablePartToken->isGivenKind(T_NUM_STRING)) { $tokens[$variablePartIndex] = new Token([T_LNUMBER, $variablePartToken->getContent()]); continue; } if ($variablePartToken->isGivenKind(T_STRING) && $tokens[$variablePartIndex + 1]->equals(']')) { $tokens[$variablePartIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, "'".$variablePartToken->getContent()."'"]); } } $tokens->insertAt($distinctVariableSet['lastVariableTokenIndex'] + 1, new Token([CT::T_CURLY_CLOSE, '}'])); $tokens->insertAt($distinctVariableSet['firstVariableTokenIndex'], new Token([T_CURLY_OPEN, '{'])); } } } } private function isStringPartToken(Token $token) { return $token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) || $token->isGivenKind(T_START_HEREDOC) || '"' === $token->getContent() || 'b"' === strtolower($token->getContent()) ; } } bindTo` on lambdas without referencing to `$this`.' ); } public function isCandidate(Tokens $tokens) { if (\PHP_VERSION_ID >= 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return $tokens->isTokenKindFound(T_FUNCTION); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $analyzer = new TokensAnalyzer($tokens); $expectedFunctionKinds = [T_FUNCTION]; if (\PHP_VERSION_ID >= 70400) { $expectedFunctionKinds[] = T_FN; } for ($index = $tokens->count() - 4; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind($expectedFunctionKinds) || !$analyzer->isLambda($index)) { continue; } $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(T_STATIC)) { continue; } $argumentsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); $argumentsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStartIndex); if ($tokens[$index]->isGivenKind(T_FUNCTION)) { $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, ['{']); $lambdaEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $lambdaOpenIndex); } else { $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, [[T_DOUBLE_ARROW]]); $lambdaEndIndex = $this->findExpressionEnd($tokens, $lambdaOpenIndex); } if ($this->hasPossibleReferenceToThis($tokens, $lambdaOpenIndex, $lambdaEndIndex)) { continue; } $tokens->insertAt( $index, [ new Token([T_STATIC, 'static']), new Token([T_WHITESPACE, ' ']), ] ); $index -= 4; } } private function findExpressionEnd(Tokens $tokens, $index) { $nextIndex = $tokens->getNextMeaningfulToken($index); while (null !== $nextIndex) { $nextToken = $tokens[$nextIndex]; if ($nextToken->equalsAny([',', ';', [T_CLOSE_TAG]])) { break; } $blockType = Tokens::detectBlockType($nextToken); if (null !== $blockType && $blockType['isStart']) { $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); } $index = $nextIndex; $nextIndex = $tokens->getNextMeaningfulToken($index); } return $index; } private function hasPossibleReferenceToThis(Tokens $tokens, $startIndex, $endIndex) { for ($i = $startIndex; $i < $endIndex; ++$i) { if ($tokens[$i]->isGivenKind(T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { return true; } if ($tokens[$i]->isGivenKind([ T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE, CT::T_DYNAMIC_VAR_BRACE_OPEN, T_EVAL, ])) { return true; } if ($tokens[$i]->equals('$')) { $nextIndex = $tokens->getNextMeaningfulToken($i); if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { return true; } } } return false; } } false] ), ], 'Rule is applied only in a PHP 7.1+ environment.' ); } public function isCandidate(Tokens $tokens) { if (\PHP_VERSION_ID < 70100) { return false; } if (!$tokens->isTokenKindFound(T_VARIABLE)) { return false; } if (\PHP_VERSION_ID >= 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return $tokens->isTokenKindFound(T_FUNCTION); } public function getPriority() { return 1; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use_nullable_type_declaration', 'Whether to add or remove `?` before type declarations for parameters with a default `null` value.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionsAnalyzer = new FunctionsAnalyzer(); $tokenKinds = [T_FUNCTION]; if (\PHP_VERSION_ID >= 70400) { $tokenKinds[] = T_FN; } for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind($tokenKinds)) { continue; } $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); $this->fixFunctionParameters($tokens, $arguments); } } private function fixFunctionParameters(Tokens $tokens, array $arguments) { foreach (array_reverse($arguments) as $argumentInfo) { if ( !$argumentInfo->hasTypeAnalysis() || !$argumentInfo->hasDefault() || 'null' !== strtolower($argumentInfo->getDefault()) ) { continue; } $argumentTypeInfo = $argumentInfo->getTypeAnalysis(); if (true === $this->configuration['use_nullable_type_declaration']) { if (!$argumentTypeInfo->isNullable()) { $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_NULLABLE_TYPE, '?'])); } } else { if ($argumentTypeInfo->isNullable()) { $tokens->removeTrailingWhitespace($argumentTypeInfo->getStartIndex()); $tokens->clearTokenAndMergeSurroundingWhitespace($argumentTypeInfo->getStartIndex()); } } } } } isTokenKindFound(T_STRING); } public function getPriority() { return -1; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionsAnalyzer = new FunctionsAnalyzer(); for ($index = \count($tokens) - 1; $index > 0; --$index) { if (!$tokens[$index]->equals([T_STRING, 'implode'], false)) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $argumentsIndices = $this->getArgumentIndices($tokens, $index); if (1 === \count($argumentsIndices)) { $firstArgumentIndex = key($argumentsIndices); $tokens->insertAt($firstArgumentIndex, [ new Token([T_CONSTANT_ENCAPSED_STRING, "''"]), new Token(','), new Token([T_WHITESPACE, ' ']), ]); continue; } if (2 === \count($argumentsIndices)) { list($firstArgumentIndex, $secondArgumentIndex) = array_keys($argumentsIndices); if ($tokens[$firstArgumentIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { continue; } if (!$tokens[$secondArgumentIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { continue; } $firstArgumentEndIndex = $argumentsIndices[key($argumentsIndices)]; $newSecondArgumentTokens = []; for ($i = key($argumentsIndices); $i <= $firstArgumentEndIndex; ++$i) { $newSecondArgumentTokens[] = clone $tokens[$i]; $tokens->clearAt($i); } $tokens->insertAt($firstArgumentIndex, clone $tokens[$secondArgumentIndex]); ++$secondArgumentIndex; $tokens->clearAt($secondArgumentIndex); $tokens->insertAt($secondArgumentIndex, $newSecondArgumentTokens); } } } private function getArgumentIndices(Tokens $tokens, $functionNameIndex) { $argumentsAnalyzer = new ArgumentsAnalyzer(); $openParenthesis = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); $indices = []; foreach ($argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis) as $startIndexCandidate => $endIndex) { $indices[$tokens->getNextMeaningfulToken($startIndexCandidate - 1)] = $tokens->getPrevMeaningfulToken($endIndex + 1); } return $indices; } } isAnyTokenKindsFound(array_merge($this->getFunctionyTokenKinds(), [T_STRING])); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionyTokens = $this->getFunctionyTokenKinds(); $languageConstructionTokens = $this->getLanguageConstructionTokenKinds(); $braceTypes = $this->getBraceAfterVariableKinds(); foreach ($tokens as $index => $token) { if (!$token->equals('(')) { continue; } $lastTokenIndex = $tokens->getPrevNonWhitespace($index); $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex); if ( null !== $nextNonWhiteSpace && $tokens[$nextNonWhiteSpace]->equals('?') && $tokens[$lastTokenIndex]->isGivenKind($languageConstructionTokens) ) { continue; } if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) { $this->fixFunctionCall($tokens, $index); } elseif ($tokens[$lastTokenIndex]->isGivenKind(T_STRING)) { $possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex); if (!$tokens[$possibleDefinitionIndex]->isGivenKind(T_FUNCTION)) { $this->fixFunctionCall($tokens, $index); } } elseif ($tokens[$lastTokenIndex]->equalsAny($braceTypes)) { $block = Tokens::detectBlockType($tokens[$lastTokenIndex]); if ( Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $block['type'] || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $block['type'] || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE === $block['type'] ) { $this->fixFunctionCall($tokens, $index); } } } } private function fixFunctionCall(Tokens $tokens, $index) { if ($tokens[$index - 1]->isWhitespace()) { $tokens->clearAt($index - 1); } } private function getBraceAfterVariableKinds() { static $tokens = [ ')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], ]; return $tokens; } private function getFunctionyTokenKinds() { static $tokens = [ T_ARRAY, T_ECHO, T_EMPTY, T_EVAL, T_EXIT, T_INCLUDE, T_INCLUDE_ONCE, T_ISSET, T_LIST, T_PRINT, T_REQUIRE, T_REQUIRE_ONCE, T_UNSET, T_VARIABLE, ]; return $tokens; } private function getLanguageConstructionTokenKinds() { static $languageConstructionTokens = [ T_ECHO, T_PRINT, T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE, ]; return $languageConstructionTokens; } } = 7.0.', [ new VersionSpecificCodeSample( "= 70000 && $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } public function getPriority() { return 3; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $dirnameInfo = $this->getDirnameInfo($tokens, $index); if (!$dirnameInfo) { continue; } $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indexes'][0]); if (!$tokens[$prev]->equals('(')) { continue; } $prev = $tokens->getPrevMeaningfulToken($prev); $firstArgumentEnd = $dirnameInfo['end']; $dirnameInfoArray = [$dirnameInfo]; while ($dirnameInfo = $this->getDirnameInfo($tokens, $prev, $firstArgumentEnd)) { $dirnameInfoArray[] = $dirnameInfo; $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indexes'][0]); if (!$tokens[$prev]->equals('(')) { break; } $prev = $tokens->getPrevMeaningfulToken($prev); $firstArgumentEnd = $dirnameInfo['end']; } if (\count($dirnameInfoArray) > 1) { $this->combineDirnames($tokens, $dirnameInfoArray); } $index = $prev; } } private function getDirnameInfo(Tokens $tokens, $index, $firstArgumentEndIndex = null) { if (!$tokens[$index]->equals([T_STRING, 'dirname'], false)) { return false; } if (!(new FunctionsAnalyzer())->isGlobalFunctionCall($tokens, $index)) { return false; } $info['indexes'] = []; $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(T_NS_SEPARATOR)) { $info['indexes'][] = $prev; } $info['indexes'][] = $index; $next = $tokens->getNextMeaningfulToken($index); $info['indexes'][] = $next; if (null !== $firstArgumentEndIndex) { $next = $tokens->getNextMeaningfulToken($firstArgumentEndIndex); } else { $next = $tokens->getNextMeaningfulToken($next); if ($tokens[$next]->equals(')')) { return false; } while (!$tokens[$next]->equalsAny([',', ')'])) { $blockType = Tokens::detectBlockType($tokens[$next]); if ($blockType) { $next = $tokens->findBlockEnd($blockType['type'], $next); } $next = $tokens->getNextMeaningfulToken($next); } } $info['indexes'][] = $next; if ($tokens[$next]->equals(',')) { $next = $tokens->getNextMeaningfulToken($next); $info['indexes'][] = $next; } if ($tokens[$next]->equals(')')) { $info['levels'] = 1; $info['end'] = $next; return $info; } if (!$tokens[$next]->isGivenKind(T_LNUMBER)) { return false; } $info['secondArgument'] = $next; $info['levels'] = (int) $tokens[$next]->getContent(); $next = $tokens->getNextMeaningfulToken($next); if ($tokens[$next]->equals(',')) { $info['indexes'][] = $next; $next = $tokens->getNextMeaningfulToken($next); } if (!$tokens[$next]->equals(')')) { return false; } $info['indexes'][] = $next; $info['end'] = $next; return $info; } private function combineDirnames(Tokens $tokens, array $dirnameInfoArray) { $outerDirnameInfo = array_pop($dirnameInfoArray); $levels = $outerDirnameInfo['levels']; foreach ($dirnameInfoArray as $dirnameInfo) { $levels += $dirnameInfo['levels']; foreach ($dirnameInfo['indexes'] as $index) { $tokens->removeLeadingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } $levelsToken = new Token([T_LNUMBER, (string) $levels]); if (isset($outerDirnameInfo['secondArgument'])) { $tokens[$outerDirnameInfo['secondArgument']] = $levelsToken; } else { $prev = $tokens->getPrevMeaningfulToken($outerDirnameInfo['end']); $items = []; if (!$tokens[$prev]->equals(',')) { $items = [new Token(','), new Token([T_WHITESPACE, ' '])]; } $items[] = $levelsToken; $tokens->insertAt($outerDirnameInfo['end'], $items); } } } = 7.1.', [ new VersionSpecificCodeSample( "= 70100 && $tokens->isTokenKindFound(T_FUNCTION); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $excludeFuncNames = [ [T_STRING, '__construct'], [T_STRING, '__destruct'], [T_STRING, '__clone'], ]; for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $funcName = $tokens->getNextMeaningfulToken($index); if ($tokens[$funcName]->equalsAny($excludeFuncNames, false)) { continue; } $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($this->hasReturnTypeHint($tokens, $startIndex)) { continue; } if ($tokens[$startIndex]->equals(';')) { if ($this->hasVoidReturnAnnotation($tokens, $index)) { $this->fixFunctionDefinition($tokens, $startIndex); } continue; } if ($this->hasReturnAnnotation($tokens, $index)) { continue; } $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); if ($this->hasVoidReturn($tokens, $startIndex, $endIndex)) { $this->fixFunctionDefinition($tokens, $startIndex); } } } private function hasReturnAnnotation(Tokens $tokens, $index) { foreach ($this->findReturnAnnotations($tokens, $index) as $return) { if (['void'] !== $return->getTypes()) { return true; } } return false; } private function hasVoidReturnAnnotation(Tokens $tokens, $index) { foreach ($this->findReturnAnnotations($tokens, $index) as $return) { if (['void'] === $return->getTypes()) { return true; } } return false; } private function hasReturnTypeHint(Tokens $tokens, $index) { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); } private function hasVoidReturn(Tokens $tokens, $startIndex, $endIndex) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($i = $startIndex; $i < $endIndex; ++$i) { if ( ($tokens[$i]->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) || ($tokens[$i]->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($i)) ) { $i = $tokens->getNextTokenOfKind($i, ['{']); $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); continue; } if ($tokens[$i]->isGivenKind([T_YIELD, T_YIELD_FROM])) { return false; } if (!$tokens[$i]->isGivenKind(T_RETURN)) { continue; } $i = $tokens->getNextMeaningfulToken($i); if (!$tokens[$i]->equals(';')) { return false; } } return true; } private function fixFunctionDefinition(Tokens $tokens, $index) { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $tokens->insertAt($endFuncIndex + 1, [ new Token([CT::T_TYPE_COLON, ':']), new Token([T_WHITESPACE, ' ']), new Token([T_STRING, 'void']), ]); } private function findReturnAnnotations(Tokens $tokens, $index) { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([ T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, ])); if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { return []; } $doc = new DocBlock($tokens[$index]->getContent()); return $doc->getAnnotationsOfType('return'); } } isTokenKindFound(T_THROW); } public function getPriority() { return 1; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind(T_THROW)) { continue; } $openingBraceCandidateIndex = $tokens->getNextTokenOfKind($index, [';', '(']); while ($tokens[$openingBraceCandidateIndex]->equals('(')) { $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingBraceCandidateIndex); $openingBraceCandidateIndex = $tokens->getNextTokenOfKind($closingBraceIndex, [';', '(']); } $this->trimNewLines($tokens, $index, $openingBraceCandidateIndex); } } private function trimNewLines(Tokens $tokens, $startIndex, $endIndex) { for ($index = $startIndex; $index < $endIndex; ++$index) { $content = $tokens[$index]->getContent(); if ($tokens[$index]->isGivenKind(T_COMMENT)) { if (0 === strpos($content, '//')) { $content = '/*'.substr($content, 2).' */'; $tokens->clearAt($index + 1); } elseif (0 === strpos($content, '#')) { $content = '/*'.substr($content, 1).' */'; $tokens->clearAt($index + 1); } elseif (false !== Preg::match('/\R/', $content)) { $content = Preg::replace('/\R/', ' ', $content); } $tokens[$index] = new Token([T_COMMENT, $content]); continue; } if (!$tokens[$index]->isGivenKind(T_WHITESPACE)) { continue; } if (0 === Preg::match('/\R/', $content)) { continue; } $prevIndex = $tokens->getNonEmptySibling($index, -1); if ($tokens[$prevIndex]->equalsAny(array_merge(self::REMOVE_WHITESPACE_AFTER_TOKENS, self::REMOVE_WHITESPACE_AROUND_TOKENS))) { $tokens->clearAt($index); continue; } $nextIndex = $tokens->getNonEmptySibling($index, 1); if ( $tokens[$nextIndex]->equalsAny(array_merge(self::REMOVE_WHITESPACE_AROUND_TOKENS, self::REMOVE_WHITESPACE_BEFORE_TOKENS)) && !$tokens[$prevIndex]->isGivenKind(T_FUNCTION) ) { $tokens->clearAt($index); continue; } $tokens[$index] = new Token([T_WHITESPACE, ' ']); } } } 'none'] ), new VersionSpecificCodeSample( " 'one'] ), ], 'Rule is applied only in a PHP 7+ environment.' ); } public function getPriority() { return -17; } public function isCandidate(Tokens $tokens) { return \PHP_VERSION_ID >= 70000 && $tokens->isTokenKindFound(CT::T_TYPE_COLON); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $oneSpaceBefore = 'one' === $this->configuration['space_before']; for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { if (!$tokens[$index]->isGivenKind(CT::T_TYPE_COLON)) { continue; } $previousIndex = $index - 1; $previousToken = $tokens[$previousIndex]; if ($previousToken->isWhitespace()) { if (!$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { if ($oneSpaceBefore) { $tokens[$previousIndex] = new Token([T_WHITESPACE, ' ']); } else { $tokens->clearAt($previousIndex); } } } elseif ($oneSpaceBefore) { $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); if ($tokenWasAdded) { ++$limit; } ++$index; } ++$index; $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); if ($tokenWasAdded) { ++$limit; } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('space_before', 'Spacing to apply before colon.')) ->setAllowedValues(['one', 'none']) ->setDefault('none') ->getOption(), ]); } } \[\])*$/'; const MINIMUM_PHP_VERSION = 70000; private $excludeFuncNames = [ [T_STRING, '__clone'], [T_STRING, '__destruct'], ]; private $skippedTypes = [ 'mixed' => true, 'resource' => true, 'static' => true, 'void' => true, ]; public function getDefinition() { return new FixerDefinition( 'EXPERIMENTAL: Takes `@param` annotations of non-mixed types and adjusts accordingly the function signature. Requires PHP >= 7.0.', [ new VersionSpecificCodeSample( '= self::MINIMUM_PHP_VERSION && $tokens->isTokenKindFound(T_FUNCTION); } public function getPriority() { return 8; } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; 0 < $index; --$index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { continue; } $funcName = $tokens->getNextMeaningfulToken($index); if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, false)) { continue; } $paramTypeAnnotations = $this->findParamAnnotations($tokens, $index); foreach ($paramTypeAnnotations as $paramTypeAnnotation) { if (\PHP_VERSION_ID < self::MINIMUM_PHP_VERSION) { continue; } $types = array_values($paramTypeAnnotation->getTypes()); $paramType = current($types); if (isset($this->skippedTypes[$paramType])) { continue; } $hasIterable = false; $hasNull = false; $hasArray = false; $hasString = false; $hasInt = false; $hasFloat = false; $hasBool = false; $hasCallable = false; $hasObject = false; $minimumTokenPhpVersion = self::MINIMUM_PHP_VERSION; foreach ($types as $key => $type) { if (1 !== Preg::match(self::CLASS_REGEX, $type, $matches)) { continue; } if (isset($matches['array'])) { $hasArray = true; unset($types[$key]); } if ('iterable' === $type) { $hasIterable = true; unset($types[$key]); $minimumTokenPhpVersion = 70100; } if ('null' === $type) { $hasNull = true; unset($types[$key]); $minimumTokenPhpVersion = 70100; } if ('string' === $type) { $hasString = true; unset($types[$key]); } if ('int' === $type) { $hasInt = true; unset($types[$key]); } if ('float' === $type) { $hasFloat = true; unset($types[$key]); } if ('bool' === $type) { $hasBool = true; unset($types[$key]); } if ('callable' === $type) { $hasCallable = true; unset($types[$key]); } if ('array' === $type) { $hasArray = true; unset($types[$key]); } if ('object' === $type) { $hasObject = true; unset($types[$key]); $minimumTokenPhpVersion = 70200; } } if (\PHP_VERSION_ID < $minimumTokenPhpVersion) { continue; } $typesCount = \count($types); if (1 < $typesCount) { continue; } if (0 === $typesCount) { $paramType = ''; } elseif (1 === $typesCount) { $paramType = array_shift($types); } $startIndex = $tokens->getNextTokenOfKind($index, ['(']) + 1; $variableIndex = $this->findCorrectVariable($tokens, $startIndex - 1, $paramTypeAnnotation); if (null === $variableIndex) { continue; } $byRefIndex = $tokens->getPrevMeaningfulToken($variableIndex); if ($tokens[$byRefIndex]->equals('&')) { $variableIndex = $byRefIndex; } if (!('(' === $tokens[$variableIndex - 1]->getContent()) && $this->hasParamTypeHint($tokens, $variableIndex - 2)) { continue; } if (!$this->isValidSyntax(sprintf('fixFunctionDefinition( $paramType, $tokens, $variableIndex, $hasNull, $hasArray, $hasIterable, $hasString, $hasInt, $hasFloat, $hasBool, $hasCallable, $hasObject ); } } } private function findParamAnnotations(Tokens $tokens, $index) { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([ T_COMMENT, T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, ])); if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { return []; } $doc = new DocBlock($tokens[$index]->getContent()); return $doc->getAnnotationsOfType('param'); } private function findCorrectVariable(Tokens $tokens, $index, $paramTypeAnnotation) { $nextFunction = $tokens->getNextTokenOfKind($index, [[T_FUNCTION]]); $variableIndex = $tokens->getNextTokenOfKind($index, [[T_VARIABLE]]); if (\is_int($nextFunction) && $variableIndex > $nextFunction) { return null; } if (!isset($tokens[$variableIndex])) { return null; } $variableToken = $tokens[$variableIndex]->getContent(); Preg::match('/@param\s*[^\s!<]+\s*([^\s]+)/', $paramTypeAnnotation->getContent(), $paramVariable); if (isset($paramVariable[1]) && $paramVariable[1] === $variableToken) { return $variableIndex; } return $this->findCorrectVariable($tokens, $index + 1, $paramTypeAnnotation); } private function hasParamTypeHint(Tokens $tokens, $index) { return $tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, T_CALLABLE, CT::T_NULLABLE_TYPE]); } private function fixFunctionDefinition( $paramType, Tokens $tokens, $index, $hasNull, $hasArray, $hasIterable, $hasString, $hasInt, $hasFloat, $hasBool, $hasCallable, $hasObject ) { $newTokens = []; if (true === $hasIterable && true === $hasArray) { $newTokens[] = new Token([CT::T_ARRAY_TYPEHINT, 'array']); } elseif (true === $hasIterable) { $newTokens[] = new Token([T_STRING, 'iterable']); } elseif (true === $hasArray) { $newTokens[] = new Token([CT::T_ARRAY_TYPEHINT, 'array']); } elseif (true === $hasString) { $newTokens[] = new Token([T_STRING, 'string']); } elseif (true === $hasInt) { $newTokens[] = new Token([T_STRING, 'int']); } elseif (true === $hasFloat) { $newTokens[] = new Token([T_STRING, 'float']); } elseif (true === $hasBool) { $newTokens[] = new Token([T_STRING, 'bool']); } elseif (true === $hasCallable) { $newTokens[] = new Token([T_CALLABLE, 'callable']); } elseif (true === $hasObject) { $newTokens[] = new Token([T_STRING, 'object']); } if ('' !== $paramType && [] !== $newTokens) { return; } foreach (explode('\\', $paramType) as $nsIndex => $value) { if (0 === $nsIndex && '' === $value) { continue; } if (0 < $nsIndex) { $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); } $newTokens[] = new Token([T_STRING, $value]); } if (true === $hasNull) { array_unshift($newTokens, new Token([CT::T_NULLABLE_TYPE, '?'])); } $newTokens[] = new Token([T_WHITESPACE, ' ']); $tokens->insertAt($index, $newTokens); } } functionFilter = $this->getFunctionFilter(); } public function getDefinition() { return new FixerDefinition( 'Add leading `\` before function invocation to speed up resolving.', [ new CodeSample( ' [ 'json_encode', ], ] ), new CodeSample( ' 'all'] ), new CodeSample( ' 'namespaced'] ), new CodeSample( ' ['myGlobalFunction']] ), new CodeSample( ' ['@all']] ), new CodeSample( ' ['@internal']] ), new CodeSample( ' ['@compiler_optimized']] ), ], null, 'Risky when any of the functions are overridden.' ); } public function getPriority() { return 1; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if ('all' === $this->configuration['scope']) { $this->fixFunctionCalls($tokens, $this->functionFilter, 0, \count($tokens) - 1, false); return; } $namespaces = (new NamespacesAnalyzer())->getDeclarations($tokens); foreach (array_reverse($namespaces) as $namespace) { $this->fixFunctionCalls($tokens, $this->functionFilter, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex(), '' === $namespace->getFullName()); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('exclude', 'List of functions to ignore.')) ->setAllowedTypes(['array']) ->setAllowedValues([static function (array $value) { foreach ($value as $functionName) { if (!\is_string($functionName) || '' === trim($functionName) || trim($functionName) !== $functionName) { throw new InvalidOptionsException(sprintf( 'Each element must be a non-empty, trimmed string, got "%s" instead.', \is_object($functionName) ? \get_class($functionName) : \gettype($functionName) )); } } return true; }]) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('include', 'List of function names or sets to fix. Defined sets are `@internal` (all native functions), `@all` (all global functions) and `@compiler_optimized` (functions that are specially optimized by Zend).')) ->setAllowedTypes(['array']) ->setAllowedValues([static function (array $value) { foreach ($value as $functionName) { if (!\is_string($functionName) || '' === trim($functionName) || trim($functionName) !== $functionName) { throw new InvalidOptionsException(sprintf( 'Each element must be a non-empty, trimmed string, got "%s" instead.', \is_object($functionName) ? \get_class($functionName) : \gettype($functionName) )); } $sets = [ self::SET_ALL, self::SET_INTERNAL, self::SET_COMPILER_OPTIMIZED, ]; if ('@' === $functionName[0] && !\in_array($functionName, $sets, true)) { throw new InvalidOptionsException(sprintf('Unknown set "%s", known sets are "%s".', $functionName, implode('", "', $sets))); } } return true; }]) ->setDefault([self::SET_INTERNAL]) ->getOption(), (new FixerOptionBuilder('scope', 'Only fix function calls that are made within a namespace or fix all.')) ->setAllowedValues(['all', 'namespaced']) ->setDefault('all') ->getOption(), (new FixerOptionBuilder('strict', 'Whether leading `\` of function call not meant to have it should be removed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function fixFunctionCalls(Tokens $tokens, callable $functionFilter, $start, $end, $tryToRemove) { $functionsAnalyzer = new FunctionsAnalyzer(); $insertAtIndexes = []; for ($index = $start; $index < $end; ++$index) { if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$functionFilter($tokens[$index]->getContent()) || $tryToRemove) { if (!$this->configuration['strict']) { continue; } if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } continue; } if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { continue; } $insertAtIndexes[] = $index; } foreach (array_reverse($insertAtIndexes) as $index) { $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); } } private function getFunctionFilter() { $exclude = $this->normalizeFunctionNames($this->configuration['exclude']); if (\in_array(self::SET_ALL, $this->configuration['include'], true)) { if (\count($exclude) > 0) { return static function ($functionName) use ($exclude) { return !isset($exclude[strtolower($functionName)]); }; } return static function () { return true; }; } $include = []; if (\in_array(self::SET_INTERNAL, $this->configuration['include'], true)) { $include = $this->getAllInternalFunctionsNormalized(); } elseif (\in_array(self::SET_COMPILER_OPTIMIZED, $this->configuration['include'], true)) { $include = $this->getAllCompilerOptimizedFunctionsNormalized(); } foreach ($this->configuration['include'] as $additional) { if ('@' !== $additional[0]) { $include[strtolower($additional)] = true; } } if (\count($exclude) > 0) { return static function ($functionName) use ($include, $exclude) { return isset($include[strtolower($functionName)]) && !isset($exclude[strtolower($functionName)]); }; } return static function ($functionName) use ($include) { return isset($include[strtolower($functionName)]); }; } private function getAllCompilerOptimizedFunctionsNormalized() { return $this->normalizeFunctionNames([ 'array_key_exists', 'array_slice', 'assert', 'boolval', 'call_user_func', 'call_user_func_array', 'chr', 'count', 'defined', 'doubleval', 'floatval', 'func_get_args', 'func_num_args', 'get_called_class', 'get_class', 'gettype', 'in_array', 'intval', 'is_array', 'is_bool', 'is_double', 'is_float', 'is_int', 'is_integer', 'is_long', 'is_null', 'is_object', 'is_real', 'is_resource', 'is_string', 'ord', 'strlen', 'strval', 'constant', 'define', 'dirname', 'extension_loaded', 'function_exists', 'is_callable', ]); } private function getAllInternalFunctionsNormalized() { return $this->normalizeFunctionNames(get_defined_functions()['internal']); } private function normalizeFunctionNames(array $functionNames) { foreach ($functionNames as $index => $functionName) { $functionNames[strtolower($functionName)] = true; unset($functionNames[$index]); } return $functionNames; } } fixSpace2($tokens, $index); } public function getDefinition() { return new FixerDefinition( 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma. Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.', [ new CodeSample( " false] ), new CodeSample( " true] ), new CodeSample( " 'ensure_fully_multiline'] ), new CodeSample( " 'ensure_single_line'] ), new CodeSample( " 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => true, ] ), new CodeSample( " 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => false, ] ), new VersionSpecificCodeSample( <<<'SAMPLE' true] ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound('('); } public function configure(array $configuration = null) { parent::configure($configuration); if ($this->configuration['ensure_fully_multiline'] && 'ignore' === $this->configuration['on_multiline']) { $this->configuration['on_multiline'] = 'ensure_fully_multiline'; } } public function getPriority() { return -30; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $expectedTokens = [T_LIST, T_FUNCTION, CT::T_USE_LAMBDA]; if (\PHP_VERSION_ID >= 70400) { $expectedTokens[] = T_FN; } for ($index = $tokens->count() - 1; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->equals('(')) { continue; } $meaningfulTokenBeforeParenthesis = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ( $meaningfulTokenBeforeParenthesis->isKeyword() && !$meaningfulTokenBeforeParenthesis->isGivenKind($expectedTokens) ) { continue; } $isMultiline = $this->fixFunction($tokens, $index); if ( $isMultiline && 'ensure_fully_multiline' === $this->configuration['on_multiline'] && !$meaningfulTokenBeforeParenthesis->isGivenKind(T_LIST) ) { $this->ensureFunctionFullyMultiline($tokens, $index); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('keep_multiple_spaces_after_comma', 'Whether keep multiple spaces after comma.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder( 'ensure_fully_multiline', 'ensure every argument of a multiline argument list is on its own line' )) ->setAllowedTypes(['bool']) ->setDefault(false) ->setDeprecationMessage('Use option `on_multiline` instead.') ->getOption(), (new FixerOptionBuilder( 'on_multiline', 'Defines how to handle function arguments lists that contain newlines.' )) ->setAllowedValues(['ignore', 'ensure_single_line', 'ensure_fully_multiline']) ->setDefault('ignore') ->getOption(), (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->setNormalizer(static function (Options $options, $value) { if (\PHP_VERSION_ID < 70300 && $value) { throw new InvalidOptionsForEnvException('"after_heredoc" option can only be enabled with PHP 7.3+.'); } return $value; }) ->getOption(), ]); } private function fixFunction(Tokens $tokens, $startFunctionIndex) { $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); $isMultiline = false; $firstWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $startFunctionIndex, $endFunctionIndex); $lastWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $endFunctionIndex, $startFunctionIndex); foreach ([$firstWhitespaceIndex, $lastWhitespaceIndex] as $index) { if (null === $index || !Preg::match('/\R/', $tokens[$index]->getContent())) { continue; } if ('ensure_single_line' !== $this->configuration['on_multiline']) { $isMultiline = true; continue; } $newLinesRemoved = $this->ensureSingleLine($tokens, $index); if (!$newLinesRemoved) { $isMultiline = true; } } for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { $token = $tokens[$index]; if ($token->equals(')')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } if ($token->equals('}')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->equals(',')) { $this->fixSpace2($tokens, $index); if (!$isMultiline && $this->isNewline($tokens[$index + 1])) { $isMultiline = true; break; } } } return $isMultiline; } private function findWhitespaceIndexAfterParenthesis(Tokens $tokens, $startParenthesisIndex, $endParenthesisIndex) { $direction = $endParenthesisIndex > $startParenthesisIndex ? 1 : -1; $startIndex = $startParenthesisIndex + $direction; $endIndex = $endParenthesisIndex - $direction; for ($index = $startIndex; $index !== $endIndex; $index += $direction) { $token = $tokens[$index]; if ($token->isWhitespace()) { return $index; } if (!$token->isComment()) { break; } } return null; } private function ensureSingleLine(Tokens $tokens, $index) { $previousToken = $tokens[$index - 1]; if ($previousToken->isComment() && 0 !== strpos($previousToken->getContent(), '/*')) { return false; } $content = Preg::replace('/\R\h*/', '', $tokens[$index]->getContent()); if ('' !== $content) { $tokens[$index] = new Token([T_WHITESPACE, $content]); } else { $tokens->clearAt($index); } return true; } private function ensureFunctionFullyMultiline(Tokens $tokens, $startFunctionIndex) { $searchIndex = $startFunctionIndex; do { $prevWhitespaceTokenIndex = $tokens->getPrevTokenOfKind( $searchIndex, [[T_WHITESPACE]] ); $searchIndex = $prevWhitespaceTokenIndex; } while (null !== $prevWhitespaceTokenIndex && false === strpos($tokens[$prevWhitespaceTokenIndex]->getContent(), "\n") ); if (null === $prevWhitespaceTokenIndex) { $existingIndentation = ''; } else { $existingIndentation = $tokens[$prevWhitespaceTokenIndex]->getContent(); $lastLineIndex = strrpos($existingIndentation, "\n"); $existingIndentation = false === $lastLineIndex ? $existingIndentation : substr($existingIndentation, $lastLineIndex + 1) ; } $indentation = $existingIndentation.$this->whitespacesConfig->getIndent(); $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); $wasWhitespaceBeforeEndFunctionAddedAsNewToken = $tokens->ensureWhitespaceAtIndex( $tokens[$endFunctionIndex - 1]->isWhitespace() ? $endFunctionIndex - 1 : $endFunctionIndex, 0, $this->whitespacesConfig->getLineEnding().$existingIndentation ); if ($wasWhitespaceBeforeEndFunctionAddedAsNewToken) { ++$endFunctionIndex; } for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { $token = $tokens[$index]; if ($token->equals(')')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } if ($token->equals('}')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->equals(',') && !$tokens[$tokens->getNextMeaningfulToken($index)]->equals(')')) { $this->fixNewline($tokens, $index, $indentation); } } $this->fixNewline($tokens, $startFunctionIndex, $indentation, false); } private function fixNewline(Tokens $tokens, $index, $indentation, $override = true) { if ($tokens[$index + 1]->isComment()) { return; } if ($tokens[$index + 2]->isComment()) { $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index + 2); if (!$this->isNewline($tokens[$nextMeaningfulTokenIndex - 1])) { $tokens->ensureWhitespaceAtIndex($nextMeaningfulTokenIndex, 0, $this->whitespacesConfig->getLineEnding().$indentation); } return; } $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextMeaningfulTokenIndex]->equals(')')) { return; } $tokens->ensureWhitespaceAtIndex($index + 1, 0, $this->whitespacesConfig->getLineEnding().$indentation); } private function fixSpace2(Tokens $tokens, $index) { if ($tokens[$index - 1]->isWhitespace()) { $prevIndex = $tokens->getPrevNonWhitespace($index - 1); if ( !$tokens[$prevIndex]->equals(',') && !$tokens[$prevIndex]->isComment() && ($this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(T_END_HEREDOC)) ) { $tokens->clearAt($index - 1); } } $nextIndex = $index + 1; $nextToken = $tokens[$nextIndex]; if ($nextToken->isWhitespace()) { $newContent = $nextToken->getContent(); if ('ensure_single_line' === $this->configuration['on_multiline']) { $newContent = Preg::replace('/\R/', '', $newContent); } if ( (!$this->configuration['keep_multiple_spaces_after_comma'] || Preg::match('/\R/', $newContent)) && !$this->isCommentLastLineToken($tokens, $index + 2) ) { $newContent = ltrim($newContent, " \t"); } $tokens[$nextIndex] = new Token([T_WHITESPACE, '' === $newContent ? ' ' : $newContent]); return; } if (!$this->isCommentLastLineToken($tokens, $index + 1)) { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } } private function isCommentLastLineToken(Tokens $tokens, $index) { if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) { return false; } $content = $tokens[$index + 1]->getContent(); return $content !== ltrim($content, "\r\n"); } private function isNewline(Token $token) { return $token->isWhitespace() && false !== strpos($token->getContent(), "\n"); } } 70100, 'iterable' => 70100, 'object' => 70200, ]; private $scalarTypes = [ 'bool' => 'bool', 'true' => 'bool', 'false' => 'bool', 'float' => 'float', 'int' => 'int', 'string' => 'string', ]; private $skippedTypes = [ 'mixed' => true, 'resource' => true, 'null' => true, ]; private $classRegex = '/^\\\\?[a-zA-Z_\\x7f-\\xff](?:\\\\?[a-zA-Z0-9_\\x7f-\\xff]+)*(?\[\])*$/'; public function getDefinition() { return new FixerDefinition( 'EXPERIMENTAL: Takes `@return` annotation of non-mixed types and adjusts accordingly the function signature. Requires PHP >= 7.0.', [ new VersionSpecificCodeSample( ' false] ), new VersionSpecificCodeSample( '= 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return \PHP_VERSION_ID >= 70000 && $tokens->isTokenKindFound(T_FUNCTION); } public function getPriority() { return 13; } public function isRisky() { return true; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('scalar_types', 'Fix also scalar types; may have unexpected behaviour due to PHP bad type coercion system.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { if (\PHP_VERSION_ID >= 80000) { unset($this->skippedTypes['mixed']); } for ($index = $tokens->count() - 1; 0 < $index; --$index) { if ( !$tokens[$index]->isGivenKind(T_FUNCTION) && (\PHP_VERSION_ID < 70400 || !$tokens[$index]->isGivenKind(T_FN)) ) { continue; } $funcName = $tokens->getNextMeaningfulToken($index); if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, false)) { continue; } $returnTypeAnnotation = $this->findReturnAnnotations($tokens, $index); if (1 !== \count($returnTypeAnnotation)) { continue; } $returnTypeAnnotation = current($returnTypeAnnotation); $types = array_values($returnTypeAnnotation->getTypes()); $typesCount = \count($types); if (1 > $typesCount || 2 < $typesCount) { continue; } $isNullable = false; $returnType = current($types); if (2 === $typesCount) { $null = $types[0]; $returnType = $types[1]; if ('null' !== $null) { $null = $types[1]; $returnType = $types[0]; } if ('null' !== $null) { continue; } $isNullable = true; if (\PHP_VERSION_ID < 70100) { continue; } if ('void' === $returnType) { continue; } } if ('static' === $returnType) { $returnType = \PHP_VERSION_ID < 80000 ? 'self' : 'static'; } if (isset($this->skippedTypes[$returnType])) { continue; } if (isset($this->versionSpecificTypes[$returnType]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$returnType]) { continue; } if (isset($this->scalarTypes[$returnType])) { if (false === $this->configuration['scalar_types']) { continue; } $returnType = $this->scalarTypes[$returnType]; } else { if (1 !== Preg::match($this->classRegex, $returnType, $matches)) { continue; } if (isset($matches['array'])) { $returnType = 'array'; } } $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($this->hasReturnTypeHint($tokens, $startIndex)) { continue; } if (!$this->isValidSyntax(sprintf('fixFunctionDefinition($tokens, $startIndex, $isNullable, $returnType); } } private function hasReturnTypeHint(Tokens $tokens, $index) { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); } private function fixFunctionDefinition(Tokens $tokens, $index, $isNullable, $returnType) { static $specialTypes = [ 'array' => [CT::T_ARRAY_TYPEHINT, 'array'], 'callable' => [T_CALLABLE, 'callable'], 'static' => [T_STATIC, 'static'], ]; $newTokens = [ new Token([CT::T_TYPE_COLON, ':']), new Token([T_WHITESPACE, ' ']), ]; if (true === $isNullable) { $newTokens[] = new Token([CT::T_NULLABLE_TYPE, '?']); } if (isset($specialTypes[$returnType])) { $newTokens[] = new Token($specialTypes[$returnType]); } else { $returnTypeUnqualified = ltrim($returnType, '\\'); if (isset($this->scalarTypes[$returnTypeUnqualified]) || isset($this->versionSpecificTypes[$returnTypeUnqualified])) { $newTokens[] = new Token([T_STRING, $returnTypeUnqualified]); } else { foreach (explode('\\', $returnType) as $nsIndex => $value) { if (0 === $nsIndex && '' === $value) { continue; } if (0 < $nsIndex) { $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); } $newTokens[] = new Token([T_STRING, $value]); } } } $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $tokens->insertAt($endFuncIndex + 1, $newTokens); } private function findReturnAnnotations(Tokens $tokens, $index) { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([ T_COMMENT, T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, ])); if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { return []; } $doc = new DocBlock($tokens[$index]->getContent()); return $doc->getAnnotationsOfType('return'); } } false]), ], null, 'Risky when the function `fopen` is overridden.' ); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('b_mode', 'The `b` flag must be used (`true`) or omitted (`false`).')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function fixFopenFlagToken(Tokens $tokens, $argumentStartIndex, $argumentEndIndex) { $argumentFlagIndex = null; for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { continue; } if (null !== $argumentFlagIndex) { return; } $argumentFlagIndex = $i; } if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { return; } $content = $tokens[$argumentFlagIndex]->getContent(); $contentQuote = $content[0]; if ('b' === $contentQuote || 'B' === $contentQuote) { $binPrefix = $contentQuote; $contentQuote = $content[1]; $mode = substr($content, 2, -1); } else { $binPrefix = ''; $mode = substr($content, 1, -1); } if (false === $this->isValidModeString($mode)) { return; } $mode = str_replace('t', '', $mode); if ($this->configuration['b_mode']) { if (false === strpos($mode, 'b')) { $mode .= 'b'; } } else { $mode = str_replace('b', '', $mode); } $newContent = $binPrefix.$contentQuote.$mode.$contentQuote; if ($content !== $newContent) { $tokens[$argumentFlagIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, $newContent]); } } } = 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return $tokens->isTokenKindFound(T_FUNCTION); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $functionsAnalyzer = new FunctionsAnalyzer(); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ( !$token->isGivenKind(T_FUNCTION) && (\PHP_VERSION_ID < 70400 || !$token->isGivenKind(T_FN)) ) { continue; } $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); foreach (array_reverse($arguments) as $argument) { $type = $argument->getTypeAnalysis(); if (!$type instanceof TypeAnalysis) { continue; } $tokens->ensureWhitespaceAtIndex($type->getEndIndex() + 1, 0, ' '); } } } } = 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return $tokens->isTokenKindFound(T_FUNCTION); } public function getDefinition() { return new FixerDefinition( 'Spaces should be properly placed in a function declaration.', [ new CodeSample( ' self::SPACING_NONE] ), new VersionSpecificCodeSample( ' null; ', new VersionSpecification(70400), ['closure_function_spacing' => self::SPACING_NONE] ), ] ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ( !$token->isGivenKind(T_FUNCTION) && (\PHP_VERSION_ID < 70400 || !$token->isGivenKind(T_FN)) ) { continue; } $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', [T_CLOSE_TAG]]); if (!$tokens[$startParenthesisIndex]->equals('(')) { continue; } $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{', [T_DOUBLE_ARROW]]); if ( $tokens[$startBraceIndex]->equalsAny(['{', [T_DOUBLE_ARROW]]) && ( !$tokens[$startBraceIndex - 1]->isWhitespace() || $tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions) ) ) { $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); } $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); $afterParenthesisToken = $tokens[$afterParenthesisIndex]; if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' '); $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex); $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' '); } $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex); $isLambda = $tokensAnalyzer->isLambda($index); if (!$isLambda && $tokens[$startParenthesisIndex - 1]->isWhitespace() && !$tokens[$tokens->getPrevNonWhitespace($startParenthesisIndex - 1)]->isComment()) { $tokens->clearAt($startParenthesisIndex - 1); } if ($isLambda && self::SPACING_NONE === $this->configuration['closure_function_spacing']) { if ($tokens[$index + 1]->isWhitespace()) { $tokens->clearAt($index + 1); } } else { $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); } if ($isLambda) { $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(T_STATIC)) { $tokens->ensureWhitespaceAtIndex($prev + 1, 0, ' '); } } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('closure_function_spacing', 'Spacing to use before open parenthesis for closures.')) ->setDefault(self::SPACING_ONE) ->setAllowedValues($this->supportedSpacings) ->getOption(), ]); } private function fixParenthesisInnerEdge(Tokens $tokens, $start, $end) { if ($tokens[$end - 1]->isWhitespace($this->singleLineWhitespaceOptions)) { $tokens->clearAt($end - 1); } if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) { $tokens->clearAt($start + 1); } } } isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { continue; } if (null !== $argumentFlagIndex) { return; } $argumentFlagIndex = $i; } if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { return; } $content = $tokens[$argumentFlagIndex]->getContent(); $contentQuote = $content[0]; if ('b' === $contentQuote || 'B' === $contentQuote) { $binPrefix = $contentQuote; $contentQuote = $content[1]; $mode = substr($content, 2, -1); } else { $binPrefix = ''; $mode = substr($content, 1, -1); } $modeLength = \strlen($mode); if ($modeLength < 2) { return; } if (false === $this->isValidModeString($mode)) { return; } $split = $this->sortFlags(Preg::split('#([^\+]\+?)#', $mode, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); $newContent = $binPrefix.$contentQuote.implode('', $split).$contentQuote; if ($content !== $newContent) { $tokens[$argumentFlagIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, $newContent]); } } private function sortFlags(array $flags) { usort( $flags, static function ($flag1, $flag2) { if ($flag1 === $flag2) { return 0; } if ('b' === $flag1) { return 1; } if ('b' === $flag2) { return -1; } if ('t' === $flag1) { return 1; } if ('t' === $flag2) { return -1; } return $flag1 < $flag2 ? -1 : 1; } ); return $flags; } } = 70400 && $tokens->isTokenKindFound(T_FN)) { return true; } return $tokens->isTokenKindFound(T_FUNCTION); } public function isRisky() { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) { if ( !$tokens[$i]->isGivenKind(T_FUNCTION) && (\PHP_VERSION_ID < 70400 || !$tokens[$i]->isGivenKind(T_FN)) ) { continue; } $startIndex = $tokens->getNextTokenOfKind($i, ['(']); $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); $this->fixFunctionDefinition($tokens, $startIndex, $i); } } private function fixFunctionDefinition(Tokens $tokens, $startIndex, $endIndex) { $lastArgumentIndex = $this->getLastNonDefaultArgumentIndex($tokens, $startIndex, $endIndex); if (!$lastArgumentIndex) { return; } for ($i = $lastArgumentIndex; $i > $startIndex; --$i) { $token = $tokens[$i]; if ($token->isGivenKind(T_VARIABLE)) { $lastArgumentIndex = $i; continue; } if (!$token->equals('=') || $this->isNonNullableTypehintedNullableVariable($tokens, $i)) { continue; } $endIndex = $tokens->getPrevTokenOfKind($lastArgumentIndex, [',']); $endIndex = $tokens->getPrevMeaningfulToken($endIndex); $this->removeDefaultArgument($tokens, $i, $endIndex); } } private function getLastNonDefaultArgumentIndex(Tokens $tokens, $startIndex, $endIndex) { for ($i = $endIndex - 1; $i > $startIndex; --$i) { $token = $tokens[$i]; if ($token->equals('=')) { $i = $tokens->getPrevMeaningfulToken($i); continue; } if ($token->isGivenKind(T_VARIABLE) && !$this->isEllipsis($tokens, $i)) { return $i; } } return null; } private function isEllipsis(Tokens $tokens, $variableIndex) { return $tokens[$tokens->getPrevMeaningfulToken($variableIndex)]->isGivenKind(T_ELLIPSIS); } private function removeDefaultArgument(Tokens $tokens, $startIndex, $endIndex) { for ($i = $startIndex; $i <= $endIndex;) { $tokens->clearTokenAndMergeSurroundingWhitespace($i); $this->clearWhitespacesBeforeIndex($tokens, $i); $i = $tokens->getNextMeaningfulToken($i); } } private function isNonNullableTypehintedNullableVariable(Tokens $tokens, $index) { $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; if (!$nextToken->equals([T_STRING, 'null'], false)) { return false; } $variableIndex = $tokens->getPrevMeaningfulToken($index); $searchTokens = [',', '(', [T_STRING], [CT::T_ARRAY_TYPEHINT], [T_CALLABLE]]; $typehintKinds = [T_STRING, CT::T_ARRAY_TYPEHINT, T_CALLABLE]; $prevIndex = $tokens->getPrevTokenOfKind($variableIndex, $searchTokens); if (!$tokens[$prevIndex]->isGivenKind($typehintKinds)) { return false; } return !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(CT::T_NULLABLE_TYPE); } private function clearWhitespacesBeforeIndex(Tokens $tokens, $index) { $prevIndex = $tokens->getNonEmptySibling($index, -1); if (!$tokens[$prevIndex]->isWhitespace()) { return; } $prevNonWhiteIndex = $tokens->getPrevNonWhitespace($prevIndex); if (null === $prevNonWhiteIndex || !$tokens[$prevNonWhiteIndex]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } } } '0', '0' => '0', 'I' => '1', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', 'Α' => 'A', 'А' => 'A', 'A' => 'A', 'ʙ' => 'B', 'Β' => 'B', 'В' => 'B', 'B' => 'B', 'Ϲ' => 'C', 'С' => 'C', 'Ⅽ' => 'C', 'C' => 'C', 'Ⅾ' => 'D', 'D' => 'D', 'Ε' => 'E', 'Е' => 'E', 'E' => 'E', 'Ϝ' => 'F', 'F' => 'F', 'ɢ' => 'G', 'Ԍ' => 'G', 'G' => 'G', 'ʜ' => 'H', 'Η' => 'H', 'Н' => 'H', 'H' => 'H', 'l' => 'I', 'Ι' => 'I', 'І' => 'I', 'Ⅰ' => 'I', 'I' => 'I', 'Ј' => 'J', 'J' => 'J', 'Κ' => 'K', 'К' => 'K', 'K' => 'K', 'K' => 'K', 'ʟ' => 'L', 'Ⅼ' => 'L', 'L' => 'L', 'Μ' => 'M', 'М' => 'M', 'Ⅿ' => 'M', 'M' => 'M', 'ɴ' => 'N', 'Ν' => 'N', 'N' => 'N', 'Ο' => 'O', 'О' => 'O', 'O' => 'O', 'Ρ' => 'P', 'Р' => 'P', 'P' => 'P', 'Q' => 'Q', 'ʀ' => 'R', 'R' => 'R', 'Ѕ' => 'S', 'S' => 'S', 'Τ' => 'T', 'Т' => 'T', 'T' => 'T', 'U' => 'U', 'Ѵ' => 'V', 'Ⅴ' => 'V', 'V' => 'V', 'W' => 'W', 'Χ' => 'X', 'Х' => 'X', 'Ⅹ' => 'X', 'X' => 'X', 'ʏ' => 'Y', 'Υ' => 'Y', 'Ү' => 'Y', 'Y' => 'Y', 'Ζ' => 'Z', 'Z' => 'Z', '_' => '_', 'ɑ' => 'a', 'а' => 'a', 'a' => 'a', 'Ь' => 'b', 'b' => 'b', 'ϲ' => 'c', 'с' => 'c', 'ⅽ' => 'c', 'c' => 'c', 'ԁ' => 'd', 'ⅾ' => 'd', 'd' => 'd', 'е' => 'e', 'e' => 'e', 'f' => 'f', 'ɡ' => 'g', 'g' => 'g', 'һ' => 'h', 'h' => 'h', 'ɩ' => 'i', 'і' => 'i', 'ⅰ' => 'i', 'i' => 'i', 'ј' => 'j', 'j' => 'j', 'k' => 'k', 'ⅼ' => 'l', 'l' => 'l', 'ⅿ' => 'm', 'm' => 'm', 'n' => 'n', 'ο' => 'o', 'о' => 'o', 'o' => 'o', 'р' => 'p', 'p' => 'p', 'q' => 'q', 'r' => 'r', 'ѕ' => 's', 's' => 's', 't' => 't', 'u' => 'u', 'ν' => 'v', 'ѵ' => 'v', 'ⅴ' => 'v', 'v' => 'v', 'ѡ' => 'w', 'w' => 'w', 'х' => 'x', 'ⅹ' => 'x', 'x' => 'x', 'у' => 'y', 'y' => 'y', 'z' => 'z', ]; public function getDefinition() { return new FixerDefinition( 'Replace accidental usage of homoglyphs (non ascii characters) in names.', [new CodeSample("isAnyTokenKindsFound([T_VARIABLE, T_STRING]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind([T_VARIABLE, T_STRING])) { continue; } $replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static function ($matches) { return isset(self::$replacements[$matches[0]]) ? self::$replacements[$matches[0]] : $matches[0] ; }, $token->getContent(), -1, $count); if ($count) { $tokens->offsetSet($index, new Token([$token->getId(), $replaced])); } } } } isAnyTokenKindsFound($this->getMagicConstantTokens()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $magicConstants = $this->getMagicConstants(); $magicConstantTokens = $this->getMagicConstantTokens(); foreach ($tokens as $index => $token) { if ($token->isGivenKind($magicConstantTokens)) { $tokens[$index] = new Token([$token->getId(), $magicConstants[$token->getId()]]); } } } private function getMagicConstants() { static $magicConstants = null; if (null === $magicConstants) { $magicConstants = [ T_LINE => '__LINE__', T_FILE => '__FILE__', T_DIR => '__DIR__', T_FUNC_C => '__FUNCTION__', T_CLASS_C => '__CLASS__', T_METHOD_C => '__METHOD__', T_NS_C => '__NAMESPACE__', CT::T_CLASS_CONSTANT => 'class', T_TRAIT_C => '__TRAIT__', ]; } return $magicConstants; } private function getMagicConstantTokens() { static $magicConstantTokens = null; if (null === $magicConstantTokens) { $magicConstantTokens = array_keys($this->getMagicConstants()); } return $magicConstantTokens; } } isTokenKindFound(T_STRING); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $nativeFunctionNames = null; if (null === $nativeFunctionNames) { $nativeFunctionNames = $this->getNativeFunctionNames(); } for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind(T_STRING)) { continue; } $next = $tokens->getNextMeaningfulToken($index); if (!$tokens[$next]->equals('(')) { $index = $next; continue; } $functionNamePrefix = $tokens->getPrevMeaningfulToken($index); if ($tokens[$functionNamePrefix]->isGivenKind([T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR, T_FUNCTION, CT::T_RETURN_REF])) { continue; } if ($tokens[$functionNamePrefix]->isGivenKind(T_NS_SEPARATOR)) { $prev = $tokens->getPrevMeaningfulToken($functionNamePrefix); if ($tokens[$prev]->isGivenKind([T_STRING, T_NEW])) { continue; } } $lower = strtolower($tokens[$index]->getContent()); if (!\array_key_exists($lower, $nativeFunctionNames)) { continue; } $tokens[$index] = new Token([T_STRING, $nativeFunctionNames[$lower]]); $index = $next; } } private function getNativeFunctionNames() { $allFunctions = get_defined_functions(); $functions = []; foreach ($allFunctions['internal'] as $function) { $functions[strtolower($function)] = $function; } return $functions; } } configuration['case']) { $this->fixFunction = static function ($token) { return strtolower($token); }; } if ('upper' === $this->configuration['case']) { $this->fixFunction = static function ($token) { return strtoupper($token); }; } } public function getDefinition() { return new FixerDefinition( 'The PHP constants `true`, `false`, and `null` MUST be written using the correct casing.', [ new CodeSample(" 'upper']), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('case', 'Whether to use the `upper` or `lower` case syntax.')) ->setAllowedValues(['upper', 'lower']) ->setDefault('lower') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $fixFunction = $this->fixFunction; foreach ($tokens as $index => $token) { if (!$token->isNativeConstant()) { continue; } if ( $this->isNeighbourAccepted($tokens, $tokens->getPrevMeaningfulToken($index)) && $this->isNeighbourAccepted($tokens, $tokens->getNextMeaningfulToken($index)) ) { $tokens[$index] = new Token([$token->getId(), $fixFunction($token->getContent())]); } } } private function isNeighbourAccepted(Tokens $tokens, $index) { static $forbiddenTokens = [ T_AS, T_CLASS, T_CONST, T_EXTENDS, T_IMPLEMENTS, T_INSTANCEOF, T_INSTEADOF, T_INTERFACE, T_NEW, T_NS_SEPARATOR, T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM, T_TRAIT, T_USE, CT::T_USE_TRAIT, CT::T_USE_LAMBDA, ]; $token = $tokens[$index]; if ($token->equalsAny(['{', '}'])) { return false; } return !$token->isGivenKind($forbiddenTokens); } } proxyFixers); } protected function createProxyFixers() { $fixer = new ConstantCaseFixer(); $fixer->configure(['case' => 'lower']); return [$fixer]; } } isAnyTokenKindsFound(Token::getKeywords()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) { $tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]); } } } } '__call', '__callstatic' => '__callStatic', '__clone' => '__clone', '__construct' => '__construct', '__debuginfo' => '__debugInfo', '__destruct' => '__destruct', '__get' => '__get', '__invoke' => '__invoke', '__isset' => '__isset', '__serialize' => '__serialize', '__set' => '__set', '__set_state' => '__set_state', '__sleep' => '__sleep', '__tostring' => '__toString', '__unserialize' => '__unserialize', '__unset' => '__unset', '__wakeup' => '__wakeup', ]; public function getDefinition() { return new FixerDefinition( 'Magic method definitions and calls must be using the correct casing.', [ new CodeSample( '__INVOKE(1); ' ), ] ); } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_STRING) && $tokens->isAnyTokenKindsFound([T_FUNCTION, T_OBJECT_OPERATOR, T_DOUBLE_COLON]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $inClass = 0; $tokenCount = \count($tokens); for ($index = 1; $index < $tokenCount - 2; ++$index) { if (0 === $inClass && $tokens[$index]->isClassy()) { $inClass = 1; $index = $tokens->getNextTokenOfKind($index, ['{']); continue; } if (0 !== $inClass) { if ($tokens[$index]->equals('{')) { ++$inClass; continue; } if ($tokens[$index]->equals('}')) { --$inClass; continue; } } if (!$tokens[$index]->isGivenKind(T_STRING)) { continue; } $content = $tokens[$index]->getContent(); if ('__' !== substr($content, 0, 2)) { continue; } $name = strtolower($content); if (!$this->isMagicMethodName($name)) { continue; } $nameInCorrectCasing = $this->getMagicMethodNameInCorrectCasing($name); if ($nameInCorrectCasing === $content) { continue; } if ($this->isFunctionSignature($tokens, $index)) { if (0 !== $inClass) { $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); } continue; } if ($this->isMethodCall($tokens, $index)) { $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); continue; } if ( ('__callstatic' === $name || '__set_state' === $name) && $this->isStaticMethodCall($tokens, $index) ) { $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); } } } private function isFunctionSignature(Tokens $tokens, $index) { $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->isGivenKind(T_FUNCTION)) { return false; } return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); } private function isMethodCall(Tokens $tokens, $index) { $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->equals([T_OBJECT_OPERATOR, '->'])) { return false; } return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); } private function isStaticMethodCall(Tokens $tokens, $index) { $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->isGivenKind(T_DOUBLE_COLON)) { return false; } return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); } private function isMagicMethodName($name) { return isset(self::$magicNames[$name]); } private function getMagicMethodNameInCorrectCasing($name) { return self::$magicNames[$name]; } private function setTokenToCorrectCasing(Tokens $tokens, $index, $nameInCorrectCasing) { $tokens[$index] = new Token([T_STRING, $nameInCorrectCasing]); } } isAnyTokenKindsFound([T_STATIC, T_STRING]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->equalsAny([[T_STRING, 'self'], [T_STATIC, 'static'], [T_STRING, 'parent']], false)) { continue; } $newContent = strtolower($token->getContent()); if ($token->getContent() === $newContent) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind([T_CONST, T_DOUBLE_COLON, T_FUNCTION, T_NAMESPACE, T_NS_SEPARATOR, T_OBJECT_OPERATOR, T_PRIVATE, T_PROTECTED, T_PUBLIC])) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind([T_FUNCTION, T_NS_SEPARATOR, T_PRIVATE, T_PROTECTED, T_PUBLIC])) { continue; } if ('static' === $newContent && $tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { continue; } $tokens[$index] = new Token([$token->getId(), $newContent]); } } } hints = [ 'array' => true, 'callable' => true, 'self' => true, ]; if (\PHP_VERSION_ID >= 70000) { $this->hints = array_merge( $this->hints, [ 'bool' => true, 'float' => true, 'int' => true, 'string' => true, ] ); } if (\PHP_VERSION_ID >= 70100) { $this->hints = array_merge( $this->hints, [ 'iterable' => true, 'void' => true, ] ); } if (\PHP_VERSION_ID >= 70200) { $this->hints = array_merge($this->hints, ['object' => true]); } if (\PHP_VERSION_ID >= 80000) { $this->hints = array_merge($this->hints, ['static' => true]); $this->hints = array_merge($this->hints, ['mixed' => true]); } $this->functionsAnalyzer = new FunctionsAnalyzer(); } public function getDefinition() { return new FixerDefinition( 'Native type hints for functions should use the correct case.', [ new CodeSample("isAllTokenKindsFound([T_FUNCTION, T_STRING]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokens[$index]->isGivenKind(T_FUNCTION)) { if (\PHP_VERSION_ID >= 70000) { $this->fixFunctionReturnType($tokens, $index); } $this->fixFunctionArgumentTypes($tokens, $index); } } } private function fixFunctionArgumentTypes(Tokens $tokens, $index) { foreach ($this->functionsAnalyzer->getFunctionArguments($tokens, $index) as $argument) { $this->fixArgumentType($tokens, $argument->getTypeAnalysis()); } } private function fixFunctionReturnType(Tokens $tokens, $index) { $this->fixArgumentType($tokens, $this->functionsAnalyzer->getFunctionReturnType($tokens, $index)); } private function fixArgumentType(Tokens $tokens, TypeAnalysis $type = null) { if (null === $type) { return; } $argumentStartIndex = $type->getStartIndex(); $argumentExpectedEndIndex = $type->isNullable() ? $tokens->getNextMeaningfulToken($argumentStartIndex) : $argumentStartIndex ; if ($argumentExpectedEndIndex !== $type->getEndIndex()) { return; } $lowerCasedName = strtolower($type->getName()); if (!isset($this->hints[$lowerCasedName])) { return; } $tokens[$argumentExpectedEndIndex] = new Token([$tokens[$argumentExpectedEndIndex]->getId(), $lowerCasedName]); } } isTokenKindFound(T_NAMESPACE); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $lastIndex = $tokens->count() - 1; for ($index = $lastIndex; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_NAMESPACE)) { continue; } $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', '{', [T_CLOSE_TAG]]); $semicolonToken = $tokens[$semicolonIndex]; if (!$semicolonToken->equals(';')) { continue; } $indexToEnsureBlankLineAfter = $this->getIndexToEnsureBlankLineAfter($tokens, $semicolonIndex); $indexToEnsureBlankLine = $tokens->getNonEmptySibling($indexToEnsureBlankLineAfter, 1); if (null !== $indexToEnsureBlankLine && $tokens[$indexToEnsureBlankLine]->isWhitespace()) { $tokens[$indexToEnsureBlankLine] = $this->getTokenToInsert($tokens[$indexToEnsureBlankLine]->getContent(), $indexToEnsureBlankLine === $lastIndex); } else { $tokens->insertAt($indexToEnsureBlankLineAfter + 1, $this->getTokenToInsert('', $indexToEnsureBlankLineAfter === $lastIndex)); } } } private function getIndexToEnsureBlankLineAfter(Tokens $tokens, $index) { $indexToEnsureBlankLine = $index; $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); while (null !== $nextIndex) { $token = $tokens[$nextIndex]; if ($token->isWhitespace()) { if (1 === Preg::match('/\R/', $token->getContent())) { break; } $nextNextIndex = $tokens->getNonEmptySibling($nextIndex, 1); if (!$tokens[$nextNextIndex]->isComment()) { break; } } if (!$token->isWhitespace() && !$token->isComment()) { break; } $indexToEnsureBlankLine = $nextIndex; $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); } return $indexToEnsureBlankLine; } private function getTokenToInsert($currentContent, $isLastIndex) { $ending = $this->whitespacesConfig->getLineEnding(); $emptyLines = $isLastIndex ? $ending : $ending.$ending; $indent = 1 === Preg::match('/^.*\R( *)$/s', $currentContent, $matches) ? $matches[1] : ''; return new Token([T_WHITESPACE, $emptyLines.$indent]); } } isTokenKindFound(T_NAMESPACE); } public function getDefinition() { return new FixerDefinition( 'The namespace declaration line shouldn\'t contain leading whitespace.', [ new CodeSample( 'isGivenKind(T_NAMESPACE)) { continue; } $beforeNamespaceIndex = $index - 1; $beforeNamespace = $tokens[$beforeNamespaceIndex]; if (!$beforeNamespace->isWhitespace()) { if (!self::endsWithWhitespace($beforeNamespace->getContent())) { $tokens->insertAt($index, new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding()])); } continue; } $lastNewline = strrpos($beforeNamespace->getContent(), "\n"); if (false === $lastNewline) { $beforeBeforeNamespace = $tokens[$index - 2]; if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) { $tokens->clearAt($beforeNamespaceIndex); } else { $tokens[$beforeNamespaceIndex] = new Token([T_WHITESPACE, ' ']); } } else { $tokens[$beforeNamespaceIndex] = new Token([T_WHITESPACE, substr($beforeNamespace->getContent(), 0, $lastNewline + 1)]); } } } private static function endsWithWhitespace($str) { if ('' === $str) { return false; } return '' === trim(substr($str, -1)); } } isTokenKindFound(T_NAMESPACE); } public function getPriority() { return -21; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if ($token->isGivenKind(T_NAMESPACE)) { $this->fixLinesBeforeNamespace($tokens, $index, 2, 2); } } } } isTokenKindFound(T_NAMESPACE); } public function getDefinition() { return new FixerDefinition( 'There should be no blank lines before a namespace declaration.', [ new CodeSample( "count(); $index < $limit; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_NAMESPACE)) { continue; } $this->fixLinesBeforeNamespace($tokens, $index, 0, 1); } } } isAnyTokenKindsFound(Token::getCastTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isCast()) { continue; } $tokens[$index] = new Token([$tokens[$index]->getId(), strtolower($tokens[$index]->getContent())]); } } } '', "\t" => '', "\n" => '', "\r" => '', "\0" => '', "\x0B" => '', ]; public function getDefinition() { return new FixerDefinition( 'A single space or none should be between cast and variable.', [ new CodeSample( " 'single'] ), new CodeSample( " 'none'] ), ] ); } public function getPriority() { return -10; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isCast()) { continue; } $tokens[$index] = new Token([ $token->getId(), strtr($token->getContent(), self::INSIDE_CAST_SPACE_REPLACE_MAP), ]); if ('single' === $this->configuration['space']) { if ($tokens[$index + 1]->isWhitespace(" \t")) { $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); } elseif (!$tokens[$index + 1]->isWhitespace()) { $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); } continue; } if ($tokens[$index + 1]->isWhitespace()) { $tokens->clearAt($index + 1); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('space', 'spacing to apply between cast and variable.')) ->setAllowedValues(['none', 'single']) ->setDefault('single') ->getOption(), ]); } } isTokenKindFound(T_UNSET_CAST); } public function getPriority() { return 0; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; $index > 0; --$index) { if ($tokens[$index]->isGivenKind(T_UNSET_CAST)) { $this->fixUnsetCast($tokens, $index); } } } private function fixUnsetCast(Tokens $tokens, $index) { $assignmentIndex = $tokens->getPrevMeaningfulToken($index); if (null === $assignmentIndex || !$tokens[$assignmentIndex]->equals('=')) { return; } $varIndex = $tokens->getNextMeaningfulToken($index); if (null === $varIndex || !$tokens[$varIndex]->isGivenKind(T_VARIABLE)) { return; } $afterVar = $tokens->getNextMeaningfulToken($varIndex); if (null === $afterVar || !$tokens[$afterVar]->equalsAny([';', [T_CLOSE_TAG]])) { return; } $nextIsWhiteSpace = $tokens[$assignmentIndex + 1]->isWhitespace(); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($varIndex); ++$assignmentIndex; if (!$nextIsWhiteSpace) { $tokens->insertAt($assignmentIndex, new Token([T_WHITESPACE, ' '])); } ++$assignmentIndex; $tokens->insertAt($assignmentIndex, new Token([T_STRING, 'null'])); } } isTokenKindFound('!'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; $index > 1; --$index) { if ($tokens[$index]->equals('!')) { $index = $this->fixShortCast($tokens, $index); } } } private function fixShortCast(Tokens $tokens, $index) { for ($i = $index - 1; $i > 1; --$i) { if ($tokens[$i]->equals('!')) { $this->fixShortCastToBoolCast($tokens, $i, $index); break; } if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) { break; } } return $i; } private function fixShortCastToBoolCast(Tokens $tokens, $start, $end) { for (; $start <= $end; ++$start) { if ( !$tokens[$start]->isComment() && !($tokens[$start]->isWhitespace() && $tokens[$start - 1]->isComment()) ) { $tokens->clearAt($start); } } $tokens->insertAt($start, new Token([T_BOOL_CAST, '(bool)'])); } } isAnyTokenKindsFound(Token::getCastTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $castMap = [ 'boolean' => 'bool', 'integer' => 'int', 'double' => 'float', 'real' => 'float', 'binary' => 'string', ]; for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isCast()) { continue; } $castFrom = trim(substr($tokens[$index]->getContent(), 1, -1)); $castFromLowered = strtolower($castFrom); if (!\array_key_exists($castFromLowered, $castMap)) { continue; } $tokens[$index] = new Token([ $tokens[$index]->getId(), str_replace($castFrom, $castMap[$castFromLowered], $tokens[$index]->getContent()), ]); } } } isTokenKindFound(T_STRING); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { static $replacement = [ 'intval' => [T_INT_CAST, '(int)'], 'floatval' => [T_DOUBLE_CAST, '(float)'], 'doubleval' => [T_DOUBLE_CAST, '(float)'], 'strval' => [T_STRING_CAST, '(string)'], 'boolval' => [T_BOOL_CAST, '(bool)'], ]; $argumentsAnalyzer = new ArgumentsAnalyzer(); foreach ($replacement as $functionIdentity => $newToken) { $currIndex = 0; while (null !== $currIndex) { $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); if (null === $boundaries) { continue 2; } list($functionName, $openParenthesis, $closeParenthesis) = $boundaries; $currIndex = $openParenthesis; if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis)) { continue; } $paramContentEnd = $closeParenthesis; $commaCandidate = $tokens->getPrevMeaningfulToken($paramContentEnd); if ($tokens[$commaCandidate]->equals(',')) { $tokens->removeTrailingWhitespace($commaCandidate); $tokens->clearAt($commaCandidate); $paramContentEnd = $commaCandidate; } $countParamTokens = 0; for ($paramContentIndex = $openParenthesis + 1; $paramContentIndex < $paramContentEnd; ++$paramContentIndex) { if (!$tokens[$paramContentIndex]->isGivenKind(T_WHITESPACE)) { ++$countParamTokens; } } $preserveParenthesises = $countParamTokens > 1; $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesis); $afterCloseParenthesisToken = $tokens[$afterCloseParenthesisIndex]; $wrapInParenthesises = $afterCloseParenthesisToken->equalsAny(['[', '{']) || $afterCloseParenthesisToken->isGivenKind(T_POW); $prevTokenIndex = $tokens->getPrevMeaningfulToken($functionName); if ($tokens[$prevTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { $tokens->removeTrailingWhitespace($prevTokenIndex); $tokens->clearAt($prevTokenIndex); } $replacementSequence = [ new Token($newToken), new Token([T_WHITESPACE, ' ']), ]; if ($wrapInParenthesises) { array_unshift($replacementSequence, new Token('(')); } if (!$preserveParenthesises) { $tokens->removeLeadingWhitespace($closeParenthesis); $tokens->clearAt($closeParenthesis); $tokens->removeLeadingWhitespace($openParenthesis); $tokens->removeTrailingWhitespace($openParenthesis); $tokens->clearAt($openParenthesis); } else { $tokens->removeTrailingWhitespace($functionName); } if ($wrapInParenthesises) { $tokens->insertAt($closeParenthesis, new Token(')')); } $tokens->overrideRange($functionName, $functionName, $replacementSequence); $currIndex = $functionName; } } } } isAnyTokenKindsFound([T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->clearIncludies($tokens, $this->findIncludies($tokens)); } private function clearIncludies(Tokens $tokens, array $includies) { $blocksAnalyzer = new BlocksAnalyzer(); foreach ($includies as $includy) { if ($includy['end'] && !$tokens[$includy['end']]->isGivenKind(T_CLOSE_TAG)) { $afterEndIndex = $tokens->getNextNonWhitespace($includy['end']); if (null === $afterEndIndex || !$tokens[$afterEndIndex]->isComment()) { $tokens->removeLeadingWhitespace($includy['end']); } } $braces = $includy['braces']; if (null !== $braces) { $prevIndex = $tokens->getPrevMeaningfulToken($includy['begin']); $nextIndex = $tokens->getNextMeaningfulToken($braces['close']); if (!$tokens[$nextIndex]->equalsAny([';', [T_CLOSE_TAG]]) && !$blocksAnalyzer->isBlock($tokens, $prevIndex, $nextIndex)) { continue; } $this->removeWhitespaceAroundIfPossible($tokens, $braces['open']); $this->removeWhitespaceAroundIfPossible($tokens, $braces['close']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['open']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['close']); } $nextIndex = $tokens->getNonEmptySibling($includy['begin'], 1); if ($tokens[$nextIndex]->isWhitespace()) { $tokens[$nextIndex] = new Token([T_WHITESPACE, ' ']); } elseif (null !== $braces || $tokens[$nextIndex]->isGivenKind([T_VARIABLE, T_CONSTANT_ENCAPSED_STRING, T_COMMENT])) { $tokens->insertAt($includy['begin'] + 1, new Token([T_WHITESPACE, ' '])); } } } private function findIncludies(Tokens $tokens) { static $includyTokenKinds = [T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE]; $includies = []; foreach ($tokens->findGivenKind($includyTokenKinds) as $includyTokens) { foreach ($includyTokens as $index => $token) { $includy = [ 'begin' => $index, 'braces' => null, 'end' => $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]), ]; $braceOpenIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$braceOpenIndex]->equals('(')) { $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); $includy['braces'] = [ 'open' => $braceOpenIndex, 'close' => $braceCloseIndex, ]; } $includies[$index] = $includy; } } krsort($includies); return $includies; } private function removeWhitespaceAroundIfPossible(Tokens $tokens, $index) { $nextIndex = $tokens->getNextNonWhitespace($index); if (null === $nextIndex || !$tokens[$nextIndex]->isComment()) { $tokens->removeLeadingWhitespace($index); } $prevIndex = $tokens->getPrevNonWhitespace($index); if (null === $prevIndex || !$tokens[$prevIndex]->isComment()) { $tokens->removeTrailingWhitespace($index); } } } true] ), ] ); } public function getPriority() { return 26; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound('}'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($this->findCurlyBraceOpen($tokens) as $index) { if ($this->isOverComplete($tokens, $index)) { $this->clearOverCompleteBraces($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); } } if ($this->configuration['namespaces']) { $this->clearIfIsOverCompleteNamespaceBlock($tokens); } } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('namespaces', 'Remove unneeded curly braces from bracketed namespaces.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function clearOverCompleteBraces(Tokens $tokens, $openIndex, $closeIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); } private function findCurlyBraceOpen(Tokens $tokens) { for ($i = \count($tokens) - 1; $i > 0; --$i) { if ($tokens[$i]->equals('{')) { yield $i; } } } private function isOverComplete(Tokens $tokens, $index) { static $include = ['{', '}', [T_OPEN_TAG], ':', ';']; return $tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny($include); } private function clearIfIsOverCompleteNamespaceBlock(Tokens $tokens) { if (Tokens::isLegacyMode()) { $index = $tokens->getNextTokenOfKind(0, [[T_NAMESPACE]]); $secondNamespaceIndex = $tokens->getNextTokenOfKind($index, [[T_NAMESPACE]]); if (null !== $secondNamespaceIndex) { return; } } elseif (1 !== $tokens->countTokenKind(T_NAMESPACE)) { return; } $index = $tokens->getNextTokenOfKind(0, [[T_NAMESPACE]]); do { $index = $tokens->getNextMeaningfulToken($index); } while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])); if (!$tokens[$index]->equals('{')) { return; } $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); if (null !== $afterCloseIndex && (!$tokens[$afterCloseIndex]->isGivenKind(T_CLOSE_TAG) || null !== $tokens->getNextMeaningfulToken($afterCloseIndex))) { return; } $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); $tokens[$index] = new Token(';'); if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($index - 1); } } } isTokenKindFound(T_ELSE); } public function getDefinition() { return new FixerDefinition( 'There should not be useless `else` cases.', [ new CodeSample(" $token) { if (!$token->isGivenKind(T_ELSE)) { continue; } if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny([':', [T_IF]])) { continue; } $this->fixEmptyElse($tokens, $index); if ($tokens->isEmptyAt($index)) { continue; } if ($this->isSuperfluousElse($tokens, $index)) { $this->clearElse($tokens, $index); } } } private function fixEmptyElse(Tokens $tokens, $index) { $next = $tokens->getNextMeaningfulToken($index); if ($tokens[$next]->equals('{')) { $close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next); if (1 === $close - $next) { $this->clearElse($tokens, $index); } elseif ($tokens->getNextMeaningfulToken($next) === $close) { $this->clearElse($tokens, $index); } return; } $end = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); if ($next === $end) { $this->clearElse($tokens, $index); } } private function clearElse(Tokens $tokens, $index) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); $next = $tokens->getNextMeaningfulToken($index); if (!$tokens[$next]->equals('{')) { return; } $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next)); $tokens->clearTokenAndMergeSurroundingWhitespace($next); } } hasAlternativeSyntax(); } public function getPriority() { return 26; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = \count($tokens) - 1; 0 <= $index; --$index) { $token = $tokens[$index]; $this->fixElseif($index, $token, $tokens); $this->fixElse($index, $token, $tokens); $this->fixOpenCloseControls($index, $token, $tokens); } } private function findParenthesisEnd(Tokens $tokens, $structureTokenIndex) { $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); $nextToken = $tokens[$nextIndex]; if (!$nextToken->equals('(')) { return $structureTokenIndex; } return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); } private function fixOpenCloseControls($index, Token $token, Tokens $tokens) { if ($token->isGivenKind([T_IF, T_FOREACH, T_WHILE, T_FOR, T_SWITCH, T_DECLARE])) { $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $afterParenthesisIndex = $tokens->getNextMeaningfulToken($closeIndex); $afterParenthesis = $tokens[$afterParenthesisIndex]; if (!$afterParenthesis->equals(':')) { return; } $items = []; if (!$tokens[$afterParenthesisIndex - 1]->isWhitespace()) { $items[] = new Token([T_WHITESPACE, ' ']); } $items[] = new Token('{'); if (!$tokens[$afterParenthesisIndex + 1]->isWhitespace()) { $items[] = new Token([T_WHITESPACE, ' ']); } $tokens->clearAt($afterParenthesisIndex); $tokens->insertAt($afterParenthesisIndex, $items); } if (!$token->isGivenKind([T_ENDIF, T_ENDFOREACH, T_ENDWHILE, T_ENDFOR, T_ENDSWITCH, T_ENDDECLARE])) { return; } $nextTokenIndex = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$nextTokenIndex]; $tokens[$index] = new Token('}'); if ($nextToken->equals(';')) { $tokens->clearAt($nextTokenIndex); } } private function fixElse($index, Token $token, Tokens $tokens) { if (!$token->isGivenKind(T_ELSE)) { return; } $tokenAfterElseIndex = $tokens->getNextMeaningfulToken($index); $tokenAfterElse = $tokens[$tokenAfterElseIndex]; if (!$tokenAfterElse->equals(':')) { return; } $this->addBraces($tokens, new Token([T_ELSE, 'else']), $index, $tokenAfterElseIndex); } private function fixElseif($index, Token $token, Tokens $tokens) { if (!$token->isGivenKind(T_ELSEIF)) { return; } $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $tokenAfterParenthesisIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); $tokenAfterParenthesis = $tokens[$tokenAfterParenthesisIndex]; if (!$tokenAfterParenthesis->equals(':')) { return; } $this->addBraces($tokens, new Token([T_ELSEIF, 'elseif']), $index, $tokenAfterParenthesisIndex); } private function addBraces(Tokens $tokens, Token $token, $index, $colonIndex) { $items = [ new Token('}'), new Token([T_WHITESPACE, ' ']), $token, ]; if (!$tokens[$index + 1]->isWhitespace()) { $items[] = new Token([T_WHITESPACE, ' ']); } $tokens->clearAt($index); $tokens->insertAt( $index, $items ); $colonIndex += \count($items); $items = [new Token('{')]; if (!$tokens[$colonIndex + 1]->isWhitespace()) { $items[] = new Token([T_WHITESPACE, ' ']); } $tokens->clearAt($colonIndex); $tokens->insertAt( $colonIndex, $items ); } } isAnyTokenKindsFound([T_CASE, T_DEFAULT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind([T_CASE, T_DEFAULT])) { continue; } $ternariesCount = 0; for ($colonIndex = $index + 1;; ++$colonIndex) { if ($tokens[$colonIndex]->equals('?')) { ++$ternariesCount; } if ($tokens[$colonIndex]->equalsAny([':', ';'])) { if (0 === $ternariesCount) { break; } --$ternariesCount; } } $valueIndex = $tokens->getPrevNonWhitespace($colonIndex); if ($valueIndex === $colonIndex - 1 || $tokens[$valueIndex]->isComment()) { continue; } $tokens->clearAt($valueIndex + 1); } } } ['lookupTokens' => T_BREAK, 'neededSuccessors' => [';']], 'clone' => ['lookupTokens' => T_CLONE, 'neededSuccessors' => [';', ':', ',', ')'], 'forbiddenContents' => ['?', ':']], 'continue' => ['lookupTokens' => T_CONTINUE, 'neededSuccessors' => [';']], 'echo_print' => ['lookupTokens' => [T_ECHO, T_PRINT], 'neededSuccessors' => [';', [T_CLOSE_TAG]]], 'return' => ['lookupTokens' => T_RETURN, 'neededSuccessors' => [';', [T_CLOSE_TAG]]], 'switch_case' => ['lookupTokens' => T_CASE, 'neededSuccessors' => [';', ':']], 'yield' => ['lookupTokens' => T_YIELD, 'neededSuccessors' => [';', ')']], ]; public function __construct() { parent::__construct(); if (\defined('T_COALESCE')) { self::$loops['clone']['forbiddenContents'][] = [T_COALESCE, '??']; } } public function isCandidate(Tokens $tokens) { $types = []; foreach (self::$loops as $loop) { $types[] = (array) $loop['lookupTokens']; } $types = array_merge(...$types); return $tokens->isAnyTokenKindsFound($types); } public function getDefinition() { return new FixerDefinition( 'Removes unneeded parentheses around control statements.', [ new CodeSample( ' ['break', 'continue']] ), ] ); } public function getPriority() { return 30; } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $loops = array_intersect_key(self::$loops, array_flip($this->configuration['statements'])); foreach ($tokens as $index => $token) { if (!$token->equalsAny(['(', [CT::T_BRACE_CLASS_INSTANTIATION_OPEN]])) { continue; } $blockStartIndex = $index; $index = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$index]; foreach ($loops as $loop) { if (!$prevToken->isGivenKind($loop['lookupTokens'])) { continue; } $blockEndIndex = $tokens->findBlockEnd( $token->equals('(') ? Tokens::BLOCK_TYPE_PARENTHESIS_BRACE : Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, $blockStartIndex ); $blockEndNextIndex = $tokens->getNextMeaningfulToken($blockEndIndex); if (!$tokens[$blockEndNextIndex]->equalsAny($loop['neededSuccessors'])) { continue; } if (\array_key_exists('forbiddenContents', $loop)) { $forbiddenTokenIndex = $tokens->getNextTokenOfKind($blockStartIndex, $loop['forbiddenContents']); if (null !== $forbiddenTokenIndex && $forbiddenTokenIndex < $blockEndIndex) { continue; } } if ($tokens[$blockStartIndex - 1]->isWhitespace() || $tokens[$blockStartIndex - 1]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($blockStartIndex); } else { $tokens[$blockStartIndex] = new Token([T_WHITESPACE, ' ']); } $tokens->clearTokenAndMergeSurroundingWhitespace($blockEndIndex); } } } protected function createConfigurationDefinition() { return new FixerConfigurationResolverRootless('statements', [ (new FixerOptionBuilder('statements', 'List of control statements to fix.')) ->setAllowedTypes(['array']) ->setDefault([ 'break', 'clone', 'continue', 'echo_print', 'return', 'switch_case', 'yield', ]) ->getOption(), ], $this->getName()); } } 'some comment'] ), ], 'Adds a "no break" comment before fall-through cases, and removes it if there is no fall-through.' ); } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound([T_CASE, T_DEFAULT]); } public function getPriority() { return 0; } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('comment_text', 'The text to use in the added comment and to detect it.')) ->setAllowedTypes(['string']) ->setAllowedValues([ static function ($value) { if (\is_string($value) && Preg::match('/\R/', $value)) { throw new InvalidOptionsException('The comment text must not contain new lines.'); } return true; }, ]) ->setNormalizer(static function (Options $options, $value) { return rtrim($value); }) ->setDefault('no break') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($position = \count($tokens) - 1; $position >= 0; --$position) { if ($tokens[$position]->isGivenKind([T_CASE, T_DEFAULT])) { $this->fixCase($tokens, $position); } } } private function fixCase(Tokens $tokens, $casePosition) { $empty = true; $fallThrough = true; $commentPosition = null; $caseColonIndex = $tokens->getNextTokenOfKind($casePosition, [':', ';']); for ($i = $caseColonIndex + 1, $max = \count($tokens); $i < $max; ++$i) { if ($tokens[$i]->isGivenKind([T_SWITCH, T_IF, T_ELSE, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_DO, T_FUNCTION, T_CLASS])) { $empty = false; $i = $this->getStructureEnd($tokens, $i); continue; } if ($tokens[$i]->isGivenKind([T_BREAK, T_CONTINUE, T_RETURN, T_EXIT, T_GOTO])) { $fallThrough = false; continue; } if ($tokens[$i]->isGivenKind([T_THROW])) { $previousIndex = $tokens->getPrevMeaningfulToken($i); if ($previousIndex === $caseColonIndex || $tokens[$previousIndex]->equalsAny(['{', ';', '}', [T_OPEN_TAG]])) { $fallThrough = false; } continue; } if ($tokens[$i]->equals('}') || $tokens[$i]->isGivenKind(T_ENDSWITCH)) { if (null !== $commentPosition) { $this->removeComment($tokens, $commentPosition); } break; } if ($this->isNoBreakComment($tokens[$i])) { $commentPosition = $i; continue; } if ($tokens[$i]->isGivenKind([T_CASE, T_DEFAULT])) { if (!$empty && $fallThrough) { if (null !== $commentPosition && $tokens->getPrevNonWhitespace($i) !== $commentPosition) { $this->removeComment($tokens, $commentPosition); $commentPosition = null; } if (null === $commentPosition) { $this->insertCommentAt($tokens, $i); } else { $text = $this->configuration['comment_text']; $tokens[$commentPosition] = new Token([ $tokens[$commentPosition]->getId(), str_ireplace($text, $text, $tokens[$commentPosition]->getContent()), ]); $this->ensureNewLineAt($tokens, $commentPosition); } } elseif (null !== $commentPosition) { $this->removeComment($tokens, $commentPosition); } break; } if (!$tokens[$i]->isGivenKind([T_COMMENT, T_WHITESPACE])) { $empty = false; } } } private function isNoBreakComment(Token $token) { if (!$token->isComment()) { return false; } $text = preg_quote($this->configuration['comment_text'], '~'); return 1 === Preg::match("~^((//|#)\\s*{$text}\\s*)|(/\\*\\*?\\s*{$text}\\s*\\*/)$~i", $token->getContent()); } private function insertCommentAt(Tokens $tokens, $casePosition) { $lineEnding = $this->whitespacesConfig->getLineEnding(); $newlinePosition = $this->ensureNewLineAt($tokens, $casePosition); $newlineToken = $tokens[$newlinePosition]; $nbNewlines = substr_count($newlineToken->getContent(), $lineEnding); if ($newlineToken->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $newlineToken->getContent())) { ++$nbNewlines; } elseif ($tokens[$newlinePosition - 1]->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $tokens[$newlinePosition - 1]->getContent())) { ++$nbNewlines; if (!Preg::match('/\R/', $newlineToken->getContent())) { $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $lineEnding.$newlineToken->getContent()]); } } if ($nbNewlines > 1) { Preg::match('/^(.*?)(\R\h*)$/s', $newlineToken->getContent(), $matches); $indent = $this->getIndentAt($tokens, $newlinePosition - 1); $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $matches[1].$lineEnding.$indent]); $tokens->insertAt(++$newlinePosition, new Token([T_WHITESPACE, $matches[2]])); } $tokens->insertAt($newlinePosition, new Token([T_COMMENT, '// '.$this->configuration['comment_text']])); $this->ensureNewLineAt($tokens, $newlinePosition); } private function ensureNewLineAt(Tokens $tokens, $position) { $lineEnding = $this->whitespacesConfig->getLineEnding(); $content = $lineEnding.$this->getIndentAt($tokens, $position); $whitespaceToken = $tokens[$position - 1]; if (!$whitespaceToken->isGivenKind(T_WHITESPACE)) { if ($whitespaceToken->isGivenKind(T_OPEN_TAG)) { $content = Preg::replace('/\R/', '', $content); if (!Preg::match('/\R/', $whitespaceToken->getContent())) { $tokens[$position - 1] = new Token([T_OPEN_TAG, Preg::replace('/\s+$/', $lineEnding, $whitespaceToken->getContent())]); } } if ('' !== $content) { $tokens->insertAt($position, new Token([T_WHITESPACE, $content])); return $position; } return $position - 1; } if ($tokens[$position - 2]->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $tokens[$position - 2]->getContent())) { $content = Preg::replace('/^\R/', '', $content); } if (!Preg::match('/\R/', $whitespaceToken->getContent())) { $tokens[$position - 1] = new Token([T_WHITESPACE, $content]); } return $position - 1; } private function removeComment(Tokens $tokens, $commentPosition) { if ($tokens[$tokens->getPrevNonWhitespace($commentPosition)]->isGivenKind(T_OPEN_TAG)) { $whitespacePosition = $commentPosition + 1; $regex = '/^\R\h*/'; } else { $whitespacePosition = $commentPosition - 1; $regex = '/\R\h*$/'; } $whitespaceToken = $tokens[$whitespacePosition]; if ($whitespaceToken->isGivenKind(T_WHITESPACE)) { $content = Preg::replace($regex, '', $whitespaceToken->getContent()); if ('' !== $content) { $tokens[$whitespacePosition] = new Token([T_WHITESPACE, $content]); } else { $tokens->clearAt($whitespacePosition); } } $tokens->clearTokenAndMergeSurroundingWhitespace($commentPosition); } private function getIndentAt(Tokens $tokens, $position) { while (true) { $position = $tokens->getPrevTokenOfKind($position, [[T_WHITESPACE]]); if (null === $position) { break; } $content = $tokens[$position]->getContent(); $prevToken = $tokens[$position - 1]; if ($prevToken->isGivenKind(T_OPEN_TAG) && Preg::match('/\R$/', $prevToken->getContent())) { $content = $this->whitespacesConfig->getLineEnding().$content; } if (Preg::match('/\R(\h*)$/', $content, $matches)) { return $matches[1]; } } return ''; } private function getStructureEnd(Tokens $tokens, $position) { $initialToken = $tokens[$position]; if ($initialToken->isGivenKind([T_FOR, T_FOREACH, T_WHILE, T_IF, T_ELSEIF, T_SWITCH, T_FUNCTION])) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($position, ['(']) ); } elseif ($initialToken->isGivenKind(T_CLASS)) { $openParenthesisPosition = $tokens->getNextMeaningfulToken($position); if ('(' === $tokens[$openParenthesisPosition]->getContent()) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisPosition ); } } $position = $tokens->getNextMeaningfulToken($position); if ('{' !== $tokens[$position]->getContent()) { return $tokens->getNextTokenOfKind($position, [';']); } $position = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $position); if ($initialToken->isGivenKind(T_DO)) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($position, ['(']) ); return $tokens->getNextTokenOfKind($position, [';']); } return $position; } } isAnyTokenKindsFound([T_CASE, T_DEFAULT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if ($token->isGivenKind([T_CASE, T_DEFAULT])) { $this->fixSwitchCase($tokens, $index); } } } protected function fixSwitchCase(Tokens $tokens, $index) { $ternariesCount = 0; do { if ($tokens[$index]->equalsAny(['(', '{'])) { $type = Tokens::detectBlockType($tokens[$index]); $index = $tokens->findBlockEnd($type['type'], $index); continue; } if ($tokens[$index]->equals('?')) { ++$ternariesCount; continue; } if ($tokens[$index]->equalsAny([':', ';'])) { if (0 === $ternariesCount) { break; } --$ternariesCount; } } while (++$index); if ($tokens[$index]->equals(';')) { $tokens[$index] = new Token(':'); } } } isAllTokenKindsFound([T_IF, T_ELSE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(T_ELSE)) { continue; } $ifTokenIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$ifTokenIndex]->isGivenKind(T_IF)) { continue; } $conditionEndBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($ifTokenIndex)); $afterConditionIndex = $tokens->getNextMeaningfulToken($conditionEndBraceIndex); if ($tokens[$afterConditionIndex]->equals(':')) { continue; } $tokens->clearAt($index + 1); $tokens[$index] = new Token([T_ELSEIF, 'elseif']); $tokens->clearAt($ifTokenIndex); $beforeIfTokenIndex = $tokens->getPrevNonWhitespace($ifTokenIndex); if ($tokens[$beforeIfTokenIndex]->isComment() && $tokens[$ifTokenIndex + 1]->isWhitespace()) { $tokens->clearAt($ifTokenIndex + 1); } } } } isTokenKindFound(T_LIST); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(T_LIST)) { continue; } $openIndex = $tokens->getNextMeaningfulToken($index); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $markIndex = null; $prevIndex = $tokens->getPrevNonWhitespace($closeIndex); while ($tokens[$prevIndex]->equals(',')) { $markIndex = $prevIndex; $prevIndex = $tokens->getPrevNonWhitespace($prevIndex); } if (null !== $markIndex) { $tokens->clearRange( $tokens->getPrevNonWhitespace($markIndex) + 1, $closeIndex - 1 ); } } } } resolveConfiguration(); } public function getDefinition() { return new FixerDefinition( 'Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.', [ new CodeSample( ' 3; // less than ', [ 'equal' => true, 'identical' => false, 'less_and_greater' => null, ] ), new CodeSample( ' true, ] ), new CodeSample( ' false, 'identical' => false, 'less_and_greater' => false, ] ), ] ); } public function getPriority() { return 0; } public function isCandidate(Tokens $tokens) { return $tokens->isAnyTokenKindsFound($this->candidateTypes); } protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $this->fixTokens($tokens); } protected function createConfigurationDefinition() { return new FixerConfigurationResolver([ (new FixerOptionBuilder('equal', 'Style for equal (`==`, `!=`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('identical', 'Style for identical (`===`, `!==`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('less_and_greater', 'Style for less and greater than (`<`, `<=`, `>`, `>=`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(null) ->getOption(), (new FixerOptionBuilder('always_move_variable', 'Whether variables should always be on non assignable side when applying Yoda style.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function findComparisonEnd(Tokens $tokens, $index) { ++$index; $count = \count($tokens); while ($index < $count) { $token = $tokens[$index]; if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { ++$index; continue; } if ($this->isOfLowerPrecedence($token)) { break; } $block = Tokens::detectBlockType($token); if (null === $block) { ++$index; continue; } if (!$block['isStart']) { break; } $index = $tokens->findBlockEnd($block['type'], $index) + 1; } $prev = $tokens->getPrevMeaningfulToken($index); return $tokens[$prev]->isGivenKind(T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev; } private function findComparisonStart(Tokens $tokens, $index) { --$index; $nonBlockFound = false; while (0 <= $index) { $token = $tokens[$index]; if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { --$index; continue; } if ($this->isOfLowerPrecedence($token)) { break; } $block = Tokens::detectBlockType($token); if (null === $block) { --$index; $nonBlockFound = true; continue; } if ( $block['isStart'] || ($nonBlockFound && Tokens::BLOCK_TYPE_CURLY_BRACE === $block['type']) ) { break; } $index = $tokens->findBlockStart($block['type'], $index) - 1; } return $tokens->getNextMeaningfulToken($index); } private function fixTokens(Tokens $tokens) { for ($i = \count($tokens) - 1; $i > 1; --$i) { if ($tokens[$i]->isGivenKind($this->candidateTypes)) { $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getId()]; } elseif ( ($tokens[$i]->equals('<') && \in_array('<', $this->candidateTypes, true)) || ($tokens[$i]->equals('>') && \in_array('>', $this->candidateTypes, true)) ) { $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getContent()]; } else { continue; } $fixableCompareInfo = $this->getCompareFixableInfo($tokens, $i, $yoda); if (null === $fixableCompareInfo) { continue; } $i = $this->fixTokensCompare( $tokens, $fixableCompareInfo['left']['start'], $fixableCompareInfo['left']['end'], $i, $fixableCompareInfo['right']['start'], $fixableCompareInfo['right']['end'] ); } return $tokens; } private function fixTokensCompare( Tokens $tokens, $startLeft, $endLeft, $compareOperatorIndex, $startRight, $endRight ) { $type = $tokens[$compareOperatorIndex]->getId(); $content = $tokens[$compareOperatorIndex]->getContent(); if (\array_key_exists($type, $this->candidatesMap)) { $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type]; } elseif (\array_key_exists($content, $this->candidatesMap)) { $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content]; } $right = $this->fixTokensComparePart($tokens, $startRight, $endRight); $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft); for ($i = $startRight; $i <= $endRight; ++$i) { $tokens->clearAt($i); } for ($i = $startLeft; $i <= $endLeft; ++$i) { $tokens->clearAt($i); } $tokens->insertAt($startRight, $left); $tokens->insertAt($startLeft, $right); return $startLeft; } private function fixTokensComparePart(Tokens $tokens, $start, $end) { $newTokens = $tokens->generatePartialCode($start, $end); $newTokens = $this->fixTokens(Tokens::fromCode(sprintf('clearAt(\count($newTokens) - 1); $newTokens->clearAt(0); $newTokens->clearEmptyTokens(); return $newTokens; } private function getCompareFixableInfo(Tokens $tokens, $index, $yoda) { $left = $this->getLeftSideCompareFixableInfo($tokens, $index); $right = $this->getRightSideCompareFixableInfo($tokens, $index); if (!$yoda && $tokens[$tokens->getNextMeaningfulToken($right['end'])]->equals('=')) { return null; } if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) { return null; } $strict = $this->configuration['always_move_variable']; $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict); $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict); if (!($leftSideIsVariable ^ $rightSideIsVariable)) { return null; } if (!$strict) { $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('('); $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('('); } return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable) ? null : ['left' => $left, 'right' => $right] ; } private function getLeftSideCompareFixableInfo(Tokens $tokens, $index) { return [ 'start' => $this->findComparisonStart($tokens, $index), 'end' => $tokens->getPrevMeaningfulToken($index), ]; } private function getRightSideCompareFixableInfo(Tokens $tokens, $index) { return [ 'start' => $tokens->getNextMeaningfulToken($index), 'end' => $this->findComparisonEnd($tokens, $index), ]; } private function isListStatement(Tokens $tokens, $index, $end) { for ($i = $index; $i <= $end; ++$i) { if ($tokens[$i]->isGivenKind([T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { return true; } } return false; } private function isOfLowerPrecedence(Token $token) { static $tokens; if (null === $tokens) { $tokens = [ T_AND_EQUAL, T_BOOLEAN_AND, T_BOOLEAN_OR, T_CASE, T_CONCAT_EQUAL, T_DIV_EQUAL, T_DOUBLE_ARROW, T_ECHO, T_GOTO, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR, T_MINUS_EQUAL, T_MOD_EQUAL, T_MUL_EQUAL, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_OR_EQUAL, T_PLUS_EQUAL, T_POW_EQUAL, T_PRINT, T_RETURN, T_SL_EQUAL, T_SR_EQUAL, T_THROW, T_XOR_EQUAL, ]; if (\defined('T_COALESCE')) { $tokens[] = T_COALESCE; } if (\defined('T_COALESCE_EQUAL')) { $tokens[] = T_COALESCE_EQUAL; } } static $otherTokens = [ '&', '|', '^', '?', ':', '=', ',', ';', ]; return $token->isGivenKind($tokens) || $token->equalsAny($otherTokens); } private function isVariable(Tokens $tokens, $start, $end, $strict) { $tokenAnalyzer = new TokensAnalyzer($tokens); if ($start === $end) { return $tokens[$start]->isGivenKind(T_VARIABLE); } if ($tokens[$start]->equals('(')) { return true; } if ($strict) { for ($index = $start; $index <= $end; ++$index) { if ( $tokens[$index]->isCast() || $tokens[$index]->isGivenKind(T_INSTANCEOF) || $tokens[$index]->equals('!') || $tokenAnalyzer->isBinaryOperator($index) ) { return false; } } } $index = $start; while ( $tokens[$index]->equals('(') && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) === $end ) { $index = $tokens->getNextMeaningfulToken($index); $end = $tokens->getPrevMeaningfulToken($end); } $expectString = false; while ($index <= $end) { $current = $tokens[$index]; if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) { ++$index; continue; } if ($index === $end) { return $current->isGivenKind($expectString ? T_STRING : T_VARIABLE); } if ($current->isGivenKind([T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { return false; } $nextIndex = $tokens->getNextMeaningfulToken($index); $next = $tokens[$nextIndex]; if ($current->isGivenKind(T_STRING) && $next->isGivenKind(T_DOUBLE_COLON)) { $index = $tokens->getNextMeaningfulToken($nextIndex); continue; } if ($current->isGivenKind(T_NS_SEPARATOR) && $next->isGivenKind(T_STRING)) { $index = $nextIndex; continue; } if ($current->isGivenKind(T_STRING) && $next->isGivenKind(T_NS_SEPARATOR)) { $index = $nextIndex; continue; } if ($current->isGivenKind([T_STRING, T_VARIABLE]) && $next->isGivenKind(T_OBJECT_OPERATOR)) { $index = $tokens->getNextMeaningfulToken($nextIndex); $expectString = true; continue; } if ( $current->isGivenKind($expectString ? T_STRING : T_VARIABLE) && $next->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) ) { $index = $tokens->findBlockEnd( $next->equals('[') ? Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE : Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $nextIndex ); if ($index === $end) { return true; } $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->equalsAny([[T_OBJECT_OPERATOR, '->'], '[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']])) { return false; } $index = $tokens->getNextMeaningfulToken($index); $expectString = true; continue; } if ($strict && $current->isGivenKind([T_STRING, T_VARIABLE]) && $next->equals('(')) { return false; } if ($expectString && $current->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index); if ($index === $end) { return true; } $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->isGivenKind(T_OBJECT_OPERATOR)) { return false; } $index = $tokens->getNextMeaningfulToken($index); $expectString = true; continue; } break; } return !$this->isConstant($tokens, $start, $end); } private function isConstant(Tokens $tokens, $index, $end) { $expectArrayOnly = false; $expectNumberOnly = false; $expectNothing = false; for (; $index <= $end; ++$index) { $token = $tokens[$index]; if ($token->isComment() || $token->isWhitespace()) { continue; } if ($expectNothing) { return false; } if ($expectArrayOnly) { if ($token->equalsAny(['(', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) { continue; } return false; } if ($token->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $expectArrayOnly = true; continue; } if ($expectNumberOnly && !$token->isGivenKind([T_LNUMBER, T_DNUMBER])) { return false; } if ($token->equals('-')) { $expectNumberOnly = true; continue; } if ( $token->isGivenKind([T_LNUMBER, T_DNUMBER, T_CONSTANT_ENCAPSED_STRING]) || $token->equalsAny([[T_STRING, 'true'], [T_STRING, 'false'], [T_STRING, 'null']]) ) { $expectNothing = true; continue; } return false; } return true; } private function resolveConfiguration() { $candidateTypes = []; $this->candidatesMap = []; if (null !== $this->configuration['equal']) { $candidateTypes[T_IS_EQUAL] = $this->configuration['equal']; $candidateTypes[T_IS_NOT_EQUAL] = $this->configuration['equal']; } if (null !== $this->configuration['identical']) { $candidateTypes[T_IS_IDENTICAL] = $this->configuration['identical']; $candidateTypes[T_IS_NOT_IDENTICAL] = $this->configuration['identical']; } if (null !== $this->configuration['less_and_greater']) { $candidateTypes[T_IS_SMALLER_OR_EQUAL] = $this->configuration['less_and_greater']; $this->candidatesMap[T_IS_SMALLER_OR_EQUAL] = new Token([T_IS_GREATER_OR_EQUAL, '>=']); $candidateTypes[T_IS_GREATER_OR_EQUAL] = $this->configuration['less_and_greater']; $this->candidatesMap[T_IS_GREATER_OR_EQUAL] = new Token([T_IS_SMALLER_OR_EQUAL, '<=']); $candidateTypes['<'] = $this->configuration['less_and_greater']; $this->candidatesMap['<'] = new Token('>'); $candidateTypes['>'] = $this->configuration['less_and_greater']; $this->candidatesMap['>'] = new Token('<'); } $this->candidateTypesConfiguration = $candidateTypes; $this->candidateTypes = array_keys($candidateTypes); } } isAnyTokenKindsFound([T_ELSE, T_ELSEIF]); } public function getDefinition() { return new FixerDefinition( 'Replaces superfluous `elseif` with `if`.', [ new CodeSample(" $token) { if ($this->isElseif($tokens, $index) && $this->isSuperfluousElse($tokens, $index)) { $this->convertElseifToIf($tokens, $index); } } } private function isElseif(Tokens $tokens, $index) { return $tokens[$index]->isGivenKind(T_ELSEIF) || ($tokens[$index]->isGivenKind(T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_IF)) ; } private function convertElseifToIf(Tokens $tokens, $index) { if ($tokens[$index]->isGivenKind(T_ELSE)) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } else { $tokens[$index] = new Token([T_IF, 'if']); } $whitespace = ''; for ($previous = $index - 1; $previous > 0; --$previous) { $token = $tokens[$previous]; if ($token->isWhitespace() && Preg::match('/(\R\N*)$/', $token->getContent(), $matches)) { $whitespace = $matches[1]; break; } } if ('' === $whitespace) { return; } $previousToken = $tokens[$index - 1]; if (!$previousToken->isWhitespace()) { $tokens->insertAt($index, new Token([T_WHITESPACE, $whitespace])); } elseif (!Preg::match('/\R/', $previousToken->getContent())) { $tokens[$index - 1] = new Token([T_WHITESPACE, $whitespace]); } } } isGivenKind(T_CLASS)) { throw new \LogicException(sprintf('No "T_CLASS" at given index %d, got "%s".', $index, $tokens[$index]->getName())); } $index = $tokens->getNextMeaningfulToken($index); if (0 !== Preg::match('/(?:Test|TestCase)$/', $tokens[$index]->getContent())) { return true; } while (null !== $index = $tokens->getNextMeaningfulToken($index)) { if ($tokens[$index]->equals('{')) { break; } if (!$tokens[$index]->isGivenKind(T_STRING)) { continue; } if (0 !== Preg::match('/(?:Test|TestCase)(?:Interface)?$/', $tokens[$index]->getContent())) { return true; } } return false; } public function findPhpUnitClasses(Tokens $tokens) { for ($index = $tokens->count() - 1; $tokens->offsetExists($index); --$index) { if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isPhpUnitClass($tokens, $index)) { continue; } $startIndex = $tokens->getNextTokenOfKind($index, ['{'], false); if (null === $startIndex) { return; } $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); yield [$startIndex, $endIndex]; } } } fixerName = $fixerName; } public function getFixerName() { return $this->fixerName; } } isWhitespace()) { throw new \InvalidArgumentException(sprintf('The given token must be whitespace, got "%s".', $token->getName())); } $str = strrchr( str_replace(["\r\n", "\r"], "\n", $token->getContent()), "\n" ); if (false === $str) { return ''; } return ltrim($str, "\n"); } public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues) { array_walk($elements, static function (&$element, $index) use ($getComparedValue) { $element = [$element, $index, $getComparedValue($element)]; }); usort($elements, static function ($a, $b) use ($compareValues) { $comparison = $compareValues($a[2], $b[2]); if (0 !== $comparison) { return $comparison; } return self::cmpInt($a[1], $b[1]); }); return array_map(static function (array $item) { return $item[0]; }, $elements); } public static function sortFixers(array $fixers) { return self::stableSort( $fixers, static function (FixerInterface $fixer) { return $fixer->getPriority(); }, static function ($a, $b) { return self::cmpInt($b, $a); } ); } public static function naturalLanguageJoinWithBackticks(array $names) { if (empty($names)) { throw new \InvalidArgumentException('Array of names cannot be empty'); } $names = array_map(static function ($name) { return sprintf('`%s`', $name); }, $names); $last = array_pop($names); if ($names) { return implode(', ', $names).' and '.$last; } return $last; } } isArray = true; $this->id = $token[0]; $this->content = $token[1]; if ($token[0] && '' === $token[1]) { throw new \InvalidArgumentException('Cannot set empty content for id-based Token.'); } } elseif (\is_string($token)) { $this->isArray = false; $this->content = $token; } else { throw new \InvalidArgumentException(sprintf( 'Cannot recognize input value as valid Token prototype, got "%s".', \is_object($token) ? \get_class($token) : \gettype($token) )); } } public static function getCastTokenKinds() { static $castTokens = [T_ARRAY_CAST, T_BOOL_CAST, T_DOUBLE_CAST, T_INT_CAST, T_OBJECT_CAST, T_STRING_CAST, T_UNSET_CAST]; return $castTokens; } public static function getClassyTokenKinds() { static $classTokens = [T_CLASS, T_TRAIT, T_INTERFACE]; return $classTokens; } public function clear() { @trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED); Tokens::setLegacyMode(true); $this->content = ''; $this->id = null; $this->isArray = false; } public function clearChanged() { @trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED); Tokens::setLegacyMode(true); $this->changed = false; } public function equals($other, $caseSensitive = true) { if ($other instanceof self) { if (!$other->isArray) { $otherPrototype = $other->content; } else { $otherPrototype = [ $other->id, $other->content, ]; } } else { $otherPrototype = $other; } if ($this->isArray !== \is_array($otherPrototype)) { return false; } if (!$this->isArray) { return $this->content === $otherPrototype; } if ($this->id !== $otherPrototype[0]) { return false; } if (isset($otherPrototype[1])) { if ($caseSensitive) { if ($this->content !== $otherPrototype[1]) { return false; } } elseif (0 !== strcasecmp($this->content, $otherPrototype[1])) { return false; } } unset($otherPrototype[0], $otherPrototype[1]); return empty($otherPrototype); } public function equalsAny(array $others, $caseSensitive = true) { foreach ($others as $other) { if ($this->equals($other, $caseSensitive)) { return true; } } return false; } public static function isKeyCaseSensitive($caseSensitive, $key) { if (\is_array($caseSensitive)) { return isset($caseSensitive[$key]) ? $caseSensitive[$key] : true; } return $caseSensitive; } public function getPrototype() { if (!$this->isArray) { return $this->content; } return [ $this->id, $this->content, ]; } public function getContent() { return $this->content; } public function getId() { return $this->id; } public function getName() { if (null === $this->id) { return null; } return self::getNameForId($this->id); } public static function getNameForId($id) { if (CT::has($id)) { return CT::getName($id); } $name = token_name($id); return 'UNKNOWN' === $name ? null : $name; } public static function getKeywords() { static $keywords = null; if (null === $