mirror of https://github.com/FriendsOfTYPO3/tea.git synced 2024-11-10 05:56:11 +01:00
tea/tools/php-cs-fixer
Oliver Klee ef38d7d84b
[TASK] Drop the .phar suffix from the tools (#204)
PhpStorm by default indexes `*.phar` files. For our current set of
tools, we do not want this. (This keeps PhpStorm from complaining
about multiple versions of the same class.)

Also mark the tools as binary for git.
2021-02-24 12:02:56 +01:00

116124 lines
No EOL
2.1 MiB
Executable file
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env php
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* 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 === 80000
|| \PHP_VERSION_ID < 50600
|| \PHP_VERSION_ID >= 80100
) {
fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 8.0.*.\n");
fwrite(STDERR, 'Current PHP version: '.PHP_VERSION.".\n");
if (defined('PHP_VERSION_ID') && \PHP_VERSION_ID === 80000) {
fwrite(STDERR, "PHP CS Fixer is not able run on PHP 8.0.0 due to bug in PHP tokenizer (https://bugs.php.net/bug.php?id=80462).\n");
fwrite(STDERR, "Update PHP version to unblock execution.\n");
exit(1);
}
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 {
fwrite(STDERR, "To ignore this requirement please set `PHP_CS_FIXER_IGNORE_ENV`.\n");
fwrite(STDERR, "If you use PHP version higher than supported, you may experience code modified in a wrong way.\n");
fwrite(STDERR, "Please report such cases at https://github.com/FriendsOfPHP/PHP-CS-Fixer .\n");
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(); ?>
D<E2><00>'src/AbstractDoctrineAnnotationFixer.php<68> <00>``<60> <00>3<F8>.<2E>'src/FixerDefinition/FixerDefinition.php<00>``z=<03>:src/FixerDefinition/VersionSpecificCodeSampleInterface.php<68><00>``<60><00><><ED>l<E1>1src/FixerDefinition/VersionSpecificCodeSample.php<68><00>``<60><00>$NW<4E>0src/FixerDefinition/FixerDefinitionInterface.phpb<00>``b4/<2F><16>"src/FixerDefinition/CodeSample.php<68><00>``<60><00>M<EF> <09>+src/FixerDefinition/CodeSampleInterface.php<68><00>``<60><00><>4/<2F>5src/FixerDefinition/VersionSpecificationInterface.php<68><00>``<60><00><>ݬ<A2>,src/FixerDefinition/VersionSpecification.phpm<00>``m0E <0A><>7src/FixerDefinition/FileSpecificCodeSampleInterface.php<68><00>``<60><00>vO<>.src/FixerDefinition/FileSpecificCodeSample.phph<00>``h<75><CF8B>src/Report/GitlabReporter.php<68><00>``<60>n<>ۛ<8A>src/Report/JsonReporter.php<68><00>``<60> <0B>src/Report/ReporterFactory.php<68><00>``<60><00>Mg.<2E>src/Report/ReportSummary.php<68><00>``<60><00>)nU<6E>!src/Report/CheckstyleReporter.php<00>``<00>C<E3><43><A1>src/Report/XmlReporter.phpI
<00>``I
k<>Ѵsrc/Report/TextReporter.phpd<00>``d<00>AIմsrc/Report/JunitReporter.php<68> <00>``<60> <00><>!s<> src/Report/ReporterInterface.php<68><00>``<60><00><><03>!src/Doctrine/Annotation/Token.php<68><00>``<60>y<><79>7<D8>"src/Doctrine/Annotation/Tokens.php<00>``yː<>src/FixerFileProcessedEvent.php<68><00>``<60><00>f<13> src/Preg.php<68><00>``<60><00><><90>8<FE>src/FixerNameValidator.php<00>``<00><14>R<B1>,src/Documentation/DocumentationGenerator.phpd/<00>``d/<00><>o<1F>src/Console/Application.php<68> <00>``<60> <00><><99><BF><F8> src/Console/WarningsDetector.php<68><00>``<60><00><>/<2F>-src/Console/Output/ProcessOutputInterface.php~<00>``~<00><>Ճ<F8>$src/Console/Output/ProcessOutput.php<68> <00>``<60> z):<3A><>!src/Console/Output/NullOutput.php<68><00>``<60>~|<7C>U<9C>"src/Console/Output/ErrorOutput.php<68> <00>``<60> y=4<1A>%src/Console/ConfigurationResolver.php<68>F<00>``<60>F<00>,<2C><>)src/Console/Command/SelfUpdateCommand.phpl<00>``lQ<><51>I<C5>,src/Console/Command/DocumentationCommand.php<68>
<00>``<60>
:<3A><>k<E7>#src/Console/Command/HelpCommand.php$F<00>``$F;<3B><><88><F5>"src/Console/Command/FixCommand.php<00>``u<><11><>6src/Console/Command/FixCommandExitStatusCalculator.php;<00>``;<1F>#<23><>5src/Console/Command/DescribeNameNotFoundException.php<68><00>``<60><00><1D><><84>'src/Console/Command/DescribeCommand.php<68>*<00>``<60>*<00><>E<EF><45>5src/Console/SelfUpdate/NewVersionCheckerInterface.php<00>``,<2C>Kl<4B>0src/Console/SelfUpdate/GithubClientInterface.php<68><00>``<60><00>]<5D>δ,src/Console/SelfUpdate/NewVersionChecker.phpy<00>``yI<13><>'src/Console/SelfUpdate/GithubClient.php<68><00>``<60>99⌴src/AbstractProxyFixer.php3<00>``3<00>n<CE>m<AA>src/RuleSet.phpb<00>``b<00>G<E1><16>src/FixerFactory.php<68><00>``<60><00><><B9><B2><AB>src/PharChecker.php<68><00>``<60>C"}Ŵ)src/Runner/FileCachingLintingIterator.php<00>``ev
<AF><B4>src/Runner/Runner.php<68><00>``<60><00><><B9>ô"src/Runner/FileLintingIterator.php><00>``><00>9<AE><39><BB>!src/Runner/FileFilterIterator.phpL<00>``L<00><08><1E>src/RuleSetInterface.phpw<00>``w<00>Lf<4C><66>src/Linter/ProcessLinter.php,
<00>``,
<00>?!i<>#src/Linter/ProcessLintingResult.phpt<00>``t<18>^<5E><>%src/Linter/LintingResultInterface.phps<00>``sO:<3A>N<A7>src/Linter/LintingException.phpg<00>``g<00>K<CE><4B><FE>*src/Linter/ProcessLinterProcessBuilder.phpR<00>``R<00>C<EF><43><9F>src/Linter/TokenizerLinter.php<68><00>``<60><00>gh<10>)src/Linter/UnavailableLinterException.phps<00>``s<00><>src/Linter/Linter.php8<00>``8<00>X<D7>ϴ%src/Linter/TokenizerLintingResult.phpF<00>``F<00><>o6<6F>src/Linter/CachingLinter.php<68><00>``<60><00>ln<6C>src/Linter/LinterInterface.php<68><00>``<60>/X<>ƴ"src/AbstractNoUselessElseFixer.phpW <00>``W <00><><C8><EB><BE>src/DocBlock/DocBlock.php<68> <00>``<60> gux<75><78>src/DocBlock/TagComparator.phpo<00>``o<00>Zc(<28>src/DocBlock/Line.php:<00>``:<00><><05>src/DocBlock/Tag.php<68><00>``<60><00><><93><FD><9E>!src/DocBlock/ShortDescription.php<00>``<00><>src/DocBlock/Annotation.phpS<00>``S<00>'w<05>)src/AbstractLinesBeforeNamespaceFixer.phpA<00>``A<00>yKM<4B>=src/FixerConfiguration/FixerConfigurationResolverRootless.php!<00>``!<0F>L9<4C>0src/FixerConfiguration/DeprecatedFixerOption.php<68><00>``<60><00><>I<F8><49>&src/FixerConfiguration/FixerOption.php<68><00>``<60>J-<1F><>-src/FixerConfiguration/FixerOptionBuilder.php:<00>``:=.<2E><16>>src/FixerConfiguration/FixerConfigurationResolverInterface.php<68><00>``<60><00><><F7>#<23>/src/FixerConfiguration/FixerOptionInterface.php\<00>``\j,<2C><><89>5src/FixerConfiguration/FixerConfigurationResolver.php<68><00>``<60>m<>$<24><>4src/FixerConfiguration/AliasedFixerOptionBuilder.php<68><00>``<60>"PAl<41>-src/FixerConfiguration/AllowedValueSubset.php<68><00>``<60><00>8<1C><>9src/FixerConfiguration/DeprecatedFixerOptionInterface.php<68><00>``<60>$<24><><C6><F5>8src/FixerConfiguration/InvalidOptionsForEnvException.php<68><00>``<60><00><>R<>-src/FixerConfiguration/AliasedFixerOption.php<68><00>``<60><00><>src/Differ/NullDiffer.php<68><00>``<60><00><>D<01>src/Differ/UnifiedDiffer.php<68><00>``<60>/<2F>1<F5><31>src/Differ/FullDiffer.php<00>``A<>m<A7><6D>&src/Differ/SebastianBergmannDiffer.php=<00>``=<00><>q<16>#src/Differ/DiffConsoleFormatter.php<68><00>``<60><00><><0E><>+src/Differ/SebastianBergmannShortDiffer.phpb<00>``bZ!<21>5<A8>src/Differ/DifferInterface.php|<00>``|<00>h<D9>B<C4>src/Event/Event.php<68><00>``<60><00>m<A3>ݴsrc/ToolInfoInterface.phpB<00>``B<00>-<2D>W<97>src/ConfigInterface.phpg<00>``g<00><>'1<>src/PharCheckerInterface.php<68><00>``<60>ѝ<03><>src/ToolInfo.php<68><00>``<60>|<7C><><19> src/AbstractAlignFixerHelper.php<68><00>``<60><00>:<3A>u<93>src/Finder.php<68><00>``<60>+8<><38>src/WordMatcher.php<68><00>``<60>x<><78><AB><FF>src/AbstractFopenFlagFixer.php<68><00>``<60>'src/StdinFileInfo.php#<00>``#`<60>)D<>src/Error/ErrorsManager.php<68><00>``<60><00><>src/Error/Error.php0<00>``0<00>|<7C>شsrc/FileRemoval.php1<00>``1<00>7<06><>src/Config.php<68> <00>``<60> <13><><10> src/AbstractPhpdocTypesFixer.php<68><00>``<60>-<1E><>src/WhitespacesFixerConfig.php<68><00>``<60><00>B<1B>&src/AbstractFunctionReferenceFixer.php<68><00>``<60><17>H<B6><48>2src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php<68><00>``<60> ^E<><45>2src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.phpY <00>``Y <00>nA<6E>7src/Fixer/Whitespace/MethodChainingIndentationFixer.phpH<00>``H<00><>Y<E9><59>2src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php<68><00>``<60><00><>Fi<46>-src/Fixer/Whitespace/IndentationTypeFixer.php
<00>``
(`W<>6src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php<68><00>``<60>1<>7src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php/<00>``/<00><>$<24><>5src/Fixer/Whitespace/CompactNullableTypehintFixer.php<68><00>``<60>ٸpB<70>:src/Fixer/Whitespace/NoExtraConsecutiveBlankLinesFixer.php;<00>``;S<><53>д/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php<68>!<00>``<60>!eF<65>0<87>(src/Fixer/Whitespace/LineEndingFixer.php<68><00>``<60><00><>
<96><B4>5src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php<68><00>``<60><00>t<C5>δ0src/Fixer/Whitespace/HeredocIndentationFixer.phpp<00>``pB<><42><1E>.src/Fixer/Whitespace/ArrayIndentationFixer.phph<00>``ha<><61><BA><BB>%src/Fixer/Strict/StrictParamFixer.php<68> <00>``<60> <00>d‹<64>*src/Fixer/Strict/StrictComparisonFixer.phpt<00>``t<00><>c<CE><63>,src/Fixer/Strict/DeclareStrictTypesFixer.phpw
<00>``w
Rw<52><0F>>src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.phpW#<00>``W#<00><>e<>Gsrc/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php<68><00>``<60>mE/<2F>Csrc/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php%<00>``%<00>w<F7><0E>>src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php
<00>``
G<>:s<>#src/Fixer/DefinedFixerInterface.php<68><00>``<60><00><>ܴ/src/Fixer/Import/GlobalNamespaceImportFixer.php<68>=<00>``<60>=<00><><90><BD><94>)src/Fixer/Import/NoUnusedImportsFixer.php<68><00>``<60><00><>R9<52>3src/Fixer/Import/FullyQualifiedStrictTypesFixer.php! <00>``! <00>&Q<>%src/Fixer/Import/GroupImportFixer.phpP<00>``POr<4F>><3E>.src/Fixer/Import/NoLeadingImportSlashFixer.php~<00>``~02ۯ<32>2src/Fixer/Import/SingleImportPerStatementFixer.php<68><00>``<60>|(<<3C>(src/Fixer/Import/OrderedImportsFixer.php<68>)<00>``<60>)|'.<2E>0src/Fixer/Import/SingleLineAfterImportsFixer.phpJ <00>``J K[}<7D><>&src/Fixer/PhpTag/NoClosingTagFixer.php<68><00>``<60> +<07>2src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php<68><00>``<60>{<05><><97>'src/Fixer/PhpTag/EchoTagSyntaxFixer.php<68><00>``<60>My<4D>Ǵ2src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php<<00>``<<00><><07><>(src/Fixer/PhpTag/NoShortEchoTagFixer.php<68><00>``<60>\<5C><>|<7C>(src/Fixer/PhpTag/FullOpeningTagFixer.phpL<00>``L<00>E<BB><45><FF>*src/Fixer/ListNotation/ListSyntaxFixer.php<68> <00>``<60> <00>r<8E><72><C6>6src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php<68> <00>``<60> <00><18>4<CB>7src/Fixer/ReturnNotation/BlankLineBeforeReturnFixer.php<00>``<00><47>2src/Fixer/ReturnNotation/ReturnAssignmentFixer.phpp<00>``p<00>.<2E><><B1>1src/Fixer/ReturnNotation/NoUselessReturnFixer.phpp<00>``pR|х<>-src/Fixer/Comment/HashToSlashCommentFixer.php<68><00>``<60>M<>Z`<60>)src/Fixer/Comment/NoEmptyCommentFixer.php"
<00>``"
<00><><90>h<99>9src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php<00>``Q<02><>8src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php<68><00>``<60><00><>Ś<D5>*src/Fixer/Comment/CommentToPhpdocFixer.phpb<00>``b<00><B9>1src/Fixer/Comment/SingleLineCommentStyleFixer.phpE <00>``E ݎ<>h<95>(src/Fixer/Comment/HeaderCommentFixer.php<68>'<00>``<60>'<00>h+<2B><>3src/Fixer/ConfigurationDefinitionFixerInterface.php<00>``M<>#src/Fixer/Alias/EregToPregFixer.php<68>
<00>``<60>
<00>^<5E><><CE>+src/Fixer/Alias/RandomApiMigrationFixer.php<00>``)<29>3<93><33>"src/Fixer/Alias/ArrayPushFixer.phpu<00>``u<00>f<97><66><B5>)src/Fixer/Alias/NoAliasFunctionsFixer.php<68><00>``<60><00>+g<><67>)src/Fixer/Alias/NoMixedEchoPrintFixer.php<68>
<00>``<60>
<00><>J<>&src/Fixer/Alias/SetTypeToCastFixer.php<68><00>``<60><00>LA<4C><41>,src/Fixer/Alias/PowToExponentiationFixer.php<00>``<12> <09>'src/Fixer/Alias/MbStrFunctionsFixer.php
<00>``
<00><01>a<D0>5src/Fixer/Alias/NoAliasLanguageConstructCallFixer.phpU<00>``Uy`<60>8<D9>,src/Fixer/Alias/BacktickToShellExecFixer.php. <00>``. F<>=<1D>&src/Fixer/PhpUnit/PhpUnitMockFixer.phpN <00>``N <00><>+<2B><>,src/Fixer/PhpUnit/PhpUnitNamespacedFixer.phpd<00>``dZI<5A>3<D8>5src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php?<00>``?<00>^V(<28><src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php<68><00>``<60>p<>=<3D>0src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.phpH&<00>``H&<00><>u<A3><75>;src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php<68>0<00>``<60>0<00>
H<85><B4>9src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.phpg<00>``gt<><74>b<E6>/src/Fixer/PhpUnit/PhpUnitOrderedCoversFixer.phpr<00>``r<00>+r<><72>+src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php<68><00>``<60>)5<o<>9src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php<68><00>``<60>r<><72>Ӵ.src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php<00>``x<><78><<3C>*src/Fixer/PhpUnit/PhpUnitTargetVersion.php<68><00>``<60><00><>+src/Fixer/PhpUnit/PhpUnitConstructFixer.phpr<00>``r<><E1AEB8>-src/Fixer/PhpUnit/PhpUnitExpectationFixer.php<68><00>``<60><00><><05><>9src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php]
<00>``]
Wm<57>Դ0src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php!<00>``!%T%<25>0src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php<68>'<00>``<60>'<00>~]<5D>(src/Fixer/PhpUnit/PhpUnitStrictFixer.php<68> <00>``<60> 0<><30><B0><8B>/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.phpw<00>``w<02>g<>src/Fixer/FixerInterface.php<68><00>``<60>eus`<60>(src/Fixer/ConfigurableFixerInterface.php<00>``<00><><BF><C5>:src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php>
<00>``>
<00><><F9>O<D2>>src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.phpX<00>``X<00>Y<BC>'<27>+src/Fixer/LanguageConstruct/IsNullFixer.php<68><00>``<60><00>pN<70><4E>7src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.phpi<00>``ix<>T´6src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.phpE<00>``E<00>;<3B>7<D8>=src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php<68><00>``<60><00>Z<DB>#<23>5src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php
<00>``
t'<27><><A8>7src/Fixer/LanguageConstruct/FunctionToConstantFixer.php<68><00>``<60>G<><47><1B>=src/Fixer/LanguageConstruct/SilencedDeprecationErrorFixer.php<00>``Q<><<3C><>=src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php<68> <00>``<60> <00><6A>=src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php<68> <00>``<60> <00><13>c<E5>0src/Fixer/LanguageConstruct/DirConstantFixer.php4 <00>``4 1<>/@<40>'src/Fixer/Basic/PsrAutoloadingFixer.php9<00>``9<00>|<7C>*<2A>src/Fixer/Basic/Psr4Fixer.phpO<00>``OZ<>B<>.src/Fixer/Basic/NonPrintableCharacterFixer.php<00>``_<1E>'<27>src/Fixer/Basic/Psr0Fixer.php<68><00>``<60><00><> <20><>src/Fixer/Basic/BracesFixer.php5a<00>``5a<00><><D7>9<FA>!src/Fixer/Basic/EncodingFixer.php;<00>``;xAШ<41>0src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php<68>
<00>``<60>
U<>J5<4A>-src/Fixer/Semicolon/NoEmptyStatementFixer.phpD<00>``D<00>}<7D>޴Csrc/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php,<00>``,a<><61>ܴ6src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php<68><00>``<60><00>QS<>Bsrc/Fixer/Semicolon/NoMultilineWhitespaceBeforeSemicolonsFixer.php <00>`` )<29><>%<25>@src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php.<00>``.<00>3<E9>)<29>,src/Fixer/WhitespacesAwareFixerInterface.php<68><00>``<60>g<><67>s<B2>&src/Fixer/DeprecatedFixerInterface.php<68><00>``<60>=r<>T<94><src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php<00>``X)<29>Asrc/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php<68><00>``<60>$<24>4src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php<68><00>``<60><00>0src/Fixer/ArrayNotation/TrimArraySpacesFixer.php<68><00>``<60><00>5<C8><35><BA>>src/Fixer/ArrayNotation/TrailingCommaInMultilineArrayFixer.php <00>`` v@Lj<4C>?src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php<68> <00>``<60> -
<DA>ƴ,src/Fixer/ArrayNotation/ArraySyntaxFixer.phpX <00>``X $<24><>+<2B>Gsrc/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php<68><00>``<60><00>m;<3B><>,src/Fixer/AbstractIncrementOperatorFixer.php<68><00>``<60><00><>0<1E><src/Fixer/ConstantNotation/NativeConstantInvocationFixer.phpV<00>``V<00><><9C><FD><AC>"src/Fixer/AbstractPhpUnitFixer.phpC<00>``C6<><36><8A><CA>3src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php<68><00>``<60>*<2A>Ց<ED>$src/Fixer/Phpdoc/PhpdocTrimFixer.phpo<00>``o<00><13>3src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php<68><00>``<60>Lc<4C><63><AB>*src/Fixer/Phpdoc/PhpdocSeparationFixer.php]
<00>``]
t<>j<E6><6A>1src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php<68>*<00>``<60>*<00>|<7C>޴)src/Fixer/Phpdoc/PhpdocInlineTagFixer.php<68><00>``<60>=<3D><>%<25>%src/Fixer/Phpdoc/PhpdocOrderFixer.php3 <00>``3 8`<00>'src/Fixer/Phpdoc/NoEmptyPhpdocFixer.phpu<00>``u<00>>pô)src/Fixer/Phpdoc/PhpdocNoPackageFixer.php<68><00>``<60><00>9<EB><39><B5>*src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php<68><00>``<60><00>.Ir<49>9src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php<68><00>``<60>P<> <0B><>'src/Fixer/Phpdoc/PhpdocSummaryFixer.php3<00>``3<02>}x<>0src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php`<00>```aO<61><4F>%src/Fixer/Phpdoc/PhpdocTypesFixer.php<68><00>``<60>Xش)src/Fixer/Phpdoc/PhpdocTagCasingFixer.php<68><00>``<60>Aٟ9<D99F>*src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php<68><00>``<60>u2YB<59>&src/Fixer/Phpdoc/PhpdocIndentFixer.php/<00>``/1,]^<5E>%src/Fixer/Phpdoc/PhpdocAlignFixer.php<68><00>``<60>z!:<02>1src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php<68><00>``<60><00><1B>(src/Fixer/Phpdoc/PhpdocLineSpanFixer.phpP <00>``P <00>ż"<22>4src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.phpv<00>``v7<><37><13>'src/Fixer/Phpdoc/PhpdocTagTypeFixer.php1<00>``1<05><><F6><BC>&src/Fixer/Phpdoc/PhpdocScalarFixer.php<00>``<00><>Ͽ<FD>7src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.phpB<00>``B<00>@<40><19>(src/Fixer/Phpdoc/PhpdocNoAccessFixer.php<68><00>``<60> lH<1C>-src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php<68><00>``<60><00><58>,src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php<68><00>``<60><15><><CE><E4>)src/Fixer/Phpdoc/PhpdocToCommentFixer.php%<00>``%<07><16><>3src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php <00>`` %<25>e<EE>/src/Fixer/Phpdoc/AlignMultilineCommentFixer.phpI <00>``I <1E><>O<D2>4src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php<68> <00>``<60> <00><><07><>9src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php<68><00>``<60><00><><A6>]<5D>.src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.phpb <00>``b D<>L<89><4C>Bsrc/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php<68> <00>``<60> r^Q<>,src/Fixer/Operator/LogicalOperatorsFixer.phpQ<00>``Q<00>h<F0><68><B0>'src/Fixer/Operator/ConcatSpaceFixer.php<68> <00>``<60> <<3C>%w<>0src/Fixer/Operator/NotOperatorWithSpaceFixer.php,<00>``,G<>Ʀ<E3>)src/Fixer/Operator/NewWithBracesFixer.php<68> <00>``<60> <00>b<A0>˴-src/Fixer/Operator/OperatorLinebreakFixer.php<00>``<00>><1B>/src/Fixer/Operator/UnaryOperatorSpacesFixer.php<68><00>``<60><00><1A><>0src/Fixer/Operator/StandardizeIncrementFixer.php<00>``<00><><E7>Ĵ1src/Fixer/Operator/TernaryOperatorSpacesFixer.php<68> <00>``<60> <00><>G<CE><47>-src/Fixer/Operator/AlignEqualsFixerHelper.php<68><00>``<60>4IUR<55>*src/Fixer/Operator/IncrementStyleFixer.php<68> <00>``<60> <00>
<A1>˴9src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php<00>``<1F><>}<7D>0src/Fixer/Operator/StandardizeNotEqualsFixer.php5<00>``5<47><CEAB>3src/Fixer/Operator/TernaryToNullCoalescingFixer.php*<00>``*oPN#<23>0src/Fixer/Operator/BinaryOperatorSpacesFixer.phpfC<00>``fCy<>s <09>;src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php<68><00>``<60>t<16>˴2src/Fixer/Operator/AlignDoubleArrowFixerHelper.phpg <00>``g L<><4C>=<3D>(src/Fixer/Operator/PreIncrementFixer.php<68><00>``<60><1A><><BF><A9>2src/Fixer/Operator/TernaryToElvisOperatorFixer.php<68><00>``<60><00>'ڴ-src/Fixer/ClassNotation/SelfAccessorFixer.php<68><00>``<60><00><>6src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.phpe <00>``e Slyt<79>.src/Fixer/ClassNotation/OrderedTraitsFixer.php <00>`` <08>j<>2src/Fixer/ClassNotation/OrderedInterfacesFixer.php<68><00>``<60>36<33><36>3src/Fixer/ClassNotation/ProtectedToPrivateFixer.phpi<00>``isj_<6A><5F>3src/Fixer/ClassNotation/VisibilityRequiredFixer.php<68><00>``<60>,<2C><>A<EB>1src/Fixer/ClassNotation/MethodSeparationFixer.php<00>``Ĵ <20><>3src/Fixer/ClassNotation/SelfStaticAccessorFixer.php<68> <00>``<60> <00><>><3E><>>src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php<68><00>``<60> <07>δ5src/Fixer/ClassNotation/OrderedClassElementsFixer.php<68>(<00>``<60>(<00><><{<7B>0src/Fixer/ClassNotation/ClassDefinitionFixer.php<68>)<00>``<60>)<00><>f<D8><66>2src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php<68><00>``<60>T<>y
<B4>?src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php<68><00>``<60><00>Y?t<>=src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php<68><00>``<60>n<><6E>ʹ+src/Fixer/ClassNotation/FinalClassFixer.phpR<00>``R<00><30>:src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php/+<00>``/+7<><37>/<2F>2src/Fixer/ClassNotation/FinalStaticAccessFixer.phpK<00>``K8<><B3><7F>>src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php<68><00>``<60>`k<><08>3src/Fixer/ClassNotation/FinalInternalClassFixer.phpX<00>``XÈ<>f<9B>Bsrc/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php<68> <00>``<60> <00>B'&<26>/src/Fixer/ClassUsage/DateTimeImmutableFixer.php<68> <00>``<60> <00><>x-<2D>>src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php<68><00>``<60>a<><61>f<DD>0src/Fixer/StringNotation/NoBinaryStringFixer.php<68><00>``<60><00>9t<06>?src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php<68><00>``<60><10><13><>2src/Fixer/StringNotation/StringLineEndingFixer.php9<00>``9k u<>-src/Fixer/StringNotation/SingleQuoteFixer.php,<00>``,-<2D>&<26>;src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php<00>``1<13><><FD>1src/Fixer/StringNotation/HeredocToNowdocFixer.phps<00>``s<00>Ye<59><65>8src/Fixer/StringNotation/ExplicitStringVariableFixer.php<00>``<00><17><06>0src/Fixer/FunctionNotation/StaticLambdaFixer.php<68> <00>``<60> <00>z<FB>̴Nsrc/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php<68> <00>``<60> ),<2C><06>/src/Fixer/FunctionNotation/ImplodeCallFixer.php[ <00>``[ <00>Y,8<>=src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php <00>`` <00>:9´5src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php<68> <00>``<60> <00>ɹ<F1><C9B9>8src/Fixer/FunctionNotation/CombineNestedDirnameFixer.phpD<00>``Dʹ蓴.src/Fixer/FunctionNotation/VoidReturnFixer.phpH<00>``H<00><># <0B>3src/Fixer/FunctionNotation/SingleLineThrowFixer.php<68>
<00>``<60>
^^<5E>4<8B>9src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php
<00>``
<00>NQ<4E><51>7src/Fixer/FunctionNotation/RegularCallableCallFixer.php<68><00>``<60><00>A_@<40>5src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php<00>``<00>n<B9>ɴ4src/Fixer/FunctionNotation/NoUselessSprintfFixer.php <00>`` <05>9<13>7src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.phpQ<00>``Q<00><00>*<2A><src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php6<00>``6<00> <09>Z<DE>7src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php<68>-<00>``<60>-.<16>_<CE>6src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php<68><00>``<60><00>y^o<>.src/Fixer/FunctionNotation/FopenFlagsFixer.php0 <00>``0 <00><><A5>+<2B>9src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php<68><00>``<60><10>'<27>7src/Fixer/FunctionNotation/FunctionDeclarationFixer.php<68><00>``<60><00><>I<DF><49>2src/Fixer/FunctionNotation/FopenFlagOrderFixer.phpW<00>``W<00>d<E2><64><B7>Esrc/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php<68><00>``<60><00>T<DE>)<29>*src/Fixer/Naming/NoHomoglyphNamesFixer.php<68> <00>``<60> {<7B>˴-src/Fixer/Casing/MagicConstantCasingFixer.php><00>``><00><>.src/Fixer/Casing/NativeFunctionCasingFixer.php<68><00>``<60>hz3)<29>&src/Fixer/Casing/ConstantCaseFixer.php<68> <00>``<60> u;<3B>[<5B>,src/Fixer/Casing/LowercaseConstantsFixer.php<00>``<~@Ѵ+src/Fixer/Casing/LowercaseKeywordsFixer.phpM<00>``M <04><><A2>+src/Fixer/Casing/MagicMethodCasingFixer.php<68><00>``<60>C}<7D>V<9F>2src/Fixer/Casing/LowercaseStaticReferenceFixer.php<68><00>``<60><00><>B<E4><42>=src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php6 <00>``6 <00><>3<><src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php <00>`` <00><>|<01>3src/Fixer/NamespaceNotation/CleanNamespaceFixer.phpW<00>``W`<60><>!<21>Asrc/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.phpA<00>``A<00><>mJ<6D>Csrc/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php<68><00>``<60><00>4$<24>@src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php<68><00>``<60><00><>u<>-src/Fixer/CastNotation/LowercaseCastFixer.php9<00>``9ϯ"<22><>*src/Fixer/CastNotation/CastSpacesFixer.phpE<00>``Ed<><64><B3><FA>+src/Fixer/CastNotation/NoUnsetCastFixer.php<68><00>``<60><00> ) <0C>/src/Fixer/CastNotation/NoShortBoolCastFixer.php<68><00>``<60><00><><FA>'<27>/src/Fixer/CastNotation/ShortScalarCastFixer.php<68><00>``<60><11><>t<98>5src/Fixer/CastNotation/ModernizeTypesCastingFixer.php<68> <00>``<60> m<><6D><96><AA>9src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php<00>``<00>˼<86><CBBC>+src/Fixer/ControlStructure/IncludeFixer.php<68> <00>``<60> j<>}<7D>9src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.phpV <00>``V '<27><>|<7C>1src/Fixer/ControlStructure/NoUselessElseFixer.php<68><00>``<60>J4=.<2E>7src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php<68><00>``<60>n<>Y<07>3src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php<68><00>``<60>=<3D><><AB><89>@src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php<68><00>``<60>'<27>,<2C>2src/Fixer/ControlStructure/NoBreakCommentFixer.phpV!<00>``V!7[<5B><>>src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php<68><00>``<60>R߿ݴ*src/Fixer/ControlStructure/ElseifFixer.phpF<00>``F<00><>'k<>=src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php<68><00>``<60>Y<><59>N<CA>-src/Fixer/ControlStructure/YodaStyleFixer.php<68>5<00>``<60>5<00>em<65>6src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php<68> <00>``<60> <00>7src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php<68><00>``<60><00><>pd<70>src/PregException.phpg<00>``g<E<><45>*src/Indicator/PhpUnitTestCaseIndicator.php<00>``<00><0E><05>Bsrc/ConfigurationException/RequiredFixerConfigurationException.php<68><00>``<60><00><><8B><03>Gsrc/ConfigurationException/InvalidForEnvFixerConfigurationException.php<68><00>``<60>wS<77>δAsrc/ConfigurationException/InvalidFixerConfigurationException.php5<00>``5{<7B>I<15><src/ConfigurationException/InvalidConfigurationException.php<68><00>``<60>#s<>k<D6> src/Utils.phpq<00>``q"o<>h<8C>src/Tokenizer/Token.php<68>"<00>``<60>"<00>m[˴0src/Tokenizer/Resolver/TypeShortNameResolver.php\<00>``\<00>-<2D>b<CF>&src/Tokenizer/TransformerInterface.phpP<00>``Pv<>R<BC><52> src/Tokenizer/TokensAnalyzer.php<68>5<00>``<60>5O<7F>L<9B>:src/Tokenizer/Generator/NamespacedStringTokenGenerator.php<68><00>``<60>݊j<>src/Tokenizer/CodeHasher.php<68><00>``<60>V<>J<E2><4A>:src/Tokenizer/Transformer/WhitespacyCommentTransformer.php<68><00>``<60>B"Ѵ5src/Tokenizer/Transformer/NullableTypeTransformer.php<68><00>``<60><00><><A7><C9><E8>3src/Tokenizer/Transformer/CurlyBraceTransformer.php|<00>``|<10>b<AF><62>,src/Tokenizer/Transformer/UseTransformer.php<68><00>``<60><00>x~޴6src/Tokenizer/Transformer/ClassConstantTransformer.php!<00>``!uG<75>W<C4>6src/Tokenizer/Transformer/NamedArgumentTransformer.php#<00>``#<0F>T<16>=src/Tokenizer/Transformer/ConstructorPromotionTransformer.php <00>`` <00><><14><>6src/Tokenizer/Transformer/ArrayTypehintTransformer.php<68><00>``<60><00>R <02>6src/Tokenizer/Transformer/NameQualifiedTransformer.phpF<00>``F_>ٴ2src/Tokenizer/Transformer/AttributeTransformer.php4<00>``4V<><56><BB><8E>:src/Tokenizer/Transformer/NamespaceOperatorTransformer.php<68><00>``<60>P<1A><><BA>/src/Tokenizer/Transformer/ImportTransformer.php0<00>``0i<><69><15>2src/Tokenizer/Transformer/TypeColonTransformer.php<68><00>``<60>}<7D>0n<30>@src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php<68><00>``<60>rSH[<5B>8src/Tokenizer/Transformer/TypeAlternationTransformer.php<00>``@<40><>G<AA>2src/Tokenizer/Transformer/ReturnRefTransformer.php<68><00>``<60><00>4<99>δ4src/Tokenizer/Transformer/SquareBraceTransformer.php<68> <00>``<60> <00>k셴,src/Tokenizer/Analyzer/ArgumentsAnalyzer.php<68>
<00>``<60>
<00><><15>+src/Tokenizer/Analyzer/CommentsAnalyzer.php<68><00>``<60><00><> ´,src/Tokenizer/Analyzer/GotoLabelAnalyzer.phpC<00>``C|L$"<22>,src/Tokenizer/Analyzer/ReferenceAnalyzer.php<68><00>``<60><00><>_<94><5F>)src/Tokenizer/Analyzer/BlocksAnalyzer.php!<00>``!<00><>=<3D><>-src/Tokenizer/Analyzer/NamespacesAnalyzer.php<68><00>``<60>b<><62>Ĵ.src/Tokenizer/Analyzer/WhitespacesAnalyzer.php<68><00>``<60>Ë<>д)src/Tokenizer/Analyzer/ClassyAnalyzer.php<00>``<00>ֺ<>0src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php<00>``<05>)src/Tokenizer/Analyzer/SwitchAnalyzer.php<
<00>``<
s 6<>>src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php<68><00>``<60>`9<>8src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php<68><00>``<60><00>ˆ<C4><CB86>2src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php <00>`` <00>d<02>4src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.phpA<00>``A<00>1WX<57>5src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php <00>`` <00>7<C2><37><97>0src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php<68><00>``<60>],D <0C>0src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php<00>``'<27><><82>,src/Tokenizer/Analyzer/FunctionsAnalyzer.php!<00>``!EwṴsrc/Tokenizer/Transformers.php<68><00>``<60>-<2D><>ܴsrc/Tokenizer/Tokens.php<68>Z<00>``<60>Z<00><>
M<B4>%src/Tokenizer/AbstractTransformer.phpv<00>``v'0m<30>src/Tokenizer/CT.php<68><00>``<60><00>[Q<>src/AbstractFixer.php<68><00>``<60>&<26><04>,src/AbstractPhpdocToTypeDeclarationFixer.php<68><00>``<60><00>U<9B>شsrc/FileReader.php<00>``<0E>1<>src/RuleSet/RuleSet.php'<00>``'/Du><3E>+src/RuleSet/RuleSetDescriptionInterface.php<00>``<00><><8F><86><AF> src/RuleSet/RuleSetInterface.phps<00>``s<00>4N<>&src/RuleSet/Sets/PHP70MigrationSet.php~<00>``~;<3B><>ϴ/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php<68><00>``<60><00><> <0C>/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php<68><00>``<60><><D28D>/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php<68><00>``<60><00><>I<90><49>/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php<68><00>``<60><00><08><><A1>&src/RuleSet/Sets/PHP54MigrationSet.phpf<00>``f<00><1B><1A>&src/RuleSet/Sets/PHP74MigrationSet.php<68><00>``<60><00><><FE>1<DD>/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php<68><00>``<60> <0C>'5<>+src/RuleSet/Sets/PHP80MigrationRiskySet.php <00>`` N<><4E>"<22>"src/RuleSet/Sets/PSR12RiskySet.php<68><00>``<60><00><>>|<7C>src/RuleSet/Sets/SymfonySet.php<68><00>``<60>ݠ<17><>/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php<68><00>``<60>d;&<26>/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php<68><00>``<60>0Y<>&src/RuleSet/Sets/PHP56MigrationSet.phpX<00>``X%<25>MH<4D>/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php<68><00>``<60>*^<5E><>+src/RuleSet/Sets/PHP71MigrationRiskySet.phpz<00>``z<00><1A>src/RuleSet/Sets/PSR1Set.php|<00>``|<00>5<C0>*<2A>"src/RuleSet/Sets/PhpCsFixerSet.php<68><00>``<60>"<22>+src/RuleSet/Sets/PHP74MigrationRiskySet.php<68><00>``<60> L<><15>/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php<68><00>``<60>ȑ<><C891><9D>/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php<68><00>``<60>ߴ/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php<68><00>``<60>Ő<><C590><91>/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php<68><00>``<60>z!S<><53>/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php<68><00>``<60>k<><6B>%<25>&src/RuleSet/Sets/PHP71MigrationSet.php<68><00>``<60><00>3<03><>*src/RuleSet/Sets/DoctrineAnnotationSet.phpE<00>``E<00><>a<81><61>+src/RuleSet/Sets/PHP70MigrationRiskySet.php[<00>``[١4B<34>+src/RuleSet/Sets/PHP56MigrationRiskySet.phpc<00>``c><3E>4<>src/RuleSet/Sets/PSR2Set.php<68><00>``<60>v:<3A><><9A>&src/RuleSet/Sets/PHP73MigrationSet.php3<00>``3<00><><F0><83><80>$src/RuleSet/Sets/SymfonyRiskySet.php<68><00>``<60>@wj<77><6A>'src/RuleSet/Sets/PhpCsFixerRiskySet.phpx<00>``xQLa<4C>/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php<68><00>``<60><00>f<><66>src/RuleSet/Sets/PSR12Set.php<68><00>``<60><00><> ?<3F>&src/RuleSet/Sets/PHP80MigrationSet.php<68><00>``<60>-c_<63><5F>src/RuleSet/RuleSets.phpt<00>``t<00>.<2E>H<ED>*src/RuleSet/AbstractRuleSetDescription.php<68><00>``<60>9<><39><E1><DC> src/Cache/DirectoryInterface.php<68><00>``<60><00>F<D0>d<92>src/Cache/FileHandler.php<68><00>``<60><00><0E>̴src/Cache/CacheInterface.php<00>``'뭴src/Cache/Directory.phpP<00>``P<00><><85>T<AC>"src/Cache/FileHandlerInterface.php<68><00>``<60><00><><A5>h<EE>src/Cache/Cache.php*<00>``*o<><6F>ܴsrc/Cache/Signature.php{<00>``{#R<><52><98> src/Cache/SignatureInterface.php4<00>``4<00>J<>src/Cache/FileCacheManager.php<68><00>``<60>l<>}<7D><>#src/Cache/CacheManagerInterface.php<68><00>``<60><00>D<08><>src/Cache/NullCacheManager.php<68><00>``<60><00>4n<>ci-integration.sh<73><00>``<60>|U<>{<7B>(vendor/symfony/filesystem/Filesystem.php;<00>``;#A<><41><93>)vendor/symfony/filesystem/LockHandler.php;<00>``;<00>f$<06><vendor/symfony/filesystem/Exception/IOExceptionInterface.php<68><00>``<60>j<>wM<77>:vendor/symfony/filesystem/Exception/ExceptionInterface.phpi<00>``i$ <20><><FF>3vendor/symfony/filesystem/Exception/IOException.php<68><00>``<60><00>\5<><35>=vendor/symfony/filesystem/Exception/FileNotFoundException.php<68><00>``<60><00><>9`<60>vendor/symfony/finder/Glob.php<68><00>``<60>U)j<>%vendor/symfony/finder/SplFileInfo.php<00>``<00><00><><ED>5vendor/symfony/finder/Comparator/NumberComparator.php<68><00>``<60><00>ڡ3<DAA1>3vendor/symfony/finder/Comparator/DateComparator.php#<00>``#<16>δ/vendor/symfony/finder/Comparator/Comparator.php<68><00>``<60><00><><9E><BB><83>:vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php`<00>```!<21>ky<6B>1vendor/symfony/finder/Iterator/FilterIterator.php<68><00>``<60> <1D><><9C>=vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php
<00>``
<00><>ƺ<D9>9vendor/symfony/finder/Iterator/FilenameFilterIterator.phpr<00>``rtu<>;vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php<68><00>``<60><02>۴Avendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php<68><00>``<60>f<19>_<DB>=vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php= <00>``= Y<><59>9vendor/symfony/finder/Iterator/FileTypeFilterIterator.phpZ<00>``Z(&<26><>:vendor/symfony/finder/Iterator/DateRangeFilterIterator.phps<00>``s=<3D><>x<B5>7vendor/symfony/finder/Iterator/CustomFilterIterator.phpX<00>``XDVSB<53>5vendor/symfony/finder/Iterator/PathFilterIterator.php<68><00>``<60><00><><E2>F<FA><vendor/symfony/finder/Iterator/FilecontentFilterIterator.phpA<00>``A<00><>3vendor/symfony/finder/Iterator/SortableIterator.phpN<00>``N<00>%<25><> vendor/symfony/finder/Finder.php%"<00>``%"<00>uH<75><48>9vendor/symfony/finder/Exception/AccessDeniedException.php<68><00>``<60><00><>s<BE><73>6vendor/symfony/finder/Exception/ExceptionInterface.php<68><00>``<60>L<><4C>~<7E>&vendor/symfony/process/InputStream.php'<00>``'<00>X<B3>><3E>/vendor/symfony/process/Pipes/PipesInterface.phpm<00>``m<04><>u<8B>-vendor/symfony/process/Pipes/WindowsPipes.php0 <00>``0 <05>A<FA>.vendor/symfony/process/Pipes/AbstractPipes.php<68>
<00>``<60>
<00>ym<79>*vendor/symfony/process/Pipes/UnixPipes.php<68><00>``<60><00><><BA><8F><8A>%vendor/symfony/process/PhpProcess.php<68><00>``<60><00>x<15>=vendor/symfony/process/Exception/ProcessTimedOutException.php<00>``<><0E><>;vendor/symfony/process/Exception/ProcessFailedException.phpx<00>``x<00><>zy<7A>7vendor/symfony/process/Exception/ExceptionInterface.phpf<00>``f]<5D>>T<>5vendor/symfony/process/Exception/RuntimeException.php<68><00>``<60><00><1B>:<3A>3vendor/symfony/process/Exception/LogicException.php<68><00>``<60> <20><><B3><E3>=vendor/symfony/process/Exception/InvalidArgumentException.php<68><00>``<60><00><>+_<>'vendor/symfony/process/ProcessUtils.php:<00>``:<1E><><9D>)vendor/symfony/process/ProcessBuilder.php
<00>``
Vq<56>Ѵ.vendor/symfony/process/PhpExecutableFinder.php<68><00>``<60>*><3E><><B4>+vendor/symfony/process/ExecutableFinder.php<68><00>``<60><1F><>ô"vendor/symfony/process/Process.phpl<00>``l<00>0mU<6D>+vendor/symfony/polyfill-php70/bootstrap.phpw<00>``wb<14><>'vendor/symfony/polyfill-php70/Php70.php<68><00>``<60>=<3D>+<2B>Evendor/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php3<00>``3<00><>h;<3B>Avendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php/<00>``/|mʹ<vendor/symfony/polyfill-php70/Resources/stubs/ParseError.php*<00>``*<00><>@vendor/symfony/polyfill-php70/Resources/stubs/AssertionError.php.<00>``.&8<>y<FA>Xvendor/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php<68><00>``<60><00><>~<7E><>;vendor/symfony/polyfill-php70/Resources/stubs/TypeError.php)<00>``)<00><>O_<4F>7vendor/symfony/polyfill-php70/Resources/stubs/Error.php)<00>``)[k <09>&vendor/symfony/console/Application.phpQh<00>``Qh<00><><CA><FD><A6>>vendor/symfony/console/Formatter/OutputFormatterStyleStack.php;<00>``;%<25><><8D>9vendor/symfony/console/Formatter/OutputFormatterStyle.php<68><00>``<60><00>`*<17>4vendor/symfony/console/Formatter/OutputFormatter.php<68><00>``<60>:<3A><>n<D8>=vendor/symfony/console/Formatter/OutputFormatterInterface.php<68><00>``<60><00><><F2><F1><F1>Bvendor/symfony/console/Formatter/OutputFormatterStyleInterface.php<68><00>``<60><00><>G<>8vendor/symfony/console/Question/ConfirmationQuestion.php<68><00>``<60><00>d<ED>?<3F>,vendor/symfony/console/Question/Question.php
<00>``
N<><4E><92>2vendor/symfony/console/Question/ChoiceQuestion.phpB
<00>``B
<00><><8D>дDvendor/symfony/console/DependencyInjection/AddConsoleCommandPass.phpb <00>``b <><E8929C>#vendor/symfony/console/Terminal.php<68>
<00>``<60>
<00><>Ѵ0vendor/symfony/console/Output/BufferedOutput.php`<00>```<00><D3>(vendor/symfony/console/Output/Output.php<68> <00>``<60> 0p<08>/vendor/symfony/console/Output/ConsoleOutput.php<68><00>``<60>Sc<><63>8vendor/symfony/console/Output/ConsoleOutputInterface.php<68><00>``<60><00><><87>ʴ.vendor/symfony/console/Output/StreamOutput.php<00>``$<24><>W<B9>1vendor/symfony/console/Output/OutputInterface.php<68><00>``<60>n <0A>,vendor/symfony/console/Output/NullOutput.php<68><00>``<60><00><><AE>Z<8B>6vendor/symfony/console/Event/ConsoleExceptionEvent.php<68><00>``<60><00><>(<28><>4vendor/symfony/console/Event/ConsoleCommandEvent.php<68><00>``<60>!ȴ6vendor/symfony/console/Event/ConsoleTerminateEvent.phpz<00>``z<00>,<2C>L<EE>-vendor/symfony/console/Event/ConsoleEvent.php<68><00>``<60><00><1E>Ӵ2vendor/symfony/console/Event/ConsoleErrorEvent.phpb<00>``b<00>Mh<10>.vendor/symfony/console/Input/InputArgument.php <00>`` <00>;<3B><06>0vendor/symfony/console/Input/InputDefinition.php<68><00>``<60><00>qR<71><52>&vendor/symfony/console/Input/Input.phpG <00>``G <00><><F4><F9><E7>,vendor/symfony/console/Input/StringInput.phpW<00>``W}<7D><>j<CB>*vendor/symfony/console/Input/ArgvInput.php<68><00>``<60><00>N
ɴ/vendor/symfony/console/Input/InputInterface.php<68><00>``<60>rrg<72>,vendor/symfony/console/Input/InputOption.php <00>`` <18><><1B>4vendor/symfony/console/Input/InputAwareInterface.php<68><00>``<60><00>O<><4F>9vendor/symfony/console/Input/StreamableInputInterface.php<68><00>``<60><00><>B<D5><42>+vendor/symfony/console/Input/ArrayInput.php+ <00>``+ '<27><>ٴ=vendor/symfony/console/Exception/CommandNotFoundException.php<68><00>``<60>K*<2A>5<E2>;vendor/symfony/console/Exception/InvalidOptionException.php<68><00>``<60><13><>H<D7>7vendor/symfony/console/Exception/ExceptionInterface.phpf<00>``f<00>AB<41><42>5vendor/symfony/console/Exception/RuntimeException.php<68><00>``<60><00><>,6<>3vendor/symfony/console/Exception/LogicException.php<68><00>``<60><00>O\e<>=vendor/symfony/console/Exception/InvalidArgumentException.php<68><00>``<60><00>̽Z<CCBD>8vendor/symfony/console/Descriptor/MarkdownDescriptor.php<68><00>``<60><00>>4<><34><vendor/symfony/console/Descriptor/ApplicationDescription.php<68> <00>``<60> @?,״0vendor/symfony/console/Descriptor/Descriptor.phps<00>``scB<63>M<B7>4vendor/symfony/console/Descriptor/JsonDescriptor.php<68><00>``<60><00>S]R<>9vendor/symfony/console/Descriptor/DescriptorInterface.php<68><00>``<60><00>P~<7E><>4vendor/symfony/console/Descriptor/TextDescriptor.php"<00>``"O<>3vendor/symfony/console/Descriptor/XmlDescriptor.php <00>`` 4 δ.vendor/symfony/console/Command/HelpCommand.php<68><00>``<60><17><<3C><>.vendor/symfony/console/Command/ListCommand.php<00>``5<><35>-<2D>*vendor/symfony/console/Command/Command.php:!<00>``:!o%<25>0vendor/symfony/console/Command/LockableTrait.php2<00>``2N<><4E>ߴ/vendor/symfony/console/Tester/CommandTester.php<68><00>``<60>Uc<1F>3vendor/symfony/console/Tester/ApplicationTester.php) <00>``) <00><><81>X<F8>6vendor/symfony/console/Helper/DebugFormatterHelper.phpj<00>``jOG<4F> <0B>1vendor/symfony/console/Helper/HelperInterface.php<68><00>``<60><1F><><18>/vendor/symfony/console/Helper/ProcessHelper.php
<00>``
<00>O<B9><4F><DF>2vendor/symfony/console/Helper/InputAwareHelper.phpc<00>``c<06><><CC><F8>(vendor/symfony/console/Helper/Helper.phpk<00>``k<00>'颴'vendor/symfony/console/Helper/Table.php<68>-<00>``<60>-<00><><1E><>2vendor/symfony/console/Helper/DescriptorHelper.phpe<00>``e2<><32>_<CE>7vendor/symfony/console/Helper/SymfonyQuestionHelper.php <00>`` <00><><1F><>0vendor/symfony/console/Helper/TableSeparator.php<68><00>``<60><00><><BC><F5><CB>1vendor/symfony/console/Helper/FormatterHelper.phpD<00>``D+<2B><>L<E6>+vendor/symfony/console/Helper/HelperSet.phpf<00>``f<00>x<><78>,vendor/symfony/console/Helper/TableStyle.php+
<00>``+
8<><38>6<BA>+vendor/symfony/console/Helper/TableCell.phpv<00>``v<00>+<2B> <0C>3vendor/symfony/console/Helper/ProgressIndicator.phpD<00>``DJx<4A>F<F1>0vendor/symfony/console/Helper/QuestionHelper.php^%<00>``^%3P<33>h<D1>-vendor/symfony/console/Helper/ProgressBar.php9%<00>``9%<00><><82><01>/vendor/symfony/console/Style/StyleInterface.php<68><00>``<60><11><><02>-vendor/symfony/console/Style/SymfonyStyle.php\<00>``\<00><A2>,vendor/symfony/console/Style/OutputStyle.phpX<00>``X<00><07><><8F>/vendor/symfony/console/Logger/ConsoleLogger.php<68>
<00>``<60>
<10> Z<>(vendor/symfony/console/ConsoleEvents.php<00>``<00>'<27><><D1>?vendor/symfony/console/CommandLoader/ContainerCommandLoader.phpH<00>``H-<2D><>ߴ?vendor/symfony/console/CommandLoader/CommandLoaderInterface.phpG<00>``G?<3F><><96><8F>=vendor/symfony/console/CommandLoader/FactoryCommandLoader.php<68><00>``<60><00>m<FE><6D><9F>6vendor/symfony/console/EventListener/ErrorListener.php"<00>``"M^<5E> <09>%vendor/symfony/debug/ErrorHandler.php8H<00>``8Hw<>+<2B><>)vendor/symfony/debug/ExceptionHandler.php<68>M<00>``<60>M<00><>ۡ<F1>)vendor/symfony/debug/DebugClassLoader.php\+<00>``\+ow<6F>g<A8>Ivendor/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php <00>`` <06><>F<DE>Kvendor/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.phpO<00>``Oh<05>ѴMvendor/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php<68><00>``<60>Fd-<2D>Evendor/symfony/debug/FatalErrorHandler/FatalErrorHandlerInterface.php<00>``ĹBV<42>6vendor/symfony/debug/Exception/FatalErrorException.php.<00>``.<00>J0<4A>=vendor/symfony/debug/Exception/UndefinedFunctionException.php<68><00>``<60><00><>J<F1><4A>8vendor/symfony/debug/Exception/ContextErrorException.php<00>``6<><08><>7vendor/symfony/debug/Exception/OutOfMemoryException.php~<00>``~<00><>o<A8><6F>7vendor/symfony/debug/Exception/SilencedErrorContext.php(<00>``(<00>+l<><6C>3vendor/symfony/debug/Exception/FlattenException.phpn<00>``nw<><77>
<B4>6vendor/symfony/debug/Exception/FatalThrowableError.phpZ<00>``Z;<17><12>9vendor/symfony/debug/Exception/ClassNotFoundException.php<68><00>``<60>i<><69><89><E6>;vendor/symfony/debug/Exception/UndefinedMethodException.php<68><00>``<60>n<><6E>ش(vendor/symfony/debug/BufferingLogger.php`<00>```<00>Dm۴vendor/symfony/debug/Debug.php.<00>``.<00>B<82>;<3B>+vendor/symfony/polyfill-php72/bootstrap.phpu<00>``u<00><><A1>&<26>'vendor/symfony/polyfill-php72/Php72.php<68><00>``<60><00><><EF>W<F7>+vendor/symfony/polyfill-ctype/bootstrap.php<68><00>``<60>|p:<3A>'vendor/symfony/polyfill-ctype/Ctype.phpH <00>``H <00><><B3>ݴ.vendor/symfony/polyfill-mbstring/bootstrap.php<00>``<11>J<FE><4A>-vendor/symfony/polyfill-mbstring/Mbstring.php<68>G<00>``<60>G̴ֽ@vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php<68>U<00>``<60>U`<60>8Q<38>Fvendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php<68><00>``<60><00>y_<79><5F>@vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php<68>T<00>``<60>T<00>2<DF>?<3F>Dvendor/symfony/polyfill-mbstring/Resources/mb_convert_variables.php8?<00>``?<00>3vendor/symfony/options-resolver/OptionsResolver.php<68>:<00>``<60>:<00>!<21>x<AB>Evendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php<00>``<00><><8F>ܴ+vendor/symfony/options-resolver/Options.php{<00>``{<00>|<7C><><B7>Evendor/symfony/options-resolver/Exception/MissingOptionsException.php<68><00>``<60>=<3D><><BC><BD>=vendor/symfony/options-resolver/Exception/AccessException.php<68><00>``<60><00>5<13>@vendor/symfony/options-resolver/Exception/ExceptionInterface.phpn<00>``n<00><02>y<F8>Gvendor/symfony/options-resolver/Exception/OptionDefinitionException.php<68><00>``<60><00>@4<><34>Fvendor/symfony/options-resolver/Exception/NoConfigurationException.php<68><00>``<60>j<><6A>E<AE>Gvendor/symfony/options-resolver/Exception/UndefinedOptionsException.php<68><00>``<60>p ͐<>Evendor/symfony/options-resolver/Exception/InvalidOptionsException.php<68><00>``<60><00><>k <0A>Cvendor/symfony/options-resolver/Exception/NoSuchOptionException.php<68><00>``<60>g]<5D>ȴFvendor/symfony/options-resolver/Exception/InvalidArgumentException.php<68><00>``<60><1C>G<B2><47>9vendor/symfony/event-dispatcher/Debug/WrappedListener.php<68>
<00>``<60>
!<21><9D><7F>Kvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php5<00>``5fV<>Bvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php<00>``O '<27>Mvendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php<68><00>``<60>\]<02><><vendor/symfony/event-dispatcher/EventDispatcherInterface.php<68><00>``<60>p<><70>X<AB>0vendor/symfony/event-dispatcher/GenericEvent.phpl<00>``l@F^Ĵ3vendor/symfony/event-dispatcher/EventDispatcher.php3<00>``3Krx"<22>Avendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php<68><00>``<60>0<><30>Ѵ)vendor/symfony/event-dispatcher/Event.php:<00>``:E<> <0C><vendor/symfony/event-dispatcher/ImmutableEventDispatcher.phpq<00>``q<03><><F1><vendor/symfony/event-dispatcher/EventSubscriberInterface.php<68><00>``<60><00><><FD><E8><9F>,vendor/symfony/stopwatch/StopwatchPeriod.phpp<00>``pΧ<>!<21>&vendor/symfony/stopwatch/Stopwatch.php<00>``#i{<7B><>+vendor/symfony/stopwatch/StopwatchEvent.php<68> <00>``<60> !<21>A <0C>$vendor/symfony/stopwatch/Section.php<68><00>``<60><00><>-<2D><>vendor/autoload.php<68><00>``<60>y? D<>#vendor/composer/autoload_static.php<68>}<00>``<60>}d4<64><34><89>4vendor/composer/xdebug-handler/src/XdebugHandler.php<68>$<00>``<60>$<19>0vendor/composer/xdebug-handler/src/PhpConfig.php<68><00>``<60>*D<><00>-vendor/composer/xdebug-handler/src/Status.php
<00>``
$<24>v-<2D>.vendor/composer/xdebug-handler/src/Process.php<68> <00>``<60> <00><>%vendor/composer/InstalledVersions.phpO<00>``O<00><><BF><C5><D4>!vendor/composer/autoload_real.php<68><00>``<60><00><>^#<23>vendor/composer/installed.php.<00>``.<00><><BF>!<21>"vendor/composer/autoload_files.php5<00>``5&<26>-<2D><>!vendor/composer/autoload_psr4.php<68><00>``<60><00><><19><>%vendor/composer/autoload_classmap.php<68>W<00>``<60>W<00><><8E><19>"vendor/composer/platform_check.phpe<00>``eݿJ<DDBF><4A>/vendor/composer/semver/src/CompilingMatcher.php<68><00>``<60>?u<><75>'vendor/composer/semver/src/Interval.php<68><00>``<60> ȏ۴,vendor/composer/semver/src/VersionParser.php<68>+<00>``<60>+7m<1F><vendor/composer/semver/src/Constraint/MatchAllConstraint.php<68><00>``<60><00><><C3><13>4vendor/composer/semver/src/Constraint/Constraint.php<68><00>``<60><00>h<BD><68><96>=vendor/composer/semver/src/Constraint/ConstraintInterface.php<68><00>``<60><00>?[<1E>=vendor/composer/semver/src/Constraint/MatchNoneConstraint.php<68><00>``<60><><EAB4A0>/vendor/composer/semver/src/Constraint/Bound.phpt<00>``t<10>ۜ<F9>9vendor/composer/semver/src/Constraint/MultiConstraint.php<00>``<00><06><><AA>)vendor/composer/semver/src/Comparator.php<00>``<><DD8A>(vendor/composer/semver/src/Intervals.php:,<00>``:,<13><>D<C7>%vendor/composer/semver/src/Semver.php<68><00>``<60>`<60>e<>'vendor/composer/autoload_namespaces.phpd<00>``dZ<><5A>H<A6>vendor/composer/ClassLoader.php<68><00>``<60><00><>Mvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php<68><00>``<60>nWS<1A>Fvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php"<00>``"РKvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php|<00>``|w<1E><17>Pvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.phph<00>``hzԷ<>Svendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.phpm<00>``m<00><>Z<D1><5A>[vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php<68><00>``<60><1E><><A5>Tvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php<68><00>``<60>fʓ۴Uvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php<68><00>``<60><00>~<7E>ĴOvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.phpt<00>``t<00><>]<>Qvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php0<00>``0<00> u<><75>Ovendor/doctrine/annotations/lib/Doctrine/Common/Annotations/FileCacheReader.php<68><00>``<60><00><><DE>q<D0>Ivendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php<00>``V<><56><01>Hvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.phpw<00>``w<00>&n<>Lvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/CachedReader.phpj<00>``j<00>&}<7D><>Svendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php-<00>``-<00><>a<1D>Ivendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php V<00>`` V<00><><E0>`<60>Jvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php<<00>``<z<>X<>Rvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php<68><00>``<60><00><><F7><8E><B1>Vvendor/doctrine/annotations/lib/Doctrine/Common/Annotations/SimpleAnnotationReader.phpJ<00>``Jq*<2A>Avendor/doctrine/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php9 <00>``9 <00><>Z<DE><5A>/vendor/psr/log/Psr/Log/LoggerAwareInterface.php|<00>``|$<13><><A3>+vendor/psr/log/Psr/Log/LoggerAwareTrait.php<68><00>``<60>T<><54>B<FA>)vendor/psr/log/Psr/Log/AbstractLogger.php;<00>``;<00>>3[<5B>%vendor/psr/log/Psr/Log/NullLogger.php<68><00>``<60><00>Di<44><69>#vendor/psr/log/Psr/Log/LogLevel.php<68><00>``<60>j<><6A>8<F1>&vendor/psr/log/Psr/Log/LoggerTrait.phpk<00>``k<00>}<7D><><89>*vendor/psr/log/Psr/Log/LoggerInterface.php<68><00>``<60><00>x<1D>3vendor/psr/log/Psr/Log/InvalidArgumentException.php`<00>``` <20>X1<58>+vendor/php-cs-fixer/diff/src/v1_4/Chunk.php <00>`` <00><><8E>۴*vendor/php-cs-fixer/diff/src/v1_4/Line.php<68><00>``<60>!<21><>/<2F>,vendor/php-cs-fixer/diff/src/v1_4/Differ.phpa<00>``a<00>B<A5><15>]vendor/php-cs-fixer/diff/src/v1_4/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php<68><00>``<60><00> 8<1F>_vendor/php-cs-fixer/diff/src/v1_4/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php<00>``<00>:<1F><>Bvendor/php-cs-fixer/diff/src/v1_4/LCS/LongestCommonSubsequence.php<68><00>``<60><00>)<12><>,vendor/php-cs-fixer/diff/src/v1_4/Parser.php<68><00>``<60>6q<36>c<D1>*vendor/php-cs-fixer/diff/src/v1_4/Diff.php<68><00>``<60>0}n<>+vendor/php-cs-fixer/diff/src/v3_0/Chunk.php<68><00>``<60>&_F<5F><46>*vendor/php-cs-fixer/diff/src/v3_0/Line.php<68><00>``<60><00>8<04><>,vendor/php-cs-fixer/diff/src/v3_0/Differ.php<68><00>``<60> <09>F*<2A>,vendor/php-cs-fixer/diff/src/v3_0/Parser.php<68><00>``<60><00>j?<3F><>Uvendor/php-cs-fixer/diff/src/v3_0/TimeEfficientLongestCommonSubsequenceCalculator.php<68><00>``<60>#<23>1<95><31>Kvendor/php-cs-fixer/diff/src/v3_0/Output/StrictUnifiedDiffOutputBuilder.php<00>``<04><>}<7D>Bvendor/php-cs-fixer/diff/src/v3_0/Output/DiffOnlyOutputBuilder.php<68><00>``<60><00>7Gvendor/php-cs-fixer/diff/src/v3_0/Output/AbstractChunkOutputBuilder.php<00>``<00>=<3D>h<90>Gvendor/php-cs-fixer/diff/src/v3_0/Output/DiffOutputBuilderInterface.php<68><00>``<60>R8O<38><4F>Evendor/php-cs-fixer/diff/src/v3_0/Output/UnifiedDiffOutputBuilder.php<68><00>``<60>IWƴHvendor/php-cs-fixer/diff/src/v3_0/LongestCommonSubsequenceCalculator.php<68><00>``<60>k<1E>b<E3>Fvendor/php-cs-fixer/diff/src/v3_0/Exception/ConfigurationException.php<68><00>``<60>k<>s<17>9vendor/php-cs-fixer/diff/src/v3_0/Exception/Exception.phpH<00>``H{n<><11>Hvendor/php-cs-fixer/diff/src/v3_0/Exception/InvalidArgumentException.php<68><00>``<60><00><1A><><98>*vendor/php-cs-fixer/diff/src/v3_0/Diff.php<68><00>``<60><00>aF<00>Wvendor/php-cs-fixer/diff/src/v3_0/MemoryEfficientLongestCommonSubsequenceCalculator.php
<00>``
<00><>_<80><5F>Wvendor/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/ConfigurationException.php<68><00>``<60><16>z8<7A>Yvendor/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/UnifiedDiffOutputBuilder.php<00>``@<40>:L<>+vendor/php-cs-fixer/diff/src/v2_0/Chunk.php<68><00>``<60><00>k<9C>˴*vendor/php-cs-fixer/diff/src/v2_0/Line.php<68><00>``<60>A<>Q<9F><51>,vendor/php-cs-fixer/diff/src/v2_0/Differ.php+<00>``+N1 δ,vendor/php-cs-fixer/diff/src/v2_0/Parser.php<68><00>``<60>l<><6C>C<E0>Uvendor/php-cs-fixer/diff/src/v2_0/TimeEfficientLongestCommonSubsequenceCalculator.php<68><00>``<60><00><><98>K<EC>Bvendor/php-cs-fixer/diff/src/v2_0/Output/DiffOnlyOutputBuilder.php<68><00>``<60>E{I<>Gvendor/php-cs-fixer/diff/src/v2_0/Output/AbstractChunkOutputBuilder.php<00>``1<>%|<7C>Gvendor/php-cs-fixer/diff/src/v2_0/Output/DiffOutputBuilderInterface.php<68><00>``<60><00>u<><75>Evendor/php-cs-fixer/diff/src/v2_0/Output/UnifiedDiffOutputBuilder.php<68> <00>``<60> .<2E>۴Hvendor/php-cs-fixer/diff/src/v2_0/LongestCommonSubsequenceCalculator.php<68><00>``<60>5<><1C>9vendor/php-cs-fixer/diff/src/v2_0/Exception/Exception.phpH<00>``Hs<><73>-<2D>Hvendor/php-cs-fixer/diff/src/v2_0/Exception/InvalidArgumentException.php<68><00>``<60>;<3B><>$<24>*vendor/php-cs-fixer/diff/src/v2_0/Diff.php<68><00>``<60><00><><B9><13>Wvendor/php-cs-fixer/diff/src/v2_0/MemoryEfficientLongestCommonSubsequenceCalculator.php
<00>``
<00>h <0A>3vendor/paragonie/random_compat/phpunit-autoload.php<68><00>``<60>4GYY<59>>vendor/paragonie/random_compat/lib/random_bytes_com_dotnet.php<68><00>``<60>vA<><41>:vendor/paragonie/random_compat/lib/random_bytes_mcrypt.php5<00>``5IWyl<79>8vendor/paragonie/random_compat/lib/byte_safe_strings.phpp<00>``p3<>6d<36>-vendor/paragonie/random_compat/lib/random.php<68> <00>``<60> <00><><08><>=vendor/paragonie/random_compat/lib/random_bytes_libsodium.php<68><00>``<60>3+2g<32>5vendor/paragonie/random_compat/lib/error_polyfill.php<00>``<00><>a4<61>2vendor/paragonie/random_compat/lib/cast_to_int.php<00>``<00><>|w<>Dvendor/paragonie/random_compat/lib/random_bytes_libsodium_legacy.php<68><00>``<60><00><>!<21><>?vendor/paragonie/random_compat/lib/random_bytes_dev_urandom.php<68><00>``<60><00><><B0><FC><B4>1vendor/paragonie/random_compat/lib/random_int.php.<00>``.m1<6D><1D>LICENSES<00>``S<00><><FF>q<A3> php-cs-fixeru<00>``u<00><07>?<3F><?php
namespace PhpCsFixer;
use PhpCsFixer\Doctrine\Annotation\Tokens as DoctrineAnnotationTokens;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token as PhpToken;
use PhpCsFixer\Tokenizer\Tokens as PhpTokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
abstract class AbstractDoctrineAnnotationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $classyElements;
public function isCandidate(PhpTokens $tokens)
{
return $tokens->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]);
}
}
<?php
namespace PhpCsFixer\FixerDefinition;
final class FixerDefinition implements FixerDefinitionInterface
{
private $riskyDescription;
private $configurationDescription;
private $defaultConfiguration;
private $codeSamples;
private $summary;
private $description;
public function __construct(
$summary,
array $codeSamples,
$description = null,
$configurationDescription = null,
array $defaultConfiguration = null,
$riskyDescription = null
) {
if (6 === \func_num_args()) {
@trigger_error('Arguments #5 and #6 of FixerDefinition::__construct() are deprecated and will be removed in 3.0, use argument #4 instead.', E_USER_DEPRECATED);
} elseif (5 === \func_num_args()) {
@trigger_error('Argument #5 of FixerDefinition::__construct() is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
} else {
$riskyDescription = $configurationDescription;
$configurationDescription = null;
}
$this->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;
}
}
<?php
namespace PhpCsFixer\FixerDefinition;
interface VersionSpecificCodeSampleInterface extends CodeSampleInterface
{
public function isSuitableFor($version);
}
<?php
namespace PhpCsFixer\FixerDefinition;
final class VersionSpecificCodeSample implements VersionSpecificCodeSampleInterface
{
private $codeSample;
private $versionSpecification;
public function __construct(
$code,
VersionSpecificationInterface $versionSpecification,
array $configuration = null
) {
$this->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);
}
}
<?php
namespace PhpCsFixer\FixerDefinition;
interface FixerDefinitionInterface
{
public function getSummary();
public function getDescription();
public function getConfigurationDescription();
public function getDefaultConfiguration();
public function getRiskyDescription();
public function getCodeSamples();
}
<?php
namespace PhpCsFixer\FixerDefinition;
final class CodeSample implements CodeSampleInterface
{
private $code;
private $configuration;
public function __construct($code, array $configuration = null)
{
$this->code = $code;
$this->configuration = $configuration;
}
public function getCode()
{
return $this->code;
}
public function getConfiguration()
{
return $this->configuration;
}
}
<?php
namespace PhpCsFixer\FixerDefinition;
interface CodeSampleInterface
{
public function getCode();
public function getConfiguration();
}
<?php
namespace PhpCsFixer\FixerDefinition;
interface VersionSpecificationInterface
{
public function isSatisfiedBy($version);
}
<?php
namespace PhpCsFixer\FixerDefinition;
final class VersionSpecification implements VersionSpecificationInterface
{
private $minimum;
private $maximum;
public function __construct($minimum = null, $maximum = null)
{
if (null === $minimum && null === $maximum) {
throw new \InvalidArgumentException('Minimum or maximum need to be specified.');
}
if (null !== $minimum && (!\is_int($minimum) || 1 > $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;
}
}
<?php
namespace PhpCsFixer\FixerDefinition;
interface FileSpecificCodeSampleInterface extends CodeSampleInterface
{
public function getSplFileInfo();
}
<?php
namespace PhpCsFixer\FixerDefinition;
final class FileSpecificCodeSample implements FileSpecificCodeSampleInterface
{
private $codeSample;
private $splFileInfo;
public function __construct(
$code,
\SplFileInfo $splFileInfo,
array $configuration = null
) {
$this->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;
}
}
<?php
namespace PhpCsFixer\Report;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class GitlabReporter implements ReporterInterface
{
public function getFormat()
{
return 'gitlab';
}
public function generate(ReportSummary $reportSummary)
{
$report = [];
foreach ($reportSummary->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;
}
}
<?php
namespace PhpCsFixer\Report;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class JsonReporter implements ReporterInterface
{
public function getFormat()
{
return 'json';
}
public function generate(ReportSummary $reportSummary)
{
$jFiles = [];
foreach ($reportSummary->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;
}
}
<?php
namespace PhpCsFixer\Report;
use Symfony\Component\Finder\Finder as SymfonyFinder;
use Symfony\Component\Finder\SplFileInfo;
final class ReporterFactory
{
private $reporters = [];
public static function create()
{
return new self();
}
public function registerBuiltInReporters()
{
static $builtInReporters;
if (null === $builtInReporters) {
$builtInReporters = [];
foreach (SymfonyFinder::create()->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];
}
}
<?php
namespace PhpCsFixer\Report;
final class ReportSummary
{
private $addAppliedFixers;
private $changed;
private $isDecoratedOutput;
private $isDryRun;
private $memory;
private $time;
public function __construct(
array $changed,
$time,
$memory,
$addAppliedFixers,
$isDryRun,
$isDecoratedOutput
) {
$this->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;
}
}
<?php
namespace PhpCsFixer\Report;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class CheckstyleReporter implements ReporterInterface
{
public function getFormat()
{
return 'checkstyle';
}
public function generate(ReportSummary $reportSummary)
{
if (!\extension_loaded('dom')) {
throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!');
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$checkstyles = $dom->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;
}
}
<?php
namespace PhpCsFixer\Report;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class XmlReporter implements ReporterInterface
{
public function getFormat()
{
return 'xml';
}
public function generate(ReportSummary $reportSummary)
{
if (!\extension_loaded('dom')) {
throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!');
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$root = $dom->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;
}
}
<?php
namespace PhpCsFixer\Report;
use PhpCsFixer\Differ\DiffConsoleFormatter;
final class TextReporter implements ReporterInterface
{
public function getFormat()
{
return 'txt';
}
public function generate(ReportSummary $reportSummary)
{
$output = '';
$i = 0;
foreach ($reportSummary->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 ? ' (<comment>%s</comment>)' : ' (%s)',
implode(', ', $fixResult['appliedFixers'])
);
}
private function getDiff($isDecoratedOutput, array $fixResult)
{
if (empty($fixResult['diff'])) {
return '';
}
$diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, sprintf(
'<comment> ---------- begin diff ----------</comment>%s%%s%s<comment> ----------- end diff -----------</comment>',
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
);
}
}
<?php
namespace PhpCsFixer\Report;
use PhpCsFixer\Preg;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class JunitReporter implements ReporterInterface
{
public function getFormat()
{
return 'junit';
}
public function generate(ReportSummary $reportSummary)
{
if (!\extension_loaded('dom')) {
throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!');
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$testsuites = $dom->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;
}
}
<?php
namespace PhpCsFixer\Report;
interface ReporterInterface
{
public function getFormat();
public function generate(ReportSummary $reportSummary);
}
<?php
namespace PhpCsFixer\Doctrine\Annotation;
use Doctrine\Common\Annotations\DocLexer;
final class Token
{
private $type;
private $content;
public function __construct($type = DocLexer::T_NONE, $content = '')
{
$this->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('');
}
}
<?php
namespace PhpCsFixer\Doctrine\Annotation;
use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token as PhpToken;
final class Tokens extends \SplFixedArray
{
public static function createFromDocComment(PhpToken $input, array $ignoredTags = [])
{
if (!$input->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;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Event\Event;
final class FixerFileProcessedEvent extends Event
{
const NAME = 'fixer.file_processed';
const STATUS_UNKNOWN = 0;
const STATUS_INVALID = 1;
const STATUS_SKIPPED = 2;
const STATUS_NO_CHANGES = 3;
const STATUS_FIXED = 4;
const STATUS_EXCEPTION = 5;
const STATUS_LINT = 6;
private $status;
public function __construct($status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
}
<?php
namespace PhpCsFixer;
final class Preg
{
public static function match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
{
$result = @preg_match(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
$result = @preg_match(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
throw self::newPregException(preg_last_error(), __METHOD__, (array) $pattern);
}
public static function matchAll($pattern, $subject, &$matches = null, $flags = PREG_PATTERN_ORDER, $offset = 0)
{
$result = @preg_match_all(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
$result = @preg_match_all(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
throw self::newPregException(preg_last_error(), __METHOD__, (array) $pattern);
}
public static function replace($pattern, $replacement, $subject, $limit = -1, &$count = null)
{
$result = @preg_replace(self::addUtf8Modifier($pattern), $replacement, $subject, $limit, $count);
if (null !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
$result = @preg_replace(self::removeUtf8Modifier($pattern), $replacement, $subject, $limit, $count);
if (null !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
throw self::newPregException(preg_last_error(), __METHOD__, (array) $pattern);
}
public static function replaceCallback($pattern, $callback, $subject, $limit = -1, &$count = null)
{
$result = @preg_replace_callback(self::addUtf8Modifier($pattern), $callback, $subject, $limit, $count);
if (null !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
$result = @preg_replace_callback(self::removeUtf8Modifier($pattern), $callback, $subject, $limit, $count);
if (null !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
throw self::newPregException(preg_last_error(), __METHOD__, (array) $pattern);
}
public static function split($pattern, $subject, $limit = -1, $flags = 0)
{
$result = @preg_split(self::addUtf8Modifier($pattern), $subject, $limit, $flags);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
$result = @preg_split(self::removeUtf8Modifier($pattern), $subject, $limit, $flags);
if (false !== $result && PREG_NO_ERROR === preg_last_error()) {
return $result;
}
throw self::newPregException(preg_last_error(), __METHOD__, (array) $pattern);
}
private static function addUtf8Modifier($pattern)
{
if (\is_array($pattern)) {
return array_map(__METHOD__, $pattern);
}
return $pattern.'u';
}
private static function removeUtf8Modifier($pattern)
{
if (\is_array($pattern)) {
return array_map(__METHOD__, $pattern);
}
if ('' === $pattern) {
return '';
}
$delimiter = $pattern[0];
$endDelimiterPosition = strrpos($pattern, $delimiter);
return substr($pattern, 0, $endDelimiterPosition).str_replace('u', '', substr($pattern, $endDelimiterPosition));
}
private static function newPregException($error, $method, array $patterns)
{
foreach ($patterns as $pattern) {
$last = error_get_last();
$result = @preg_match($pattern, '');
if (false !== $result) {
continue;
}
$code = preg_last_error();
$next = error_get_last();
if ($last !== $next) {
$message = sprintf(
'(code: %d) %s',
$code,
preg_replace('~preg_[a-z_]+[()]{2}: ~', '', $next['message'])
);
} else {
$message = sprintf('(code: %d)', $code);
}
return new PregException(
sprintf('%s(): Invalid PCRE pattern "%s": %s (version: %s)', $method, $pattern, $message, PCRE_VERSION),
$code
);
}
return new PregException(sprintf('Error occurred when calling %s.', $method), $error);
}
}
<?php
namespace PhpCsFixer;
final class FixerNameValidator
{
public function isValid($name, $isCustom)
{
if (!$isCustom) {
return 1 === Preg::match('/^[a-z][a-z0-9_]*$/', $name);
}
return 1 === Preg::match('/^[A-Z][a-zA-Z0-9]*\/[a-z][a-z0-9_]*$/', $name);
}
}
<?php
namespace PhpCsFixer\Documentation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Console\Command\HelpCommand;
use PhpCsFixer\Diff\GeckoPackages\DiffOutputBuilder\UnifiedDiffOutputBuilder;
use PhpCsFixer\Diff\v2_0\Differ;
use PhpCsFixer\Fixer\Basic\Psr0Fixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DefinedFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface;
use PhpCsFixer\FixerDefinition\CodeSampleInterface;
use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\RuleSet\RuleSet;
use PhpCsFixer\RuleSet\RuleSetDescriptionInterface;
use PhpCsFixer\RuleSet\RuleSets;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
final class DocumentationGenerator
{
private $differ;
private $path;
public function __construct()
{
$this->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 .= <<<RST
- `{$fixer->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 .= <<<RST
Description
-----------
{$description}
RST;
}
$riskyDescription = $definition->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 .= <<<RST
.. warning:: Using this rule is risky.
{$riskyDescription}
RST;
}
if ($fixer instanceof ConfigurationDefinitionFixerInterface) {
$doc .= <<<'RST'
Configuration
-------------
RST;
$configurationDefinition = $fixer->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 .= <<<RST
Rule sets
---------
The rule is part of the following rule set{$plural}:
RST;
foreach ($ruleSetConfigs as $set => $config) {
$ruleSetPath = $this->getRuleSetsDocumentationFilePath($set);
$ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/'));
$doc .= <<<RST
{$set}
Using the `{$set} <./../../ruleSets{$ruleSetPath}>`_ 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.+?(?<diff>\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|$)/s", $existingFile, $matches);
if (isset($matches['diff'])) {
return $matches['diff'];
}
}
$error = <<<RST
.. error::
Cannot generate diff for code sample #{$sampleNumber} of rule {$ruleName}:
the sample is not suitable for current version of PHP (%s).
RST;
return sprintf($error, PHP_VERSION);
}
$old = $sample->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 <<<RST
.. code-block:: diff
{$this->indent($diff, 3)}
RST;
}
private function toRst($string, $indent = 0)
{
$string = wordwrap(Preg::replace('/(?<!`)(`.*?`)(?!`)/', '`$1`', $string), 80 - $indent);
if (0 !== $indent) {
$string = $this->indent($string, $indent);
}
return $string;
}
private function indent($string, $indent)
{
return Preg::replace('/(\n)(?!\n|$)/', '$1'.str_repeat(' ', $indent), $string);
}
}
<?php
namespace PhpCsFixer\Console;
use PhpCsFixer\Console\Command\DescribeCommand;
use PhpCsFixer\Console\Command\FixCommand;
use PhpCsFixer\Console\Command\HelpCommand;
use PhpCsFixer\Console\Command\SelfUpdateCommand;
use PhpCsFixer\Console\SelfUpdate\GithubClient;
use PhpCsFixer\Console\SelfUpdate\NewVersionChecker;
use PhpCsFixer\PharChecker;
use PhpCsFixer\ToolInfo;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
@gmail
*/
final class Application extends BaseApplication
{
const VERSION = '2.18.2';
const VERSION_CODENAME = 'Remote Void';
private $toolInfo;
public function __construct()
{
if (!getenv('PHP_CS_FIXER_FUTURE_MODE')) {
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
}
parent::__construct('PHP CS Fixer', self::VERSION);
$this->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() ? '<bg=yellow;fg=black;>%s</>' : '%s', $warning));
}
}
return parent::doRun($input, $output);
}
public function getLongVersion()
{
$version = sprintf(
'%s <info>%s</info> by <comment>Fabien Potencier</comment> and <comment>Dariusz Ruminski</comment>',
parent::getLongVersion(),
self::VERSION_CODENAME
);
$commit = '18f8c9d184ba777380794a389fabc179896ba913';
if ('@'.'git-commit@' !== $commit) {
$version .= ' ('.substr($commit, 0, 7).')';
}
return $version;
}
protected function getDefaultCommands()
{
return [new HelpCommand(), new ListCommand()];
}
}
<?php
namespace PhpCsFixer\Console;
use PhpCsFixer\ToolInfo;
use PhpCsFixer\ToolInfoInterface;
final class WarningsDetector
{
private $toolInfo;
private $warnings = [];
public function __construct(ToolInfoInterface $toolInfo)
{
$this->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!']
));
}
}
<?php
namespace PhpCsFixer\Console\Output;
interface ProcessOutputInterface
{
public function printLegend();
}
<?php
namespace PhpCsFixer\Console\Output;
use PhpCsFixer\FixerFileProcessedEvent;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
final class ProcessOutput implements ProcessOutputInterface
{
private static $eventStatusMap = [
FixerFileProcessedEvent::STATUS_UNKNOWN => ['symbol' => '?', 'format' => '%s', 'description' => 'unknown'],
FixerFileProcessedEvent::STATUS_INVALID => ['symbol' => 'I', 'format' => '<bg=red>%s</bg=red>', 'description' => 'invalid file syntax (file ignored)'],
FixerFileProcessedEvent::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '<fg=cyan>%s</fg=cyan>', 'description' => 'skipped (cached or empty file)'],
FixerFileProcessedEvent::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'],
FixerFileProcessedEvent::STATUS_FIXED => ['symbol' => 'F', 'format' => '<fg=green>%s</fg=green>', 'description' => 'fixed'],
FixerFileProcessedEvent::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '<bg=red>%s</bg=red>', 'description' => 'error'],
FixerFileProcessedEvent::STATUS_LINT => ['symbol' => 'E', 'format' => '<bg=red>%s</bg=red>', '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 __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
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)));
}
}
<?php
namespace PhpCsFixer\Console\Output;
final class NullOutput implements ProcessOutputInterface
{
public function printLegend()
{
}
}
<?php
namespace PhpCsFixer\Console\Output;
use PhpCsFixer\Differ\DiffConsoleFormatter;
use PhpCsFixer\Error\Error;
use PhpCsFixer\Linter\LintingException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Output\OutputInterface;
final class ErrorOutput
{
private $output;
private $isDecorated;
public function __construct(OutputInterface $output)
{
$this->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(' <error> %s </error>', $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: <comment>%s</comment>', implode(', ', $error->getAppliedFixers())));
$diff = $error->getDiff();
if (!empty($diff)) {
$diffFormatter = new DiffConsoleFormatter(
$this->isDecorated,
sprintf(
'<comment> ---------- begin diff ----------</comment>%s%%s%s<comment> ----------- end diff -----------</comment>',
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(
' <comment>%s</comment>%s<comment>%s()</comment>',
$this->prepareOutput($trace['class']),
$this->prepareOutput($trace['type']),
$this->prepareOutput($trace['function'])
));
} elseif (isset($trace['function'])) {
$this->output->writeln(sprintf(' <comment>%s()</comment>', $this->prepareOutput($trace['function'])));
}
if (isset($trace['file'])) {
$this->output->writeln(sprintf(' in <info>%s</info> at line <info>%d</info>', $this->prepareOutput($trace['file']), $trace['line']));
}
}
private function prepareOutput($string)
{
return $this->isDecorated
? OutputFormatter::escape($string)
: $string
;
}
}
<?php
namespace PhpCsFixer\Console;
use PhpCsFixer\Cache\CacheManagerInterface;
use PhpCsFixer\Cache\Directory;
use PhpCsFixer\Cache\DirectoryInterface;
use PhpCsFixer\Cache\FileCacheManager;
use PhpCsFixer\Cache\FileHandler;
use PhpCsFixer\Cache\NullCacheManager;
use PhpCsFixer\Cache\Signature;
use PhpCsFixer\ConfigInterface;
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\Differ\DifferInterface;
use PhpCsFixer\Differ\NullDiffer;
use PhpCsFixer\Differ\SebastianBergmannDiffer;
use PhpCsFixer\Differ\UnifiedDiffer;
use PhpCsFixer\Finder;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\Linter\Linter;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Report\ReporterFactory;
use PhpCsFixer\Report\ReporterInterface;
use PhpCsFixer\RuleSet\RuleSet;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\ToolInfoInterface;
use PhpCsFixer\Utils;
use PhpCsFixer\WhitespacesFixerConfig;
use PhpCsFixer\WordMatcher;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder as SymfonyFinder;
/**
@gmail
@gmail
*/
final class ConfigurationResolver
{
const PATH_MODE_OVERRIDE = 'override';
const PATH_MODE_INTERSECTION = 'intersection';
private $allowRisky;
private $config;
private $configFile;
private $cwd;
private $defaultConfig;
private $reporter;
private $isStdIn;
private $isDryRun;
private $fixers;
private $configFinderIsOverridden;
private $toolInfo;
private $options = [
'allow-risky' => 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']) {
$defaultOption = 'null';
} elseif (getenv('PHP_CS_FIXER_FUTURE_MODE')) {
$defaultOption = 'udiff';
} else {
$defaultOption = 'sbd';
}
$option = isset($this->options['diff-format'])
? $this->options['diff-format']
: $defaultOption;
if (!\is_string($option)) {
throw new InvalidConfigurationException(sprintf(
'"diff-format" must be a string, "%s" given.',
\gettype($option)
));
}
if (is_subclass_of($option, DifferInterface::class)) {
$this->differ = new $option();
} elseif (!isset($mapper[$option])) {
throw new InvalidConfigurationException(sprintf(
'"diff-format" must be any of "%s", got "%s".',
implode('", "', array_keys($mapper)),
$option
));
} else {
$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;
}
}
<?php
namespace PhpCsFixer\Console\Command;
use PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface;
use PhpCsFixer\PharCheckerInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\ToolInfoInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
@gmail
@lyrixx
@gmail
*/
final class SelfUpdateCommand extends Command
{
protected static $defaultName = 'self-update';
private $versionChecker;
private $toolInfo;
private $pharChecker;
public function __construct(
NewVersionCheckerInterface $versionChecker,
ToolInfoInterface $toolInfo,
PharCheckerInterface $pharChecker
) {
parent::__construct();
$this->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 <info>%command.name%</info> command replace your php-cs-fixer.phar by the
latest version released on:
<comment>https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases</comment>
<info>$ php php-cs-fixer.phar %command.name%</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) {
$stdErr = $output->getErrorOutput();
$stdErr->writeln($this->getApplication()->getLongVersion());
$stdErr->writeln(sprintf('Runtime: <info>PHP %s</info>', PHP_VERSION));
}
if (!$this->toolInfo->isInstalledAsPhar()) {
$output->writeln('<error>Self-update is available only for PHAR version.</error>');
return 1;
}
$currentVersion = $this->getApplication()->getVersion();
Preg::match('/^v?(?<major>\d+)\./', $currentVersion, $matches);
$currentMajor = (int) $matches['major'];
try {
$latestVersion = $this->versionChecker->getLatestVersion();
$latestVersionOfCurrentMajor = $this->versionChecker->getLatestVersionOfMajor($currentMajor);
} catch (\Exception $exception) {
$output->writeln(sprintf(
'<error>Unable to determine newest version: %s</error>',
$exception->getMessage()
));
return 1;
}
if (1 !== $this->versionChecker->compareVersions($latestVersion, $currentVersion)) {
$output->writeln('<info>PHP CS Fixer is already up to date.</info>');
return 0;
}
$remoteTag = $latestVersion;
if (
0 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $latestVersion)
&& true !== $input->getOption('force')
) {
$output->writeln(sprintf('<info>A new major version of PHP CS Fixer is available</info> (<comment>%s</comment>)', $latestVersion));
$output->writeln(sprintf('<info>Before upgrading please read</info> https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/%s/UPGRADE.md', $latestVersion));
$output->writeln('<info>If you are ready to upgrade run this command with</info> <comment>-f</comment>');
$output->writeln('<info>Checking for new minor/patch version...</info>');
if (1 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $currentVersion)) {
$output->writeln('<info>No minor update for PHP CS Fixer.</info>');
return 0;
}
$remoteTag = $latestVersionOfCurrentMajor;
}
$localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
if (!is_writable($localFilename)) {
$output->writeln(sprintf('<error>No permission to update</error> "%s" <error>file.</error>', $localFilename));
return 1;
}
$tempFilename = \dirname($localFilename).'/'.basename($localFilename, '.phar').'-tmp.phar';
$remoteFilename = $this->toolInfo->getPharDownloadUri($remoteTag);
if (false === @copy($remoteFilename, $tempFilename)) {
$output->writeln(sprintf('<error>Unable to download new version</error> %s <error>from the server.</error>', $remoteTag));
return 1;
}
chmod($tempFilename, 0777 & ~umask());
$pharInvalidityReason = $this->pharChecker->checkFileValidity($tempFilename);
if (null !== $pharInvalidityReason) {
unlink($tempFilename);
$output->writeln(sprintf('<error>The download of</error> %s <error>is corrupt (%s).</error>', $remoteTag, $pharInvalidityReason));
$output->writeln('<error>Please re-run the "self-update" command to try again.</error>');
return 1;
}
rename($tempFilename, $localFilename);
$output->writeln(sprintf('<info>PHP CS Fixer updated</info> (<comment>%s</comment> -> <comment>%s</comment>)', $currentVersion, $remoteTag));
return 0;
}
}
<?php
namespace PhpCsFixer\Console\Command;
use PhpCsFixer\Documentation\DocumentationGenerator;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\RuleSet\RuleSets;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
final class DocumentationCommand extends Command
{
protected static $defaultName = 'documentation';
private $generator;
public function __construct($name = null)
{
parent::__construct($name);
$this->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}.");
}
}
}
<?php
namespace PhpCsFixer\Console\Command;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Console\Application;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\Preg;
use PhpCsFixer\RuleSet\RuleSet;
use PhpCsFixer\RuleSet\RuleSets;
use PhpCsFixer\Utils;
use Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
@gmail
*/
final class HelpCommand extends BaseHelpCommand
{
protected static $defaultName = 'help';
public static function getHelpCopy()
{
$template =
<<<'EOF'
The <info>%command.name%</info> command tries to fix as much coding standards
problems as possible on a given file or files in a given directory and its subdirectories:
<info>$ php %command.full_name% /path/to/dir</info>
<info>$ php %command.full_name% /path/to/file</info>
By default <comment>--path-mode</comment> 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 <comment>--path-mode=intersection</comment>
to merge paths from the config file and from the argument:
<info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>
The <comment>--format</comment> 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 </doc/report-schema/checkstyle.xsd>`_
* `junit` follows the `JUnit xml schema from Jenkins </doc/report-schema/junit-10.xsd>`_
The <comment>--quiet</comment> Do not output any message.
The <comment>--verbose</comment> 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 <comment>--rules</comment> option limits the rules to apply to the
project:
<info>$ php %command.full_name% /path/to/project --rules=@PSR2</info>
By default the PSR1 and PSR2 rules are used.
The <comment>--rules</comment> option lets you choose the exact rules to
apply (the rule names must be separated by a comma):
<info>$ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type</info>
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 <comment>-name_of_fixer</comment>:
<info>$ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type</info>
When using combinations of exact and exclude rules, applying exact rules along with above excluded results:
<info>$ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison</info>
Complete configuration for rules can be supplied using a `json` formatted string.
<info>$ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}'</info>
The <comment>--dry-run</comment> flag will run the fixer without making changes to your files.
The <comment>--diff</comment> flag can be used to let the fixer output all the changes it makes.
The <comment>--diff-format</comment> option allows to specify in which format the fixer should output the changes it makes:
* <comment>udiff</comment>: unified diff format;
* <comment>sbd</comment>: Sebastianbergmann/diff format (default when using `--diff` without specifying `diff-format`).
The <comment>--allow-risky</comment> 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 <comment>--stop-on-violation</comment> flag stops the execution upon first file that needs to be fixed.
The <comment>--show-progress</comment> option allows you to choose the way process progress is rendered:
* <comment>none</comment>: disables progress output;
* <comment>run-in</comment>: [deprecated] simple single-line progress output;
* <comment>estimating</comment>: [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;
* <comment>estimating-max</comment>: [deprecated] same as <comment>dots</comment>;
* <comment>dots</comment>: same as <comment>estimating</comment> but using all terminal columns instead of default 80.
If the option is not provided, it defaults to <comment>run-in</comment> unless a config file that disables output is used, in which case it defaults to <comment>none</comment>. This option has no effect if the verbosity of the command is less than <comment>verbose</comment>.
<info>$ php %command.full_name% --verbose --show-progress=estimating</info>
The command can also read from standard input, in which case it won't
automatically fix anything:
<info>$ cat foo.php | php %command.full_name% --diff -</info>
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):
<info>$ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff</info>
Rules
-----
Use the following command to quickly understand what a rule will do to your code:
<info>$ php php-cs-fixer.phar describe align_multiline_comment</info>
To visualize all the rules that belong to a ruleset:
<info>$ php php-cs-fixer.phar describe @PSR2</info>
Choose from the list of available rules:
%%%FIXERS_DETAILS%%%
The <comment>--dry-run</comment> option displays the files that need to be
fixed but without actually modifying them:
<info>$ php %command.full_name% /path/to/code --dry-run</info>
Config file
-----------
Instead of using command line options to customize the rule, you can save the
project configuration in a <comment>.php_cs.dist</comment> file in the root directory of your project.
The file must return an instance of `PhpCsFixer\ConfigInterface` (<url>%%%CONFIG_INTERFACE_URL%%%</url>)
which lets you configure the rules, the files and directories that
need to be analyzed. You may also create <comment>.php_cs</comment> 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 <comment>.gitignore</comment> file.
With the <comment>--config</comment> option you can specify the path to the
<comment>.php_cs</comment> file.
The example below will add two rules to the default list of PSR2 set rules:
<?php
$finder = PhpCsFixer\Finder::create()
->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` (<url>https://symfony.com/doc/current/components/finder.html</url>)
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.
<?php
$finder = PhpCsFixer\Finder::create()
->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.
<?php
$config = new Config();
return $config
->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:
<?php
$config = new Config();
return $config->setUsingCache(false);
?>
Cache file can be specified via `--cache-file` option or config file:
<?php
$config = new Config();
return $config->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('/(`.+?`)/', '<info>$1</info>', $description),
72
));
if (!empty($sets)) {
$help .= sprintf(" * <comment>%s</comment> [%s]\n | %s\n", $fixer->getName(), implode(', ', $sets), $description);
} else {
$help .= sprintf(" * <comment>%s</comment>\n | %s\n", $fixer->getName(), $description);
}
if ($fixer->isRisky()) {
$help .= sprintf(
" | *Risky rule: %s.*\n",
Preg::replace(
'/(`.+?`)/',
'<info>$1</info>',
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 = '<info>'.OutputFormatter::escape($option->getName()).'</info>';
$allowed = self::getDisplayableAllowedValues($option);
if (null !== $allowed) {
foreach ($allowed as &$value) {
if ($value instanceof AllowedValueSubset) {
$value = 'a subset of <comment>'.self::toString($value->getAllowedValues()).'</comment>';
} else {
$value = '<comment>'.self::toString($value).'</comment>';
}
}
} else {
$allowed = array_map(
static function ($type) {
return '<comment>'.$type.'</comment>';
},
$option->getAllowedTypes()
);
}
if (null !== $allowed) {
$line .= ' ('.implode(', ', $allowed).')';
}
$line .= ': '.Preg::replace(
'/(`.+?`)/',
'<info>$1</info>',
lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDescription())))
).'; ';
if ($option->hasDefault()) {
$line .= 'defaults to <comment>'.self::toString($option->getDefault()).'</comment>';
} else {
$line .= 'required';
}
if ($option instanceof DeprecatedFixerOption) {
$line .= '. DEPRECATED: '.Preg::replace(
'/(`.+?`)/',
'<info>$1</info>',
lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDeprecationMessage())))
);
}
if ($option instanceof AliasedFixerOption) {
$line .= '; DEPRECATED alias: <comment>'.$option->getAlias().'</comment>';
}
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('~</?(\w+)>~', '', $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;
}
}
<?php
namespace PhpCsFixer\Console\Command;
use PhpCsFixer\Config;
use PhpCsFixer\ConfigInterface;
use PhpCsFixer\Console\ConfigurationResolver;
use PhpCsFixer\Console\Output\ErrorOutput;
use PhpCsFixer\Console\Output\NullOutput;
use PhpCsFixer\Console\Output\ProcessOutput;
use PhpCsFixer\Error\ErrorsManager;
use PhpCsFixer\Report\ReportSummary;
use PhpCsFixer\Runner\Runner;
use PhpCsFixer\ToolInfoInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;
/**
@gmail
*/
final class FixCommand extends Command
{
protected static $defaultName = 'fix';
private $eventDispatcher;
private $errorsManager;
private $stopwatch;
private $defaultConfig;
private $toolInfo;
public function __construct(ToolInfoInterface $toolInfo)
{
parent::__construct();
$this->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 (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$stdErr->writeln($this->getApplication()->getLongVersion());
$stdErr->writeln(sprintf('Runtime: <info>PHP %s</info>', PHP_VERSION));
}
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() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'When passing both "--config" and "--rules" the rules within the configuration file are not used.'),
sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%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 <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"'));
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() ? '<bg=yellow;fg=black;>%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 <= $verbosity,
$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
);
}
}
<?php
namespace PhpCsFixer\Console\Command;
final class FixCommandExitStatusCalculator
{
const EXIT_STATUS_FLAG_HAS_INVALID_FILES = 4;
const EXIT_STATUS_FLAG_HAS_CHANGED_FILES = 8;
const EXIT_STATUS_FLAG_HAS_INVALID_CONFIG = 16;
const EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG = 32;
const EXIT_STATUS_FLAG_EXCEPTION_IN_APP = 64;
public function calculate($isDryRun, $hasChangedFiles, $hasInvalidErrors, $hasExceptionErrors, $hasLintErrorsAfterFixing)
{
$exitStatus = 0;
if ($isDryRun) {
if ($hasChangedFiles) {
$exitStatus |= self::EXIT_STATUS_FLAG_HAS_CHANGED_FILES;
}
if ($hasInvalidErrors) {
$exitStatus |= self::EXIT_STATUS_FLAG_HAS_INVALID_FILES;
}
}
if ($hasExceptionErrors || $hasLintErrorsAfterFixing) {
$exitStatus |= self::EXIT_STATUS_FLAG_EXCEPTION_IN_APP;
}
return $exitStatus;
}
}
<?php
namespace PhpCsFixer\Console\Command;
final class DescribeNameNotFoundException extends \InvalidArgumentException
{
private $name;
private $type;
public function __construct($name, $type)
{
$this->name = $name;
$this->type = $type;
parent::__construct();
}
public function getName()
{
return $this->name;
}
public function getType()
{
return $this->type;
}
}
<?php
namespace PhpCsFixer\Console\Command;
use PhpCsFixer\Differ\DiffConsoleFormatter;
use PhpCsFixer\Differ\FullDiffer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DefinedFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
use PhpCsFixer\FixerDefinition\CodeSampleInterface;
use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\Preg;
use PhpCsFixer\RuleSet\RuleSets;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
use PhpCsFixer\WordMatcher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class DescribeCommand extends Command
{
protected static $defaultName = 'describe';
private $setNames;
private $fixerFactory;
private $fixers;
public function __construct(FixerFactory $fixerFactory = null)
{
parent::__construct();
if (null === $fixerFactory) {
$fixerFactory = new FixerFactory();
$fixerFactory->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)
{
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) {
$stdErr = $output->getErrorOutput();
$stdErr->writeln($this->getApplication()->getLongVersion());
$stdErr->writeln(sprintf('Runtime: <info>PHP %s</info>', PHP_VERSION));
}
$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('/(`.+?`)/', '<info>$1</info>', $message);
$description .= sprintf(' <error>DEPRECATED</error>: %s.', $message);
}
$output->writeln(sprintf('<info>Description of</info> %s <info>rule</info>.', $name));
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln(sprintf('Fixer class: <comment>%s</comment>.', \get_class($fixer)));
}
$output->writeln($description);
if ($definition->getDescription()) {
$output->writeln($definition->getDescription());
}
$output->writeln('');
if ($fixer->isRisky()) {
$output->writeln('<error>Fixer applying this rule is risky.</error>');
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 = '* <info>'.OutputFormatter::escape($option->getName()).'</info>';
$allowed = HelpCommand::getDisplayableAllowedValues($option);
if (null !== $allowed) {
foreach ($allowed as &$value) {
if ($value instanceof AllowedValueSubset) {
$value = 'a subset of <comment>'.HelpCommand::toString($value->getAllowedValues()).'</comment>';
} else {
$value = '<comment>'.HelpCommand::toString($value).'</comment>';
}
}
} else {
$allowed = array_map(
static function ($type) {
return '<comment>'.$type.'</comment>';
},
$option->getAllowedTypes()
);
}
if (null !== $allowed) {
$line .= ' ('.implode(', ', $allowed).')';
}
$description = Preg::replace('/(`.+?`)/', '<info>$1</info>', OutputFormatter::escape($option->getDescription()));
$line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; ';
if ($option->hasDefault()) {
$line .= sprintf(
'defaults to <comment>%s</comment>',
HelpCommand::toString($option->getDefault())
);
} else {
$line .= '<comment>required</comment>';
}
if ($option instanceof DeprecatedFixerOption) {
$line .= '. <error>DEPRECATED</error>: '.Preg::replace(
'/(`.+?`)/',
'<info>$1</info>',
OutputFormatter::escape(lcfirst($option->getDeprecationMessage()))
);
}
if ($option instanceof AliasedFixerOption) {
$line .= '; <error>DEPRECATED</error> alias: <comment>'.$option->getAlias().'</comment>';
}
$output->writeln($line);
}
$output->writeln('');
} elseif ($fixer instanceof ConfigurableFixerInterface) {
$output->writeln('<comment>Fixer is configurable.</comment>');
if ($definition->getConfigurationDescription()) {
$output->writeln($definition->getConfigurationDescription());
}
if ($definition->getDefaultConfiguration()) {
$output->writeln(sprintf('Default configuration: <comment>%s</comment>.', 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(
'<comment> ---------- begin diff ----------</comment>%s%%s%s<comment> ----------- end diff -----------</comment>',
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 <comment>default</comment> configuration.', $index + 1));
} else {
$output->writeln(sprintf(' * Example #%d. Fixing with configuration: <comment>%s</comment>.', $index + 1, HelpCommand::toString($codeSample->getConfiguration())));
}
} else {
$output->writeln(sprintf(' * Example #%d.', $index + 1));
}
$output->writeln([$diffFormatter->format($diff, ' %s'), '']);
}
}
}
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('<info>Description of the</info> %s <info>set.</info>', $ruleSetDefinitions[$name]->getName()));
$output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription()));
if ($ruleSetDefinitions[$name]->isRisky()) {
$output->writeln('This set contains <error>risky</error> rules.');
}
$output->writeln('');
$help = '';
foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) {
if ('@' === $rule[0]) {
$set = $ruleSetDefinitions[$rule];
$help .= sprintf(
" * <info>%s</info>%s\n | %s\n\n",
$rule,
$set->isRisky() ? ' <error>risky</error>' : '',
$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(
" * <info>%s</info>%s\n | %s\n%s\n",
$rule,
$fixer->isRisky() ? ' <error>risky</error>' : '',
$definition->getSummary(),
true !== $config ? sprintf(" <comment>| Configuration: %s</comment>\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 = [
'sets' => $this->getSetNames(),
'rules' => $this->getFixers(),
];
} elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$describe = 'set' === $type ? ['sets' => $this->getSetNames()] : ['rules' => $this->getFixers()];
} else {
return;
}
foreach ($describe as $list => $items) {
$output->writeln(sprintf('<comment>Defined %s:</comment>', $list));
foreach ($items as $name => $item) {
$output->writeln(sprintf('* <info>%s</info>', \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
);
}
}
<?php
namespace PhpCsFixer\Console\SelfUpdate;
interface NewVersionCheckerInterface
{
public function getLatestVersion();
public function getLatestVersionOfMajor($majorVersion);
public function compareVersions($versionA, $versionB);
}
<?php
namespace PhpCsFixer\Console\SelfUpdate;
interface GithubClientInterface
{
public function getTags();
}
<?php
namespace PhpCsFixer\Console\SelfUpdate;
use Composer\Semver\Comparator;
use Composer\Semver\Semver;
use Composer\Semver\VersionParser;
final class NewVersionChecker implements NewVersionCheckerInterface
{
private $githubClient;
private $versionParser;
private $availableVersions;
public function __construct(GithubClientInterface $githubClient)
{
$this->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);
}
}
<?php
namespace PhpCsFixer\Console\SelfUpdate;
final class GithubClient implements GithubClientInterface
{
public function getTags()
{
$url = 'https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/tags';
$result = @file_get_contents(
$url,
false,
stream_context_create([
'http' => [
'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;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractProxyFixer extends AbstractFixer
{
protected $proxyFixers;
public function __construct()
{
foreach (Utils::sortFixers($this->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();
}
<?php
namespace PhpCsFixer;
final class RuleSet extends RuleSet\RuleSet
{
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\RuleSet\RuleSetInterface;
use Symfony\Component\Finder\Finder as SymfonyFinder;
use Symfony\Component\Finder\SplFileInfo;
final class FixerFactory
{
private $nameValidator;
private $fixers = [];
private $fixersByName = [];
public function __construct()
{
$this->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'],
'single_import_per_statement' => ['group_import'],
];
$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;
}
}
<?php
namespace PhpCsFixer;
final class PharChecker implements PharCheckerInterface
{
public function checkFileValidity($filename)
{
try {
$phar = new \Phar($filename);
unset($phar);
} catch (\Exception $e) {
if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
throw $e;
}
return 'Failed to create Phar instance. '.$e->getMessage();
}
return null;
}
}
<?php
namespace PhpCsFixer\Runner;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Linter\LintingResultInterface;
final class FileCachingLintingIterator extends \CachingIterator
{
private $currentResult;
private $linter;
private $nextResult;
public function __construct(\Iterator $iterator, LinterInterface $linter)
{
parent::__construct($iterator);
$this->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());
}
}
<?php
namespace PhpCsFixer\Runner;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Cache\CacheManagerInterface;
use PhpCsFixer\Cache\Directory;
use PhpCsFixer\Cache\DirectoryInterface;
use PhpCsFixer\Differ\DifferInterface;
use PhpCsFixer\Error\Error;
use PhpCsFixer\Error\ErrorsManager;
use PhpCsFixer\Event\Event;
use PhpCsFixer\FileReader;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerFileProcessedEvent;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Linter\LintingException;
use PhpCsFixer\Linter\LintingResultInterface;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Filesystem\Exception\IOException;
final class Runner
{
private $differ;
private $directory;
private $eventDispatcher;
private $errorsManager;
private $cacheManager;
private $isDryRun;
private $linter;
private $finder;
private $fixers;
private $stopOnViolation;
public function __construct(
$finder,
array $fixers,
DifferInterface $differ,
EventDispatcherInterface $eventDispatcher = null,
ErrorsManager $errorsManager,
LinterInterface $linter,
$isDryRun,
CacheManagerInterface $cacheManager,
DirectoryInterface $directory = null,
$stopOnViolation = false
) {
$this->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);
}
}
<?php
namespace PhpCsFixer\Runner;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Linter\LintingResultInterface;
final class FileLintingIterator extends \IteratorIterator
{
private $currentResult;
private $linter;
public function __construct(\Iterator $iterator, LinterInterface $linter)
{
parent::__construct($iterator);
$this->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());
}
}
<?php
namespace PhpCsFixer\Runner;
use PhpCsFixer\Cache\CacheManagerInterface;
use PhpCsFixer\Event\Event;
use PhpCsFixer\FileReader;
use PhpCsFixer\FixerFileProcessedEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
final class FileFilterIterator extends \FilterIterator
{
private $eventDispatcher;
private $cacheManager;
private $visitedElements = [];
public function __construct(
\Traversable $iterator,
EventDispatcherInterface $eventDispatcher = null,
CacheManagerInterface $cacheManager
) {
if (!$iterator instanceof \Iterator) {
$iterator = new \IteratorIterator($iterator);
}
parent::__construct($iterator);
$this->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);
}
}
<?php
namespace PhpCsFixer;
interface RuleSetInterface extends \PhpCsFixer\RuleSet\RuleSetInterface
{
}
<?php
namespace PhpCsFixer\Linter;
use PhpCsFixer\FileReader;
use PhpCsFixer\FileRemoval;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
final class ProcessLinter implements LinterInterface
{
private $fileRemoval;
private $processBuilder;
private $temporaryFile;
public function __construct($executable = null)
{
if (null === $executable) {
$executableFinder = new PhpExecutableFinder();
$executable = $executableFinder->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 __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
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);
}
}
<?php
namespace PhpCsFixer\Linter;
use Symfony\Component\Process\Process;
final class ProcessLintingResult implements LintingResultInterface
{
private $isSuccessful;
private $process;
private $path;
public function __construct(Process $process, $path = null)
{
$this->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;
}
}
<?php
namespace PhpCsFixer\Linter;
interface LintingResultInterface
{
public function check();
}
<?php
namespace PhpCsFixer\Linter;
class LintingException extends \RuntimeException
{
}
<?php
namespace PhpCsFixer\Linter;
use Symfony\Component\Process\Process;
final class ProcessLinterProcessBuilder
{
private $executable;
public function __construct($executable)
{
$this->executable = $executable;
}
public function build($path)
{
return new Process([
$this->executable,
'-l',
$path,
]);
}
}
<?php
namespace PhpCsFixer\Linter;
use PhpCsFixer\FileReader;
use PhpCsFixer\Tokenizer\CodeHasher;
use PhpCsFixer\Tokenizer\Tokens;
final class TokenizerLinter implements LinterInterface
{
public function __construct()
{
if (false === \defined('TOKEN_PARSE') || false === class_exists(\CompileError::class)) {
throw new UnavailableLinterException('Cannot use tokenizer as linter.');
}
}
public function isAsync()
{
return false;
}
public function lintFile($path)
{
return $this->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);
}
}
}
<?php
namespace PhpCsFixer\Linter;
class UnavailableLinterException extends \RuntimeException
{
}
<?php
namespace PhpCsFixer\Linter;
final class Linter implements LinterInterface
{
private $sublinter;
public function __construct($executable = null)
{
try {
$this->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);
}
}
<?php
namespace PhpCsFixer\Linter;
final class TokenizerLintingResult implements LintingResultInterface
{
private $error;
public function __construct(\Error $error = null)
{
$this->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';
}
}
<?php
namespace PhpCsFixer\Linter;
final class CachingLinter implements LinterInterface
{
private $sublinter;
private $cache = [];
public function __construct(LinterInterface $linter)
{
$this->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];
}
}
<?php
namespace PhpCsFixer\Linter;
interface LinterInterface
{
public function isAsync();
public function lintFile($path);
public function lintSource($source);
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractNoUselessElseFixer extends AbstractFixer
{
public function getPriority()
{
return 25;
}
protected function isSuperfluousElse(Tokens $tokens, $index)
{
$previousBlockStart = $index;
do {
list($previousBlockStart, $previousBlockEnd) = $this->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;
}
}
<?php
namespace PhpCsFixer\DocBlock;
use PhpCsFixer\Preg;
class DocBlock
{
private $lines = [];
private $annotations;
public function __construct($content)
{
foreach (Preg::split('/([^\n\r]+\R*)/', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $line) {
$this->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);
}
}
<?php
namespace PhpCsFixer\DocBlock;
class TagComparator
{
private static $groups = [
['deprecated', 'link', 'see', 'since'],
['author', 'copyright', 'license'],
['category', 'package', 'subpackage'],
['property', 'property-read', 'property-write'],
];
public static function shouldBeTogether(Tag $first, Tag $second)
{
$firstName = $first->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;
}
}
<?php
namespace PhpCsFixer\DocBlock;
use PhpCsFixer\Preg;
class Line
{
private $content;
public function __construct($content)
{
$this->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];
}
}
<?php
namespace PhpCsFixer\DocBlock;
use PhpCsFixer\Preg;
class Tag
{
private static $tags = [
'api', 'author', 'category', 'copyright', 'deprecated', 'example',
'global', 'internal', 'license', 'link', 'method', 'package', 'param',
'property', 'property-read', 'property-write', 'return', 'see',
'since', 'subpackage', 'throws', 'todo', 'uses', 'var', 'version',
];
private $line;
private $name;
public function __construct(Line $line)
{
$this->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);
}
}
<?php
namespace PhpCsFixer\DocBlock;
final class ShortDescription
{
private $doc;
public function __construct(DocBlock $doc)
{
$this->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;
}
}
<?php
namespace PhpCsFixer\DocBlock;
use PhpCsFixer\Preg;
/**
@gmail
*/
class Annotation
{
const REGEX_TYPES = '
# <simple> is any non-array, non-generic, non-alternated type, eg `int` or `\Foo`
# <array> is array of <simple>, eg `int[]` or `\Foo[]`
# <generic> is generic collection type, like `array<string, int>`, `Collection<Item>` and more complex like `Collection<int, \null|SubCollection<string>>`
# <type> is <simple>, <array> or <generic> type, like `int`, `bool[]` or `Collection<ItemKey, ItemVal>`
# <types> is one or more types alternated via `|`, like `int|bool[]|Collection<ItemKey, ItemVal>`
(?<types>
(?<type>
(?<array>
(?&simple)(\[\])*
)
|
(?<simple>
[@$?]?[\\\\\w]+
)
|
(?<generic>
(?&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;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractLinesBeforeNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
protected function fixLinesBeforeNamespace(Tokens $tokens, $index, $expectedMin, $expectedMax)
{
$openingTokenIndex = null;
$precedingNewlines = 0;
$newlineInOpening = false;
$openingToken = null;
for ($i = 1; $i <= 2; ++$i) {
if (isset($tokens[$index - $i])) {
$token = $tokens[$index - $i];
if ($token->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)]));
}
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class FixerConfigurationResolverRootless implements FixerConfigurationResolverInterface
{
private $resolver;
private $root;
private $fixerName;
public function __construct($root, $options, $fixerName)
{
$this->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);
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class DeprecatedFixerOption implements DeprecatedFixerOptionInterface
{
private $option;
private $deprecationMessage;
public function __construct(FixerOptionInterface $option, $deprecationMessage)
{
$this->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;
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class FixerOption implements FixerOptionInterface
{
private $name;
private $description;
private $default;
private $isRequired;
private $allowedTypes;
private $allowedValues;
private $normalizer;
public function __construct(
$name,
$description,
$isRequired = true,
$default = null,
array $allowedTypes = null,
array $allowedValues = null,
\Closure $normalizer = null
) {
if ($isRequired && null !== $default) {
throw new \LogicException('Required options cannot have a default value.');
}
if (null !== $allowedValues) {
foreach ($allowedValues as &$allowedValue) {
if ($allowedValue instanceof \Closure) {
$allowedValue = $this->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);
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class FixerOptionBuilder
{
private $name;
private $description;
private $default;
private $isRequired = true;
private $allowedTypes;
private $allowedValues;
private $normalizer;
private $deprecationMessage;
public function __construct($name, $description)
{
$this->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;
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
interface FixerConfigurationResolverInterface
{
public function getOptions();
public function resolve(array $configuration);
}
<?php
namespace PhpCsFixer\FixerConfiguration;
interface FixerOptionInterface
{
public function getName();
public function getDescription();
public function hasDefault();
public function getDefault();
public function getAllowedTypes();
public function getAllowedValues();
public function getNormalizer();
}
<?php
namespace PhpCsFixer\FixerConfiguration;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;
final class FixerConfigurationResolver implements FixerConfigurationResolverInterface
{
private $options = [];
private $registeredNames = [];
public function __construct($options)
{
foreach ($options as $option) {
$this->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;
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class AliasedFixerOptionBuilder
{
private $optionBuilder;
private $alias;
public function __construct(FixerOptionBuilder $optionBuilder, $alias)
{
$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
);
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class AllowedValueSubset
{
private $allowedValues;
public function __construct(array $allowedValues)
{
$this->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;
}
}
<?php
namespace PhpCsFixer\FixerConfiguration;
interface DeprecatedFixerOptionInterface extends FixerOptionInterface
{
public function getDeprecationMessage();
}
<?php
namespace PhpCsFixer\FixerConfiguration;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class InvalidOptionsForEnvException extends InvalidOptionsException
{
}
<?php
namespace PhpCsFixer\FixerConfiguration;
final class AliasedFixerOption implements FixerOptionInterface
{
private $fixerOption;
private $alias;
public function __construct(FixerOptionInterface $fixerOption, $alias)
{
$this->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();
}
}
<?php
namespace PhpCsFixer\Differ;
final class NullDiffer implements DifferInterface
{
public function diff($old, $new)
{
return '';
}
}
<?php
namespace PhpCsFixer\Differ;
use PhpCsFixer\Diff\v3_0\Differ;
use PhpCsFixer\Diff\v3_0\Output\StrictUnifiedDiffOutputBuilder;
final class UnifiedDiffer implements DifferInterface
{
private $differ;
public function __construct()
{
$this->differ = new Differ(new StrictUnifiedDiffOutputBuilder([
'fromFile' => 'Original',
'toFile' => 'New',
]));
}
public function diff($old, $new)
{
return $this->differ->diff($old, $new);
}
}
<?php
namespace PhpCsFixer\Differ;
use PhpCsFixer\Diff\v3_0\Differ;
use PhpCsFixer\Diff\v3_0\Output\StrictUnifiedDiffOutputBuilder;
final class FullDiffer implements DifferInterface
{
private $differ;
public function __construct()
{
$this->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);
}
}
<?php
namespace PhpCsFixer\Differ;
use PhpCsFixer\Diff\v1_4\Differ;
final class SebastianBergmannDiffer implements DifferInterface
{
private $differ;
public function __construct()
{
$this->differ = new Differ();
}
public function diff($old, $new)
{
return $this->differ->diff($old, $new);
}
}
<?php
namespace PhpCsFixer\Differ;
use PhpCsFixer\Preg;
use Symfony\Component\Console\Formatter\OutputFormatter;
final class DiffConsoleFormatter
{
private $isDecoratedOutput;
private $template;
public function __construct($isDecoratedOutput, $template = '%s')
{
$this->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('<fg=%s>%s</fg=%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)
)
)
);
}
}
<?php
namespace PhpCsFixer\Differ;
use PhpCsFixer\Diff\v1_4\Differ;
final class SebastianBergmannShortDiffer implements DifferInterface
{
private $differ;
public function __construct()
{
$this->differ = new Differ("--- Original\n+++ New\n", false);
}
public function diff($old, $new)
{
return $this->differ->diff($old, $new);
}
}
<?php
namespace PhpCsFixer\Differ;
interface DifferInterface
{
public function diff($old, $new);
}
<?php
namespace PhpCsFixer\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
if (is_subclass_of(EventDispatcher::class, EventDispatcherInterface::class)) {
class Event extends \Symfony\Contracts\EventDispatcher\Event
{
}
} else {
class Event extends \Symfony\Component\EventDispatcher\Event
{
}
}
<?php
namespace PhpCsFixer;
interface ToolInfoInterface
{
public function getComposerInstallationDetails();
public function getComposerVersion();
public function getVersion();
public function isInstalledAsPhar();
public function isInstalledByComposer();
public function getPharDownloadUri($version);
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Fixer\FixerInterface;
/**
@gmail
*/
interface ConfigInterface
{
public function getCacheFile();
public function getCustomFixers();
public function getFinder();
public function getFormat();
public function getHideProgress();
public function getIndent();
public function getLineEnding();
public function getName();
public function getPhpExecutable();
public function getRiskyAllowed();
public function getRules();
public function getUsingCache();
public function registerCustomFixers($fixers);
public function setCacheFile($cacheFile);
public function setFinder($finder);
public function setFormat($format);
public function setHideProgress($hideProgress);
public function setIndent($indent);
public function setLineEnding($lineEnding);
public function setPhpExecutable($phpExecutable);
public function setRiskyAllowed($isRiskyAllowed);
public function setRules(array $rules);
public function setUsingCache($usingCache);
}
<?php
namespace PhpCsFixer;
interface PharCheckerInterface
{
public function checkFileValidity($filename);
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Console\Application;
final class ToolInfo implements ToolInfoInterface
{
const COMPOSER_PACKAGE_NAME = 'friendsofphp/php-cs-fixer';
const COMPOSER_LEGACY_PACKAGE_NAME = 'fabpot/php-cs-fixer';
private $composerInstallationDetails;
private $isInstalledByComposer;
public function getComposerInstallationDetails()
{
if (!$this->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';
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractAlignFixerHelper
{
/**
@const
*/
const ALIGNABLE_PLACEHOLDER = "\x2 ALIGNABLE%d \x3";
protected $deepestLevel = 0;
public function fix(Tokens $tokens)
{
$tokensClone = clone $tokens;
$this->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;
}
}
<?php
namespace PhpCsFixer;
use Symfony\Component\Finder\Finder as BaseFinder;
/**
@gmail
*/
class Finder extends BaseFinder
{
public function __construct()
{
parent::__construct();
$this
->files()
->name('*.php')
->exclude('vendor')
;
}
}
<?php
namespace PhpCsFixer;
final class WordMatcher
{
private $candidates;
public function __construct(array $candidates)
{
$this->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;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractFopenFlagFixer extends AbstractFunctionReferenceFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer;
final class StdinFileInfo extends \SplFileInfo
{
public function __construct()
{
}
public function __toString()
{
return $this->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)
{
}
}
<?php
namespace PhpCsFixer\Error;
final class ErrorsManager
{
private $errors = [];
public function getInvalidErrors()
{
return array_filter($this->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;
}
}
<?php
namespace PhpCsFixer\Error;
final class Error
{
const TYPE_INVALID = 1;
const TYPE_EXCEPTION = 2;
const TYPE_LINT = 3;
private $type;
private $filePath;
private $source;
private $appliedFixers;
private $diff;
public function __construct($type, $filePath, $source = null, array $appliedFixers = [], $diff = null)
{
$this->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;
}
}
<?php
namespace PhpCsFixer;
/**
@gmail
*/
final class FileRemoval
{
private $files = [];
public function __construct()
{
register_shutdown_function([$this, 'clean']);
}
public function __destruct()
{
$this->clean();
}
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
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);
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Fixer\FixerInterface;
/**
@gmail
@gmail
*/
class Config implements ConfigInterface
{
private $cacheFile = '.php_cs.cache';
private $customFixers = [];
private $finder;
private $format = 'txt';
private $hideProgress = false;
private $indent = ' ';
private $isRiskyAllowed = false;
private $lineEnding = "\n";
private $name;
private $phpExecutable;
private $rules = ['@PSR2' => true];
private $usingCache = true;
public function __construct($name = 'default')
{
$this->name = $name;
}
public static function create()
{
@trigger_error(__METHOD__.' is deprecated since 2.17 and will be removed in 3.0.', E_USER_DEPRECATED);
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;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractPhpdocTypesFixer extends AbstractFixer
{
protected $tags;
public function __construct()
{
parent::__construct();
$this->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);
}
}
<?php
namespace PhpCsFixer;
final class WhitespacesFixerConfig
{
private $indent;
private $lineEnding;
public function __construct($indent = ' ', $lineEnding = "\n")
{
if (!\in_array($indent, [' ', ' ', "\t"], true)) {
throw new \InvalidArgumentException('Invalid "indent" param, expected tab or two or four spaces.');
}
if (!\in_array($lineEnding, ["\n", "\r\n"], true)) {
throw new \InvalidArgumentException('Invalid "lineEnding" param, expected "\n" or "\r\n".');
}
$this->indent = $indent;
$this->lineEnding = $lineEnding;
}
public function getIndent()
{
return $this->indent;
}
public function getLineEnding()
{
return $this->lineEnding;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractFunctionReferenceFixer extends AbstractFixer
{
public function isRisky()
{
return true;
}
protected function find($functionNameToSearch, Tokens $tokens, $start = 0, $end = null)
{
$end = null === $end ? $tokens->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)];
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class SingleBlankLineAtEofFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'A PHP file without end tag must always end with a single empty line feed.',
[
new CodeSample("<?php\n\$a = 1;"),
new CodeSample("<?php\n\$a = 1;\n\n"),
]
);
}
public function getPriority()
{
return -50;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$count = $tokens->count();
if ($count && !$tokens[$count - 1]->isGivenKind([T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG])) {
$tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding());
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class NoSpacesAroundOffsetFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST NOT be spaces around offset braces.',
[
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n"),
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n", ['positions' => ['inside']]),
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n", ['positions' => ['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());
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class MethodChainingIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Method chaining MUST be properly indented. Method chaining with different levels of indentation is not supported.',
[new CodeSample("<?php\n\$user->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
;
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class NoTrailingWhitespaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Remove trailing whitespace at the end of non-blank lines.',
[new CodeSample("<?php\n\$a = 1; \n")]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = \count($tokens) - 1; $index >= 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);
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class IndentationTypeFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
private $indent;
public function getDefinition()
{
return new FixerDefinition(
'Code MUST use configured indentation type.',
[
new CodeSample("<?php\n\nif (true) {\n\techo 'Hello!';\n}\n"),
]
);
}
public function getPriority()
{
return 50;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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('/^(?:(?<! ) {1,3})?\t/m', '\1 ', $tokens[$index]->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('/(?:(?<! ) {1,3})?\t/', ' ', $matches[2]);
return $matches[1].$this->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
@localheinz
*/
final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private static $tokenMap = [
'break' => 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 __construct()
{
parent::__construct();
if (\defined('T_YIELD_FROM')) {
self::$tokenMap['yield_from'] = T_YIELD_FROM;
}
}
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->fixTokenMap = [];
foreach ($this->configuration['statements'] as $key) {
if ('die' === $key) {
@trigger_error('Option "die" is deprecated, use "exit" instead.', E_USER_DEPRECATED);
}
$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(
'<?php
function A() {
echo 1;
return 1;
}
'
),
new CodeSample(
'<?php
switch ($foo) {
case 42:
$bar->process();
break;
case 44:
break;
}
',
[
'statements' => ['break'],
]
),
new CodeSample(
'<?php
foreach ($foo as $bar) {
if ($bar->isTired()) {
$bar->sleep();
continue;
}
}
',
[
'statements' => ['continue'],
]
),
new CodeSample(
'<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
',
[
'statements' => ['do'],
]
),
new CodeSample(
'<?php
if ($foo === false) {
exit(0);
} else {
$bar = 9000;
exit(1);
}
',
[
'statements' => ['exit'],
]
),
new CodeSample(
'<?php
a:
if ($foo === false) {
goto a;
} else {
$bar = 9000;
goto b;
}
',
[
'statements' => ['goto'],
]
),
new CodeSample(
'<?php
$a = 9000;
if (true) {
$foo = $bar;
}
',
[
'statements' => ['if'],
]
),
new CodeSample(
'<?php
if (true) {
$foo = $bar;
return;
}
',
[
'statements' => ['return'],
]
),
new CodeSample(
'<?php
$a = 9000;
switch ($a) {
case 42:
break;
}
',
[
'statements' => ['switch'],
]
),
new CodeSample(
'<?php
if (null === $a) {
$foo->bar();
throw new \UnexpectedValueException("A cannot be null.");
}
',
[
'statements' => ['throw'],
]
),
new CodeSample(
'<?php
$a = 9000;
try {
$foo->bar();
} catch (\Exception $exception) {
$a = -1;
}
',
[
'statements' => ['try'],
]
),
new CodeSample(
'<?php
if (true) {
$foo = $bar;
yield $foo;
}
',
[
'statements' => ['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()
{
$allowed = self::$tokenMap;
$allowed['yield_from'] = true;
ksort($allowed);
$allowed = array_keys($allowed);
return new FixerConfigurationResolver([
(new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.'))
->setAllowedTypes(['array'])
->setAllowedValues([new AllowedValueSubset($allowed)])
->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]));
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoSpacesInsideParenthesisFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.',
[
new CodeSample("<?php\nif ( \$a ) {\n foo( );\n}\n"),
new CodeSample(
"<?php
function foo( \$bar, \$baz )
{
}\n"
),
]
);
}
public function getPriority()
{
return 2;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class CompactNullableTypehintFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Remove extra spaces in a nullable typehint.',
[
new VersionSpecificCodeSample(
"<?php\nfunction sample(? string \$str): ? string\n{}\n",
new VersionSpecification(70100)
),
],
'Rule is applied only in a PHP 7.1+ environment.'
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
final class NoExtraConsecutiveBlankLinesFixer extends AbstractProxyFixer implements ConfigurationDefinitionFixerInterface, DeprecatedFixerInterface, WhitespacesAwareFixerInterface
{
private $fixer;
public function getDefinition()
{
return $this->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Options;
final class NoExtraBlankLinesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private static $availableTokens = [
'break',
'case',
'continue',
'curly_brace_block',
'default',
'extra',
'parenthesis_brace_block',
'return',
'square_brace_block',
'switch',
'throw',
'use',
'useTrait',
'use_trait',
];
private $tokenKindCallbackMap;
private $tokenEqualsMap;
private $tokens;
private $tokensAnalyzer;
public function configure(array $configuration = null)
{
parent::configure($configuration);
static $reprToTokenMap = [
'break' => 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 => 'fixAfterThrowToken',
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(
'<?php
$foo = array("foo");
$bar = "bar";
'
),
new CodeSample(
'<?php
switch ($foo) {
case 41:
echo "foo";
break;
case 42:
break;
}
',
['tokens' => ['break']]
),
new CodeSample(
'<?php
for ($i = 0; $i < 9000; ++$i) {
if (true) {
continue;
}
}
',
['tokens' => ['continue']]
),
new CodeSample(
'<?php
for ($i = 0; $i < 9000; ++$i) {
echo $i;
}
',
['tokens' => ['curly_brace_block']]
),
new CodeSample(
'<?php
$foo = array("foo");
$bar = "bar";
',
['tokens' => ['extra']]
),
new CodeSample(
'<?php
$foo = array(
"foo"
);
',
['tokens' => ['parenthesis_brace_block']]
),
new CodeSample(
'<?php
function foo($bar)
{
return $bar;
}
',
['tokens' => ['return']]
),
new CodeSample(
'<?php
$foo = [
"foo"
];
',
['tokens' => ['square_brace_block']]
),
new CodeSample(
'<?php
function foo($bar)
{
throw new \Exception("Hello!");
}
',
['tokens' => ['throw']]
),
new CodeSample(
'<?php
namespace Foo;
use Bar\Baz;
use Baz\Bar;
class Bar
{
}
',
['tokens' => ['use']]
),
new CodeSample(
'<?php
class Foo
{
use Bar;
use Baz;
}
',
['tokens' => ['use_trait']]
),
new CodeSample(
'<?php
switch($a) {
case 1:
default:
echo 3;
}
',
['tokens' => ['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 fixAfterThrowToken($index)
{
if ($this->tokens[$this->tokens->getPrevMeaningfulToken($index)]->equalsAny([';', '{', '}', ':', [T_OPEN_TAG]])) {
$this->fixAfterToken($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;
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class LineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return true;
}
public function getDefinition()
{
return new FixerDefinition(
'All PHP files must use same line ending.',
[
new CodeSample(
"<?php \$b = \" \$a \r\n 123\"; \$a = <<<TEST\r\nAAAAA \r\n |\r\nTEST;\n"
),
]
);
}
public function getPriority()
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$ending = $this->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()
),
]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoWhitespaceInBlankLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Remove trailing whitespace at the end of blank lines.',
[new CodeSample("<?php\n \n\$a = 1;\n")]
);
}
public function getPriority()
{
return -19;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($i = 1, $count = \count($tokens); $i < $count; ++$i) {
if ($tokens[$i]->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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class HeredocIndentationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Heredoc/nowdoc content must be properly indented. Requires PHP >= 7.3.',
[
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
$a = <<<EOD
abc
def
EOD;
SAMPLE
,
new VersionSpecification(70300)
),
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
$a = <<<'EOD'
abc
def
EOD;
SAMPLE
,
new VersionSpecification(70300)
),
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
$a = <<<'EOD'
abc
def
EOD;
SAMPLE
,
new VersionSpecification(70300),
['indentation' => 'same_as_start']
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 70300 && $tokens->isTokenKindFound(T_START_HEREDOC);
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('indentation', 'Whether the indentation should be the same as in the start token line or one level more.'))
->setAllowedValues(['start_plus_one', 'same_as_start'])
->setDefault('start_plus_one')
->getOption(),
]);
}
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);
if ('start_plus_one' === $this->configuration['indentation']) {
$indent .= $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 '';
}
}
<?php
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Each element of an array must be indented exactly once.',
[
new CodeSample("<?php\n\$foo = [\n 'bar' => [\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;
}
}
<?php
namespace PhpCsFixer\Fixer\Strict;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class StrictParamFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Functions should be used with `$strict` param set to `true`.',
[new CodeSample("<?php\n\$a = array_keys(\$b);\n\$a = array_search(\$b, \$c);\n\$a = base64_decode(\$b);\n\$a = in_array(\$b, \$c);\n\$a = mb_detect_encoding(\$b, \$c);\n")],
'The functions "array_keys", "array_search", "base64_decode", "in_array" and "mb_detect_encoding" should be used with $strict param.',
'Risky when the fixed function is overridden or if the code relies on non-strict usage.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\Strict;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class StrictComparisonFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Comparisons should be strict.',
[new CodeSample("<?php\n\$a = 1== \$b;\n")],
null,
'Changing comparisons to strict might change code behavior.'
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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']]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Strict;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class DeclareStrictTypesFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Force strict types declaration in all files. Requires PHP >= 7.0.',
[
new VersionSpecificCodeSample(
"<?php\n",
new VersionSpecification(70000)
),
],
null,
'Forcing strict types will stop non strict code from working.'
);
}
public function getPriority()
{
return 2;
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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")]);
}
}
<?php
namespace PhpCsFixer\Fixer\DoctrineAnnotation;
use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
final class DoctrineAnnotationSpacesFixer extends AbstractDoctrineAnnotationFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Fixes spaces in Doctrine annotations.',
[
new CodeSample(
"<?php\n/**\n * @Foo ( )\n */\nclass Bar {}\n\n/**\n * @Foo(\"bar\" ,\"baz\")\n */\nclass Bar2 {}\n\n/**\n * @Foo(foo = \"foo\", bar = {\"foo\":\"foo\", \"bar\"=\"bar\"})\n */\nclass Bar3 {}\n"
),
new CodeSample(
"<?php\n/**\n * @Foo(foo = \"foo\", bar = {\"foo\":\"foo\", \"bar\"=\"bar\"})\n */\nclass Bar {}\n",
['after_array_assignments_equals' => 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();
}
}
}
<?php
namespace PhpCsFixer\Fixer\DoctrineAnnotation;
use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\Tokens;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class DoctrineAnnotationArrayAssignmentFixer extends AbstractDoctrineAnnotationFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Doctrine annotations must use configured operator for assignment in arrays.',
[
new CodeSample(
"<?php\n/**\n * @Foo({bar : \"baz\"})\n */\nclass Bar {}\n"
),
new CodeSample(
"<?php\n/**\n * @Foo({bar = \"baz\"})\n */\nclass Bar {}\n",
['operator' => ':']
),
]
);
}
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']);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\DoctrineAnnotation;
use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\Tokens;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
final class DoctrineAnnotationIndentationFixer extends AbstractDoctrineAnnotationFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Doctrine annotations must be indented with four spaces.',
[
new CodeSample("<?php\n/**\n * @Foo(\n * foo=\"foo\"\n * )\n */\nclass Bar {}\n"),
new CodeSample(
"<?php\n/**\n * @Foo({@Bar,\n * @Baz})\n */\nclass Bar {}\n",
['indent_mixed_lines' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\DoctrineAnnotation;
use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Doctrine annotations without arguments must use the configured syntax.',
[
new CodeSample(
"<?php\n/**\n * @Foo()\n */\nclass Bar {}\n"
),
new CodeSample(
"<?php\n/**\n * @Foo\n */\nclass Bar {}\n",
['syntax' => '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();
}
}
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
interface DefinedFixerInterface extends FixerInterface
{
public function getDefinition();
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class GlobalNamespaceImportFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Imports or fully qualifies global classes/functions/constants.',
[
new CodeSample(
'<?php
namespace Foo;
$d = new \DateTimeImmutable();
'
),
new CodeSample(
'<?php
namespace Foo;
if (\count($x)) {
/** @var \DateTimeImmutable $d */
$d = new \DateTimeImmutable();
$p = \M_PI;
}
',
['import_classes' => true, 'import_constants' => true, 'import_functions' => true]
),
new CodeSample(
'<?php
namespace Foo;
use DateTimeImmutable;
use function count;
use const M_PI;
if (count($x)) {
/** @var DateTimeImmutable $d */
$d = new DateTimeImmutable();
$p = M_PI;
}
',
['import_classes' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUnusedImportsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Unused `use` statements must be removed.',
[new CodeSample("<?php\nuse \\DateTime;\nuse \\Exception;\n\nnew DateTime();\n")]
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'/(?<![[:alnum:]\$])(?<!\\\\)'.$shortName.'(?![[:alnum:]])/i',
$token->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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Generator\NamespacedStringTokenGenerator;
use PhpCsFixer\Tokenizer\Resolver\TypeShortNameResolver;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FullyQualifiedStrictTypesFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Transforms imported FQCN parameters and return types in function arguments to short version.',
[
new CodeSample(
'<?php
use Foo\Bar;
class SomeClass
{
public function doSomething(\Foo\Bar $foo)
{
}
}
'
),
new VersionSpecificCodeSample(
'<?php
use Foo\Bar;
use Foo\Bar\Baz;
class SomeClass
{
public function doSomething(\Foo\Bar $foo): \Foo\Bar\Baz
{
}
}
',
new VersionSpecification(70000)
),
]
);
}
public function getPriority()
{
return 7;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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
);
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class GroupImportFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST be group use for the same namespaces.',
[
new VersionSpecificCodeSample(
"<?php\nuse Foo\\Bar;\nuse Foo\\Baz;\n",
new VersionSpecification(70000)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 70000 && $tokens->isTokenKindFound(T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$useWithSameNamespaces = $this->getSameNamespaces($tokens);
if ([] === $useWithSameNamespaces) {
return;
}
$this->removeSingleUseStatements($useWithSameNamespaces, $tokens);
$this->addGroupUseStatements($useWithSameNamespaces, $tokens);
}
private function getSameNamespaces(Tokens $tokens)
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
if (0 === \count($useDeclarations)) {
return [];
}
$allNamespaces = array_map(
function (NamespaceUseAnalysis $useDeclaration) {
return $this->getNamespaceNameWithSlash($useDeclaration);
},
$useDeclarations
);
$sameNamespaces = array_filter(array_count_values($allNamespaces), function ($count) {
return $count > 1;
});
$sameNamespaces = array_keys($sameNamespaces);
$sameNamespaceAnalysis = array_filter($useDeclarations, function ($useDeclaration) use ($sameNamespaces) {
$namespaceName = $this->getNamespaceNameWithSlash($useDeclaration);
return \in_array($namespaceName, $sameNamespaces, true);
});
sort($sameNamespaceAnalysis);
return $sameNamespaceAnalysis;
}
private function removeSingleUseStatements(array $statements, Tokens $tokens)
{
foreach ($statements as $useDeclaration) {
$index = $useDeclaration->getStartIndex();
$endIndex = $useDeclaration->getEndIndex();
$useStatementTokens = [T_USE, T_WHITESPACE, T_STRING, T_NS_SEPARATOR, T_AS, CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT];
while ($index !== $endIndex) {
if ($tokens[$index]->isGivenKind($useStatementTokens)) {
$tokens->clearAt($index);
}
++$index;
}
if (isset($tokens[$index]) && $tokens[$index]->equals(';')) {
$tokens->clearAt($index);
}
++$index;
if (isset($tokens[$index]) && $tokens[$index]->isGivenKind(T_WHITESPACE)) {
$tokens->clearAt($index);
}
}
}
private function addGroupUseStatements(array $statements, Tokens $tokens)
{
$currentNamespace = '';
$insertIndex = \array_slice($statements, -1)[0]->getEndIndex();
while ($tokens[$insertIndex]->isGivenKind([T_COMMENT, T_DOC_COMMENT])) {
++$insertIndex;
}
foreach ($statements as $index => $useDeclaration) {
$namespace = $this->getNamespaceNameWithSlash($useDeclaration);
if ($currentNamespace !== $namespace) {
if ($index > 1) {
++$insertIndex;
}
$currentNamespace = $namespace;
$insertIndex += $this->createNewGroup($tokens, $insertIndex, $useDeclaration, $currentNamespace);
} else {
$newTokens = [
new Token(','),
new Token([T_WHITESPACE, ' ']),
];
if ($useDeclaration->isAliased()) {
$tokens->insertAt($insertIndex + 1, $newTokens);
$insertIndex += \count($newTokens);
$newTokens = [];
$insertIndex += $this->insertToGroupUseWithAlias($tokens, $insertIndex + 1, $useDeclaration);
}
$newTokens[] = new Token([T_STRING, $useDeclaration->getShortName()]);
if (!isset($statements[$index + 1]) || $this->getNamespaceNameWithSlash($statements[$index + 1]) !== $currentNamespace) {
$newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']);
$newTokens[] = new Token(';');
$newTokens[] = new Token([T_WHITESPACE, "\n"]);
}
$tokens->insertAt($insertIndex + 1, $newTokens);
$insertIndex += \count($newTokens);
}
}
}
private function getNamespaceNameWithSlash(NamespaceUseAnalysis $useDeclaration)
{
return substr($useDeclaration->getFullName(), 0, strripos($useDeclaration->getFullName(), '\\') + 1);
}
private function insertToGroupUseWithAlias(Tokens $tokens, $insertIndex, NamespaceUseAnalysis $useDeclaration)
{
$newTokens = [
new Token([T_STRING, substr($useDeclaration->getFullName(), strripos($useDeclaration->getFullName(), '\\') + 1)]),
new Token([T_WHITESPACE, ' ']),
new Token([T_AS, 'as']),
new Token([T_WHITESPACE, ' ']),
];
$tokens->insertAt($insertIndex, $newTokens);
return \count($newTokens);
}
private function createNewGroup(Tokens $tokens, $insertIndex, NamespaceUseAnalysis $useDeclaration, $currentNamespace)
{
$insertedTokens = 0;
if (\count($tokens) === $insertIndex) {
$tokens->setSize($insertIndex + 1);
}
$newTokens = [
new Token([T_USE, 'use']),
new Token([T_WHITESPACE, ' ']),
];
if ($useDeclaration->isFunction() || $useDeclaration->isConstant()) {
$importStatementParams = $useDeclaration->isFunction()
? [CT::T_FUNCTION_IMPORT, 'function']
: [CT::T_CONST_IMPORT, 'const'];
$newTokens[] = new Token($importStatementParams);
$newTokens[] = new Token([T_WHITESPACE, ' ']);
}
$namespaceParts = array_filter(explode('\\', $currentNamespace));
foreach ($namespaceParts as $part) {
$newTokens[] = new Token([T_STRING, $part]);
$newTokens[] = new Token([T_NS_SEPARATOR, '\\']);
}
$newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']);
$newTokensCount = \count($newTokens);
$tokens->insertAt($insertIndex, $newTokens);
$insertedTokens += $newTokensCount;
$insertIndex += $newTokensCount;
if ($useDeclaration->isAliased()) {
$inserted = $this->insertToGroupUseWithAlias($tokens, $insertIndex + 1, $useDeclaration);
$insertedTokens += $inserted;
$insertIndex += $inserted;
}
$tokens->insertAt($insertIndex + 1, new Token([T_STRING, $useDeclaration->getShortName()]));
++$insertedTokens;
return $insertedTokens;
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class NoLeadingImportSlashFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Remove leading slashes in `use` clauses.',
[new CodeSample("<?php\nnamespace Foo;\nuse \\Bar;\n")]
);
}
public function getPriority()
{
return -20;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, ' ']);
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class SingleImportPerStatementFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST be one use keyword per declaration.',
[new CodeSample("<?php\nuse Foo, Sample, Sample\\Sample as Sample2;\n")]
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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 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('<?php '.implode($ending, $statements));
$importTokens->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 = WhitespacesAnalyzer::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]));
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
@gmail
@matulionis
@gmail
*/
final class OrderedImportsFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const IMPORT_TYPE_CLASS = 'class';
const IMPORT_TYPE_CONST = 'const';
const IMPORT_TYPE_FUNCTION = 'function';
const SORT_ALPHA = 'alpha';
const SORT_LENGTH = 'length';
const SORT_NONE = 'none';
private $supportedSortTypes = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION];
private $supportedSortAlgorithms = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE];
public function getDefinition()
{
return new FixerDefinition(
'Ordering `use` statements.',
[
new CodeSample("<?php\nuse Z; use A;\n"),
new CodeSample(
'<?php
use Acme\Bar;
use Bar1;
use Acme;
use Bar;
',
['sort_algorithm' => self::SORT_LENGTH]
),
new VersionSpecificCodeSample(
"<?php\nuse function AAC;\nuse const AAB;\nuse AAA;\n",
new VersionSpecification(70000)
),
new VersionSpecificCodeSample(
'<?php
use const AAAA;
use const BBB;
use Bar;
use AAC;
use Acme;
use function CCC\AA;
use function DDD;
',
new VersionSpecification(70000),
[
'sort_algorithm' => self::SORT_LENGTH,
'imports_order' => [
self::IMPORT_TYPE_CONST,
self::IMPORT_TYPE_CLASS,
self::IMPORT_TYPE_FUNCTION,
],
]
),
new VersionSpecificCodeSample(
'<?php
use const BBB;
use const AAAA;
use Acme;
use AAC;
use Bar;
use function DDD;
use function CCC\AA;
',
new VersionSpecification(70000),
[
'sort_algorithm' => self::SORT_ALPHA,
'imports_order' => [
self::IMPORT_TYPE_CONST,
self::IMPORT_TYPE_CLASS,
self::IMPORT_TYPE_FUNCTION,
],
]
),
new VersionSpecificCodeSample(
'<?php
use const BBB;
use const AAAA;
use function DDD;
use function CCC\AA;
use Acme;
use AAC;
use Bar;
',
new VersionSpecification(70000),
[
'sort_algorithm' => 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(
'<?php use %s%s;',
self::IMPORT_TYPE_CLASS === $use['importType'] ? '' : ' '.$use['importType'].' ',
$use['namespace']
)
);
$declarationTokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
/**
@alt
*/
final class SingleLineAfterImportsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'<?php
namespace Foo;
use Bar;
use Baz;
final class Example
{
}
'
),
new CodeSample(
'<?php
namespace Foo;
use Bar;
use Baz;
final class Example
{
}
'
),
]
);
}
public function getPriority()
{
return -11;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$ending = $this->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;
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoClosingTagFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'The closing `?>` tag MUST be omitted from files containing only PHP.',
[new CodeSample("<?php\nclass Sample\n{\n}\n?>\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(';'));
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class LinebreakAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Ensure there is no code on the same line as the PHP open tag.',
[new CodeSample("<?php \$a = 1;\n\$b = 3;\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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()]);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class EchoTagSyntaxFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const OPTION_FORMAT = 'format';
const OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY = 'shorten_simple_statements_only';
const OPTION_LONG_FUNCTION = 'long_function';
const FORMAT_SHORT = 'short';
const FORMAT_LONG = 'long';
const LONG_FUNCTION_ECHO = 'echo';
const LONG_FUNCTION_PRINT = 'print';
const SUPPORTED_FORMAT_OPTIONS = [
self::FORMAT_LONG,
self::FORMAT_SHORT,
];
const SUPPORTED_LONGFUNCTION_OPTIONS = [
self::LONG_FUNCTION_ECHO,
self::LONG_FUNCTION_PRINT,
];
public function getDefinition()
{
$sample = <<<'EOT'
<?=1?>
<?php print '2' . '3'; ?>
<?php /* comment */ echo '2' . '3'; ?>
<?php print '2' . '3'; someFunction(); ?>
EOT
;
return new FixerDefinition(
'Replaces short-echo `<?=` with long format `<?php echo`/`<?php print` syntax, or vice-versa.',
[
new CodeSample($sample),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG, self::OPTION_LONG_FUNCTION => self::LONG_FUNCTION_PRINT]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT, self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY => false]),
],
null
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) {
return $tokens->isAnyTokenKindsFound([T_ECHO, T_PRINT]);
}
return $tokens->isTokenKindFound(T_OPEN_TAG_WITH_ECHO);
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(self::OPTION_FORMAT, 'The desired language construct.'))
->setAllowedValues(self::SUPPORTED_FORMAT_OPTIONS)
->setDefault(self::FORMAT_LONG)
->getOption(),
(new FixerOptionBuilder(self::OPTION_LONG_FUNCTION, 'The function to be used to expand the short echo tags'))
->setAllowedValues(self::SUPPORTED_LONGFUNCTION_OPTIONS)
->setDefault(self::LONG_FUNCTION_ECHO)
->getOption(),
(new FixerOptionBuilder(self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY, 'Render short-echo tags only in case of simple code'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) {
$this->longToShort($tokens);
} else {
$this->shortToLong($tokens);
}
}
private function longToShort(Tokens $tokens)
{
$skipWhenComplexCode = $this->configuration[self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY];
$count = $tokens->count();
for ($index = 0; $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind(T_OPEN_TAG)) {
continue;
}
$nextMeaningful = $tokens->getNextMeaningfulToken($index);
if (null === $nextMeaningful) {
return;
}
if (!$tokens[$nextMeaningful]->isGivenKind([T_ECHO, T_PRINT])) {
$index = $nextMeaningful;
continue;
}
if ($skipWhenComplexCode && $this->isComplexCode($tokens, $nextMeaningful + 1)) {
$index = $nextMeaningful;
continue;
}
$newTokens = $this->buildLongToShortTokens($tokens, $index, $nextMeaningful);
$tokens->overrideRange($index, $nextMeaningful, $newTokens);
$count = $tokens->count();
}
}
private function shortToLong(Tokens $tokens)
{
if (self::LONG_FUNCTION_PRINT === $this->configuration[self::OPTION_LONG_FUNCTION]) {
$echoToken = [T_PRINT, 'print'];
} else {
$echoToken = [T_ECHO, 'echo'];
}
$index = -1;
while (true) {
$index = $tokens->getNextTokenOfKind($index, [[T_OPEN_TAG_WITH_ECHO]]);
if (null === $index) {
return;
}
$replace = [new Token([T_OPEN_TAG, '<?php ']), new Token($echoToken)];
if (!$tokens[$index + 1]->isWhitespace()) {
$replace[] = new Token([T_WHITESPACE, ' ']);
}
$tokens->overrideRange($index, $index, $replace);
++$index;
}
}
private function isComplexCode(Tokens $tokens, $index)
{
$semicolonFound = false;
for ($count = $tokens->count(); $index < $count; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_CLOSE_TAG)) {
return false;
}
if (';' === $token->getContent()) {
$semicolonFound = true;
} elseif ($semicolonFound && !$token->isWhitespace()) {
return true;
}
}
return false;
}
private function buildLongToShortTokens(Tokens $tokens, $openTagIndex, $echoTagIndex)
{
$result = [new Token([T_OPEN_TAG_WITH_ECHO, '<?='])];
$start = $tokens->getNextNonWhitespace($openTagIndex);
if ($start === $echoTagIndex) {
return $result;
}
$end = $echoTagIndex - 1;
while ($tokens[$end]->isWhitespace()) {
--$end;
}
for ($index = $start; $index <= $end; ++$index) {
$result[] = clone $tokens[$index];
}
return $result;
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class BlankLineAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line.',
[new CodeSample("<?php \$a = 1;\n\$b = 1;\n")]
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]));
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class NoShortEchoTagFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Replaces short-echo `<?=` with long format `<?php echo` syntax.',
[new CodeSample("<?= \"foo\";\n")]
);
}
public function getPriority()
{
return 0;
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
return [new EchoTagSyntaxFixer()];
}
}
<?php
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FullOpeningTagFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'PHP code must use the long `<?php` tags or short-echo `<?=` tags and not other tag variations.',
[
new CodeSample(
'<?
echo "Hello!";
'
),
]
);
}
public function getPriority()
{
return 98;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokensOrg)
{
$content = $tokensOrg->generateCode();
$newContent = Preg::replace('/<\?(?:phP|pHp|pHP|Php|PhP|PHp|PHP)?(\s|$)/', '<?php$1', $content, -1, $count);
if (!$count) {
return;
}
$tokens = Tokens::fromCode($newContent);
$tokensOldContentLength = 0;
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_OPEN_TAG)) {
$tokenContent = $token->getContent();
if ('<?php' !== strtolower(substr($content, $tokensOldContentLength, 5))) {
$tokenContent = '<? ';
}
$tokensOldContentLength += \strlen($tokenContent);
continue;
}
if ($token->isGivenKind([T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_STRING])) {
$tokenContent = '';
$tokenContentLength = 0;
$parts = explode('<?php', $token->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 ('<?php' === strtolower($originalTokenContent)) {
$tokenContent .= $originalTokenContent;
$tokenContentLength += 5;
} else {
$tokenContent .= '<?';
$tokenContentLength += 2;
}
}
}
$tokens[$index] = new Token([$token->getId(), $tokenContent]);
$token = $tokens[$index];
}
$tokensOldContentLength += \strlen($token->getContent());
}
$tokensOrg->overrideRange(0, $tokensOrg->count() - 1, $tokens);
}
}
<?php
namespace PhpCsFixer\Fixer\ListNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ListSyntaxFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $candidateTokenKind;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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(
"<?php\n[\$sample] = \$array;\n",
new VersionSpecification(70100)
),
new VersionSpecificCodeSample(
"<?php\nlist(\$sample) = \$array;\n",
new VersionSpecification(70100),
['syntax' => '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);
}
}
<?php
namespace PhpCsFixer\Fixer\ReturnNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class SimplifiedNullReturnFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'A return statement wishing to return `void` should not return `null`.',
[
new CodeSample("<?php return null;\n"),
new VersionSpecificCodeSample(
<<<'EOT'
<?php
function foo() { return null; }
function bar(): int { return null; }
function baz(): ?int { return null; }
function xyz(): void { return null; }
EOT
,
new VersionSpecification(70100)
),
]
);
}
public function getPriority()
{
return 16;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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());
}
}
<?php
namespace PhpCsFixer\Fixer\ReturnNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\Whitespace\BlankLineBeforeStatementFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@localheinz
*/
final class BlankLineBeforeReturnFixer extends AbstractProxyFixer implements DeprecatedFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'An empty line feed should precede a return statement.',
[new CodeSample("<?php\nfunction A()\n{\n echo 1;\n return 1;\n}\n")]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new BlankLineBeforeStatementFixer();
$fixer->configure(['statements' => ['return']]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\ReturnNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class ReturnAssignmentFixer extends AbstractFixer
{
private $tokensAnalyzer;
public function getDefinition()
{
return new FixerDefinition(
'Local, dynamic and directly referenced variables should not be assigned and directly returned by a function or method.',
[new CodeSample("<?php\nfunction a() {\n \$a = 1;\n return \$a;\n}\n")]
);
}
public function getPriority()
{
return -15;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound([T_FUNCTION, T_RETURN, T_VARIABLE]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$tokenCount = \count($tokens);
$this->tokensAnalyzer = new TokensAnalyzer($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->tokensAnalyzer->isSuperGlobal($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);
}
}
<?php
namespace PhpCsFixer\Fixer\ReturnNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUselessReturnFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'<?php
function example($b) {
if ($b) {
return;
}
return;
}
'
),
]
);
}
public function getPriority()
{
return -18;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class HashToSlashCommentFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Single line comments should use double slashes `//` and not hash `#`.',
[new CodeSample("<?php # comment\n")]
);
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new SingleLineCommentStyleFixer();
$fixer->configure(['comment_types' => ['hash']]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Tokens;
final class NoEmptyCommentFixer extends AbstractFixer
{
const TYPE_HASH = 1;
const TYPE_DOUBLE_SLASH = 2;
const TYPE_SLASH_ASTERISK = 3;
public function getPriority()
{
return 2;
}
public function getDefinition()
{
return new FixerDefinition(
'There should not be any empty comments.',
[new CodeSample("<?php\n//\n#\n/* */\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class MultilineCommentOpeningClosingFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. Both must end with a single asterisk before the closing slash.',
[
new CodeSample(
<<<'EOT'
<?php
/******
* Multiline comment with arbitrary asterisks count
******/
/**\
* Multiline comment that seems a DocBlock
*/
/**
* DocBlock with arbitrary asterisk count at the end
**/
EOT
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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('/(?<!\\/)\\*{2,}\\/$/', '*/', $newContent);
if ($newContent !== $originalContent) {
$tokens[$index] = new Token([$token->getId(), $newContent]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST be no trailing spaces inside comment or PHPDoc.',
[new CodeSample('<?php
// This is '.'
// a comment. '.'
')]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
final class CommentToPhpdocFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private $ignoredTags = [];
public function isCandidate(Tokens $tokens)
{
return $tokens->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("<?php /* header */ \$x = true; /* @var bool \$isFoo */ \$isFoo = true;\n"),
new CodeSample("<?php\n// @todo do something later\n\$foo = 1;\n\n// @var int \$a\n\$a = foo();\n", ['ignored_tags' => ['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', '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, '/*'), '*/');
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleLineCommentStyleFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $asteriskEnabled;
private $hashEnabled;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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(
'<?php
/* asterisk comment */
$a = 1;
# hash comment
$b = 2;
/*
* multi-line
* comment
*/
$c = 3;
'
),
new CodeSample(
'<?php
/* first comment */
$a = 1;
/*
* second comment
*/
$b = 2;
/*
* third
* comment
*/
$c = 3;
',
['comment_types' => ['asterisk']]
),
new CodeSample(
"<?php # comment\n",
['comment_types' => ['hash']]
),
]
);
}
public function getPriority()
{
return -19;
}
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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
final class HeaderCommentFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const HEADER_PHPDOC = 'PHPDoc';
const HEADER_COMMENT = 'comment';
const HEADER_LOCATION_AFTER_OPEN = 1;
const HEADER_LOCATION_AFTER_DECLARE_STRICT = 2;
const HEADER_LINE_SEPARATION_BOTH = 1;
const HEADER_LINE_SEPARATION_TOP = 2;
const HEADER_LINE_SEPARATION_BOTTOM = 3;
const HEADER_LINE_SEPARATION_NONE = 4;
public function getDefinition()
{
return new FixerDefinition(
'Add, replace or remove header comment.',
[
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
[
'header' => 'Made with love.',
]
),
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
[
'header' => 'Made with love.',
'comment_type' => 'PHPDoc',
'location' => 'after_open',
'separate' => 'bottom',
]
),
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
[
'header' => '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);
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
interface ConfigurationDefinitionFixerInterface extends ConfigurableFixerInterface
{
public function getConfigurationDefinition();
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\PregException;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
final class EregToPregFixer extends AbstractFixer
{
private static $functions = [
['ereg', 'preg_match', ''],
['eregi', 'preg_match', 'i'],
['ereg_replace', 'preg_replace', ''],
['eregi_replace', 'preg_replace', 'i'],
['split', 'preg_split', ''],
['spliti', 'preg_split', 'i'],
];
private static $delimiters = ['/', '#', '!'];
public function getDefinition()
{
return new FixerDefinition(
'Replace deprecated `ereg` regular expression functions with `preg`.',
[new CodeSample("<?php \$x = ereg('[A-Z]');\n")],
null,
'Risky if the `ereg` function is overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurationDefinitionFixerInterface
{
private static $argumentCounts = [
'getrandmax' => [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("<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n"),
new CodeSample(
"<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n",
['replacements' => ['getrandmax' => 'mt_getrandmax']]
),
new CodeSample(
"<?php \$a = rand(\$b, \$c);\n",
['replacements' => ['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());
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ArrayPushFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Converts simple usages of `array_push($x, $y);` to `$x[] = $y;`.',
[new VersionSpecificCodeSample("<?php\narray_push(\$x, \$y);\n", new VersionSpecification(70000))],
null,
'Risky when the function `array_push` is overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 70000 && $tokens->isTokenKindFound(T_STRING) && $tokens->count() > 7;
}
public function isRisky()
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$functionsAnalyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 7; $index > 0; --$index) {
if (!$tokens[$index]->equals([T_STRING, 'array_push'], false)) {
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$callIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
$namespaceSeparatorIndex = null;
if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) {
$namespaceSeparatorIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
}
if (!$tokens[$index]->equalsAny([';', '{', '}', ')', [T_OPEN_TAG]])) {
continue;
}
$openBraceIndex = $tokens->getNextMeaningfulToken($callIndex);
$blockType = Tokens::detectBlockType($tokens[$openBraceIndex]);
if (null === $blockType || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE !== $blockType['type']) {
continue;
}
$closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex);
$afterCloseBraceIndex = $tokens->getNextMeaningfulToken($closeBraceIndex);
if (null !== $afterCloseBraceIndex && !$tokens[$afterCloseBraceIndex]->equalsAny([';', [T_CLOSE_TAG]])) {
continue;
}
$firstArgumentStop = $this->getFirstArgumentEnd($tokens, $openBraceIndex);
$firstArgumentStop = $tokens->getNextMeaningfulToken($firstArgumentStop);
if (!$tokens[$firstArgumentStop]->equals(',')) {
return;
}
$secondArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStop);
$secondArgumentStop = $this->getSecondArgumentEnd($tokens, $secondArgumentStart, $closeBraceIndex);
if (null === $secondArgumentStop) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closeBraceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStop);
$tokens->insertAt(
$firstArgumentStop,
[
new Token('['),
new Token(']'),
new Token([T_WHITESPACE, ' ']),
new Token('='),
]
);
$tokens->clearTokenAndMergeSurroundingWhitespace($openBraceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($callIndex);
if (null !== $namespaceSeparatorIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex);
}
}
}
private function getFirstArgumentEnd(Tokens $tokens, $index)
{
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
while ($nextToken->equalsAny([
'$',
'[',
'(',
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[CT::T_DYNAMIC_PROP_BRACE_OPEN],
[CT::T_DYNAMIC_VAR_BRACE_OPEN],
[CT::T_NAMESPACE_OPERATOR],
[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->getFirstArgumentEnd($tokens, $nextIndex);
}
if ($nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) {
return $this->getFirstArgumentEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex));
}
return $index;
}
private function getSecondArgumentEnd(Tokens $tokens, $index, $endIndex)
{
if ($tokens[$index]->isGivenKind(T_ELLIPSIS)) {
return null;
}
$index = $tokens->getNextMeaningfulToken($index);
for (; $index <= $endIndex; ++$index) {
$blockType = Tokens::detectBlockType($tokens[$index]);
while (null !== $blockType && $blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
$index = $tokens->getNextMeaningfulToken($index);
$blockType = Tokens::detectBlockType($tokens[$index]);
}
if ($tokens[$index]->equals(',') || $tokens[$index]->isGivenKind([T_YIELD, T_YIELD_FROM, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR])) {
return null;
}
}
return $endIndex;
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class NoAliasFunctionsFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $aliases = [];
private static $internalSet = [
'chop' => '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(
'<?php
$a = chop($b);
close($b);
$a = doubleval($b);
$a = fputs($b, $c);
$a = get_required_files();
ini_alter($b, $c);
$a = is_double($b);
$a = is_integer($b);
$a = is_long($b);
$a = is_real($b);
$a = is_writeable($b);
$a = join($glue, $pieces);
$a = key_exists($key, $array);
magic_quotes_runtime($new_setting);
$a = pos($array);
$a = show_source($filename, true);
$a = sizeof($b);
$a = strchr($haystack, $needle);
$a = imap_header($imap_stream, 1);
user_error($message);
mbereg_search_getregs();
'
),
new CodeSample(
'<?php
$a = is_double($b);
mbereg_search_getregs();
',
['sets' => ['@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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoMixedEchoPrintFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public static $defaultConfig = ['use' => '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("<?php print 'example';\n"),
new CodeSample("<?php echo('example');\n", ['use' => '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']);
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SetTypeToCastFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Cast shall be used, not `settype`.',
[
new CodeSample(
'<?php
settype($foo, "integer");
settype($bar, "string");
settype($bar, "null");
'
),
],
null,
'Risky when the `settype` function is overridden or when used as the 2nd or 3rd expression in a `for` loop .'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]->equalsAny([';', '{', '}', [T_OPEN_TAG]])) {
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);
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PowToExponentiationFixer extends AbstractFunctionReferenceFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->count() > 7 && $tokens->isTokenKindFound(T_STRING);
}
public function getDefinition()
{
return new FixerDefinition(
'Converts `pow` to the `**` operator.',
[
new CodeSample(
"<?php\n pow(\$a, 1);\n"
),
],
null,
'Risky when the function `pow` is overridden.'
);
}
public function getPriority()
{
return 3;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$candidates = $this->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class MbStrFunctionsFixer extends AbstractFunctionReferenceFixer
{
private static $functionsMap = [
'str_split' => ['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(
'<?php
$a = strlen($a);
$a = strpos($a, $b);
$a = strrpos($a, $b);
$a = substr($a, $b);
$a = strtolower($a);
$a = strtoupper($a);
$a = stripos($a, $b);
$a = strripos($a, $b);
$a = strstr($a, $b);
$a = stristr($a, $b);
$a = strrchr($a, $b);
$a = substr_count($a, $b);
'
),
],
null,
'Risky when any of the 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->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']]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoAliasLanguageConstructCallFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Master language constructs shall be used instead of aliases.',
[
new CodeSample(
'<?php
die;
'
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_EXIT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_EXIT)) {
continue;
}
if ('exit' === strtolower($token->getContent())) {
continue;
}
$tokens[$index] = new Token([T_EXIT, 'exit']);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class BacktickToShellExecFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound('`');
}
public function getDefinition()
{
return new FixerDefinition(
'Converts backtick operators to `shell_exec` calls.',
[
new CodeSample(
<<<'EOT'
<?php
$plain = `ls -lah`;
$withVar = `ls -lah $var1 ${var2} {$var3} {$var4[0]} {$var5->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);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitMockFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
private $fixCreatePartialMock;
public function getDefinition()
{
return new FixerDefinition(
'Usages of `->getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.',
[
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$mock = $this->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(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$mock1 = $this->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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitNamespacedFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $originalClassRegEx;
private $classMap;
public function getDefinition()
{
$codeSample = '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomething()
{
PHPUnit_Framework_Assert::assertTrue(true);
}
}
';
return new FixerDefinition(
'PHPUnit classes MUST be used in namespaced version, e.g. `\PHPUnit\Framework\TestCase` instead of `\PHPUnit_Framework_TestCase`.',
[
new CodeSample($codeSample),
new CodeSample($codeSample, ['target' => 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);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class PhpUnitMockShortWillReturnFixer extends AbstractPhpUnitFixer
{
const RETURN_METHODS_MAP = [
'returnargument' => '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('<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$someMock = $this->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class PhpUnitDedicateAssertInternalTypeFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
private $typeToDedicatedAssertMap = [
'array' => '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(
'<?php
final class MyTest extends \PHPUnit\Framework\TestCase
{
public function testMe()
{
$this->assertInternalType("array", $var);
$this->assertInternalType("boolean", $var);
}
}
'
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit\Framework\TestCase
{
public function testMe()
{
$this->assertInternalType("array", $var);
$this->assertInternalType("boolean", $var);
}
}
',
['target' => PhpUnitTargetVersion::VERSION_7_5]
),
],
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('('),
]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class PhpUnitTestAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function isRisky()
{
return true;
}
public function getDefinition()
{
return new FixerDefinition(
'Adds or removes @test annotations from tests, following configuration.',
[
new CodeSample('<?php
class Test extends \\PhpUnit\\FrameWork\\TestCase
{
/**
* @test
*/
public function itDoesSomething() {} }'.$this->whitespacesConfig->getLineEnding()),
new CodeSample('<?php
class Test extends \\PhpUnit\\FrameWork\\TestCase
{
public function testItDoesSomething() {}}'.$this->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 createDocBlock(Tokens $tokens, $docBlockIndex)
{
$lineEnd = $this->whitespacesConfig->getLineEnding();
$originalIndent = WhitespacesAnalyzer::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 = WhitespacesAnalyzer::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 = WhitespacesAnalyzer::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'));
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class PhpUnitTestCaseStaticMethodCallsFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
const CALL_TYPE_THIS = 'this';
const CALL_TYPE_SELF = 'self';
const CALL_TYPE_STATIC = 'static';
private $allowedValues = [
self::CALL_TYPE_THIS => 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 = '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testMe()
{
$this->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)
{
$nextIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
return $tokens[$nextIndex]->equals('{')
? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex)
: $nextIndex;
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class PhpUnitSetUpTearDownVisibilityFixer extends AbstractPhpUnitFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Changes the visibility of the `setUp()` and `tearDown()` functions of PHPUnit to `protected`, to match the PHPUnit TestCase.',
[
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
private $hello;
public function setUp()
{
$this->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;
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\Phpdoc\PhpdocOrderByValueFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class PhpUnitOrderedCoversFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Order `@covers` annotation of PHPUnit tests.',
[
new CodeSample(
'<?php
/**
* @covers Foo
* @covers Bar
*/
final class MyTest extends \PHPUnit_Framework_TestCase
{}
'
),
]
);
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new PhpdocOrderByValueFixer();
$fixer->configure([
'annotations' => [
'covers',
],
]);
return [
$fixer,
];
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitSizeClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'All PHPUnit test cases should have `@small`, `@medium` or `@large` annotation to enable run time limits.',
[
new CodeSample("<?php\nclass MyTest extends TestCase {}\n"),
new CodeSample("<?php\nclass MyTest extends TestCase {}\n", ['group' => '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 = WhitespacesAnalyzer::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 addSizeAnnotation(DocBlock $docBlock, Tokens $tokens, $docBlockIndex)
{
$lines = $docBlock->getLines();
$originalIndent = WhitespacesAnalyzer::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 = WhitespacesAnalyzer::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'),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class PhpUnitNoExpectationAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private $fixMessageRegExp;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException FooException
* @expectedExceptionMessageRegExp /foo.*$/
* @expectedExceptionCode 123
*/
function testAaa()
{
aaa();
}
}
'
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException FooException
* @expectedExceptionCode 123
*/
function testBbb()
{
bbb();
}
/**
* @expectedException FooException
* @expectedExceptionMessageRegExp /foo.*$/
*/
function testCcc()
{
ccc();
}
}
',
['target' => 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 = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex);
$paramList = $this->annotationsToParamList($annotations);
$newMethodsCode = '<?php $this->'
.(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 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;
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
final class PhpUnitMethodCasingFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
const CAMEL_CASE = 'camel_case';
const SNAKE_CASE = 'snake_case';
public function getDefinition()
{
return new FixerDefinition(
'Enforce camel (or snake) case for PHPUnit test methods, following configuration.',
[
new CodeSample(
'<?php
class MyTest extends \\PhpUnit\\FrameWork\\TestCase
{
public function test_my_code() {}
}
'
),
new CodeSample(
'<?php
class MyTest extends \\PhpUnit\\FrameWork\\TestCase
{
public function testMyCode() {}
}
',
['case' => 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)
{
$parts = explode('::', $functionName);
$functionNamePart = array_pop($parts);
if (self::CAMEL_CASE === $this->configuration['case']) {
$newFunctionNamePart = $functionNamePart;
$newFunctionNamePart = ucwords($newFunctionNamePart, '_');
$newFunctionNamePart = str_replace('_', '', $newFunctionNamePart);
$newFunctionNamePart = lcfirst($newFunctionNamePart);
} else {
$newFunctionNamePart = Utils::camelCaseToUnderscore($functionNamePart);
}
$parts[] = $newFunctionNamePart;
return implode('::', $parts);
}
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]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use Composer\Semver\Comparator;
final class PhpUnitTargetVersion
{
const VERSION_3_0 = '3.0';
const VERSION_3_2 = '3.2';
const VERSION_3_5 = '3.5';
const VERSION_4_3 = '4.3';
const VERSION_4_8 = '4.8';
const VERSION_5_0 = '5.0';
const VERSION_5_2 = '5.2';
const VERSION_5_4 = '5.4';
const VERSION_5_5 = '5.5';
const VERSION_5_6 = '5.6';
const VERSION_5_7 = '5.7';
const VERSION_6_0 = '6.0';
const VERSION_7_5 = '7.5';
const VERSION_8_4 = '8.4';
const VERSION_NEWEST = 'newest';
private function __construct()
{
}
public static function fulfills($candidate, $target)
{
if (self::VERSION_NEWEST === $target) {
throw new \LogicException(sprintf('Parameter `target` shall not be provided as "%s", determine proper target for tested PHPUnit feature instead.', self::VERSION_NEWEST));
}
if (self::VERSION_NEWEST === $candidate) {
return true;
}
return Comparator::greaterThanOrEqualTo($candidate, $target);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitConstructFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
private static $assertionFixers = [
'assertSame' => '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(
'<?php
final class FooTest extends \PHPUnit_Framework_TestCase {
public function testSomething() {
$this->assertEquals(false, $b);
$this->assertSame(true, $a);
$this->assertNotEquals(null, $c);
$this->assertNotSame(null, $d);
}
}
'
),
new CodeSample(
'<?php
final class FooTest extends \PHPUnit_Framework_TestCase {
public function testSomething() {
$this->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];
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitExpectationFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private $methodMap = [];
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->methodMap = [
'setExpectedException' => 'expectExceptionMessage',
];
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) {
$this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp';
}
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_8_4)) {
$this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageMatches';
$this->methodMap['expectExceptionMessageRegExp'] = 'expectExceptionMessageMatches';
}
}
public function getDefinition()
{
return new FixerDefinition(
'Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.',
[
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", "Msg", 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
'
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", null, 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
',
['target' => PhpUnitTargetVersion::VERSION_8_4]
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", null, 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
',
['target' => PhpUnitTargetVersion::VERSION_5_6]
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->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_8_4, 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().WhitespacesAnalyzer::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);
}
$methodName = 'expectException';
if ('expectExceptionMessageRegExp' === $tokens[$index]->getContent()) {
$methodName = $this->methodMap[$tokens[$index]->getContent()];
}
$tokens[$index] = new Token([T_STRING, $methodName]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitTestClassRequiresCoversFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Adds a default `@coversNothing` annotation to PHPUnit test classes that have no `@covers*` annotation.',
[
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->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)]);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer
{
public function getDefinition()
{
return new FixerDefinition(
'PHPUnit annotations should be a FQCNs including a root namespace.',
[new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @covers Project\NameSpace\Something
* @coversDefaultClass Project\Default
* @uses Project\Test\Util
*/
public function testSomeTest()
{
}
}
'
)]
);
}
public function getPriority()
{
return -9;
}
protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex)
{
$prevDocCommentIndex = $tokens->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()
)]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitDedicateAssertFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
private static $fixMap = [
'array_key_exists' => ['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(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertTrue(is_float( $a), "my message");
$this->assertTrue(is_nan($a));
}
}
'
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->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);
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurationDefinitionFixerInterface
{
private static $assertionMap = [
'assertAttributeEquals' => '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(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertAttributeEquals(a(), b());
$this->assertAttributeNotEquals(a(), b());
$this->assertEquals(a(), b());
$this->assertNotEquals(a(), b());
}
}
'
),
new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->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());
}
}
<?php
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'All PHPUnit test classes should be marked as internal.',
[
new CodeSample("<?php\nclass MyTest extends TestCase {}\n"),
new CodeSample(
"<?php\nclass MyTest extends TestCase {}\nfinal class FinalTest extends TestCase {}\nabstract class AbstractTest extends TestCase {}\n",
['types' => ['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 = WhitespacesAnalyzer::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 addInternalAnnotation(DocBlock $docBlock, Tokens $tokens, $docBlockIndex)
{
$lines = $docBlock->getLines();
$originalIndent = WhitespacesAnalyzer::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 = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
$doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding());
return $doc;
}
return $doc;
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\Tokenizer\Tokens;
/**
@symfony
*/
interface FixerInterface
{
public function isCandidate(Tokens $tokens);
public function isRisky();
public function fix(\SplFileInfo $file, Tokens $tokens);
public function getName();
public function getPriority();
public function supports(\SplFileInfo $file);
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
interface ConfigurableFixerInterface extends FixerInterface
{
public function configure(array $configuration = null);
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class DeclareEqualNormalizeFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $callback;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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("<?php\ndeclare(ticks = 1);\n"),
new CodeSample("<?php\ndeclare(ticks=1);\n", ['space' => '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);
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleSpaceAfterConstructFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private static $tokenMap = [
'abstract' => T_ABSTRACT,
'as' => T_AS,
'attribute' => CT::T_ATTRIBUTE_CLOSE,
'break' => T_BREAK,
'case' => T_CASE,
'catch' => T_CATCH,
'class' => T_CLASS,
'clone' => T_CLONE,
'comment' => T_COMMENT,
'const' => T_CONST,
'const_import' => CT::T_CONST_IMPORT,
'continue' => T_CONTINUE,
'do' => T_DO,
'echo' => T_ECHO,
'else' => T_ELSE,
'elseif' => T_ELSEIF,
'extends' => T_EXTENDS,
'final' => T_FINAL,
'finally' => T_FINALLY,
'for' => T_FOR,
'foreach' => T_FOREACH,
'function' => T_FUNCTION,
'function_import' => CT::T_FUNCTION_IMPORT,
'global' => T_GLOBAL,
'goto' => T_GOTO,
'if' => T_IF,
'implements' => T_IMPLEMENTS,
'include' => T_INCLUDE,
'include_once' => T_INCLUDE_ONCE,
'instanceof' => T_INSTANCEOF,
'insteadof' => T_INSTEADOF,
'interface' => T_INTERFACE,
'match' => null,
'named_argument' => CT::T_NAMED_ARGUMENT_COLON,
'new' => T_NEW,
'open_tag_with_echo' => T_OPEN_TAG_WITH_ECHO,
'php_doc' => T_DOC_COMMENT,
'php_open' => T_OPEN_TAG,
'print' => T_PRINT,
'private' => T_PRIVATE,
'protected' => T_PROTECTED,
'public' => T_PUBLIC,
'require' => T_REQUIRE,
'require_once' => T_REQUIRE_ONCE,
'return' => T_RETURN,
'static' => T_STATIC,
'throw' => T_THROW,
'trait' => T_TRAIT,
'try' => T_TRY,
'use' => T_USE,
'use_lambda' => CT::T_USE_LAMBDA,
'use_trait' => CT::T_USE_TRAIT,
'var' => T_VAR,
'while' => T_WHILE,
'yield' => T_YIELD,
'yield_from' => null,
];
private $fixTokenMap = [];
public function configure(array $configuration = null)
{
parent::configure($configuration);
if (\defined('T_YIELD_FROM')) {
self::$tokenMap['yield_from'] = T_YIELD_FROM;
}
if (\defined('T_MATCH')) {
self::$tokenMap['match'] = T_MATCH;
}
$this->fixTokenMap = [];
foreach ($this->configuration['constructs'] as $key) {
$this->fixTokenMap[$key] = self::$tokenMap[$key];
}
if (isset($this->fixTokenMap['public'])) {
$this->fixTokenMap['constructor_public'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC;
}
if (isset($this->fixTokenMap['protected'])) {
$this->fixTokenMap['constructor_protected'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED;
}
if (isset($this->fixTokenMap['private'])) {
$this->fixTokenMap['constructor_private'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE;
}
}
public function getDefinition()
{
return new FixerDefinition(
'Ensures a single space after language constructs.',
[
new CodeSample(
'<?php
throw new \Exception();
'
),
new CodeSample(
'<?php
echo "Hello!";
',
[
'constructs' => [
'echo',
],
]
),
new VersionSpecificCodeSample(
'<?php
yield from baz();
',
new VersionSpecification(70000),
[
'constructs' => [
'yield_from',
],
]
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound(array_values($this->fixTokenMap)) && !$tokens->hasAlternativeSyntax();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$tokenKinds = array_values($this->fixTokenMap);
for ($index = $tokens->count() - 2; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($tokenKinds)) {
continue;
}
$whitespaceTokenIndex = $index + 1;
if ($tokens[$whitespaceTokenIndex]->equalsAny([';', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) {
continue;
}
if (
$token->isGivenKind(T_STATIC)
&& !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind([T_FUNCTION, T_VARIABLE])
) {
continue;
}
if ($token->isGivenKind(T_OPEN_TAG)) {
if ($tokens[$whitespaceTokenIndex]->equals([T_WHITESPACE]) && false === strpos($token->getContent(), "\n")) {
$tokens->clearAt($whitespaceTokenIndex);
}
continue;
}
if ($token->isGivenKind(T_CLASS) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(')) {
continue;
}
if ($token->isGivenKind([T_EXTENDS, T_IMPLEMENTS]) && $this->isMultilineExtendsOrImplementsWithMoreThanOneAncestor($tokens, $index)) {
continue;
}
if ($token->isGivenKind(T_RETURN) && $this->isMultiLineReturn($tokens, $index)) {
continue;
}
if ($token->isComment() || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
if ($tokens[$whitespaceTokenIndex]->equals([T_WHITESPACE]) && false !== strpos($tokens[$whitespaceTokenIndex]->getContent(), "\n")) {
continue;
}
}
if ($tokens[$whitespaceTokenIndex]->equals([T_WHITESPACE])) {
$tokens[$whitespaceTokenIndex] = new Token([T_WHITESPACE, ' ']);
} else {
$tokens->insertAt($whitespaceTokenIndex, new Token([T_WHITESPACE, ' ']));
}
if (
70000 <= \PHP_VERSION_ID
&& $token->isGivenKind(T_YIELD_FROM)
&& 'yield from' !== strtolower($token->getContent())
) {
$tokens[$index] = new Token([T_YIELD_FROM, Preg::replace(
'/\s+/',
' ',
$token->getContent()
)]);
}
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('constructs', 'List of constructs which must be followed by a single space.'))
->setAllowedTypes(['array'])
->setAllowedValues([new AllowedValueSubset(array_keys(self::$tokenMap))])
->setDefault(array_keys(self::$tokenMap))
->getOption(),
]);
}
private function isMultiLineReturn(Tokens $tokens, $index)
{
++$index;
$tokenFollowingReturn = $tokens[$index];
if (
!$tokenFollowingReturn->isGivenKind(T_WHITESPACE)
|| false === strpos($tokenFollowingReturn->getContent(), "\n")
) {
return false;
}
$nestedCount = 0;
for ($indexEnd = \count($tokens) - 1, ++$index; $index < $indexEnd; ++$index) {
if (false !== strpos($tokens[$index]->getContent(), "\n")) {
return true;
}
if ($tokens[$index]->equals('{')) {
++$nestedCount;
} elseif ($tokens[$index]->equals('}')) {
--$nestedCount;
} elseif (0 === $nestedCount && $tokens[$index]->equalsAny([';', [T_CLOSE_TAG]])) {
break;
}
}
return false;
}
private function isMultilineExtendsOrImplementsWithMoreThanOneAncestor(Tokens $tokens, $index)
{
$hasMoreThanOneAncestor = false;
while (++$index) {
$token = $tokens[$index];
if ($token->equals(',')) {
$hasMoreThanOneAncestor = true;
continue;
}
if ($token->equals('{')) {
return false;
}
if ($hasMoreThanOneAncestor && false !== strpos($token->getContent(), "\n")) {
return true;
}
}
return false;
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class IsNullFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Replaces `is_null($var)` expression with `null === $var`.',
[
new CodeSample("<?php\n\$a = is_null(\$b);\n"),
],
null,
'Risky when the function `is_null` is 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)
{
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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class ClassKeywordRemoveFixer extends AbstractFixer
{
private $imports = [];
public function getDefinition()
{
return new FixerDefinition(
'Converts `::class` keywords to FQCN strings.',
[
new CodeSample(
'<?php
use Foo\Bar\Baz;
$className = Baz::class;
'
),
]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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
));
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUnsetOnPropertyFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Properties should be set to `null` instead of using `unset`.',
[new CodeSample("<?php\nunset(\$this->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']),
]
);
}
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ExplicitIndirectVariableFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Add curly braces to indirect variables to make them clear to understand. Requires PHP >= 7.0.',
[
new VersionSpecificCodeSample(
<<<'EOT'
<?php
echo $$foo;
echo $$foo['bar'];
echo $foo->$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, '}']),
]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class ErrorSuppressionFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const OPTION_MUTE_DEPRECATION_ERROR = 'mute_deprecation_error';
const OPTION_NOISE_REMAINING_USAGES = 'noise_remaining_usages';
const OPTION_NOISE_REMAINING_USAGES_EXCLUDE = 'noise_remaining_usages_exclude';
public function getDefinition()
{
return new FixerDefinition(
'Error control operator should be added to deprecation notices and/or removed from other cases.',
[
new CodeSample("<?php\ntrigger_error('Warning.', E_USER_DEPRECATED);\n"),
new CodeSample(
"<?php\n@mkdir(\$dir);\n@unlink(\$path);\n",
[self::OPTION_NOISE_REMAINING_USAGES => true]
),
new CodeSample(
"<?php\n@mkdir(\$dir);\n@unlink(\$path);\n",
[
self::OPTION_NOISE_REMAINING_USAGES => 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']);
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FunctionToConstantFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private static $availableFunctions;
private $functionsFixMap;
public function __construct()
{
if (null === self::$availableFunctions) {
self::$availableFunctions = [
'get_called_class' => [
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(
"<?php\necho phpversion();\necho pi();\necho php_sapi_name();\nclass Foo\n{\n public function Bar()\n {\n echo get_class();\n echo get_called_class();\n }\n}\n"
),
new CodeSample(
"<?php\necho phpversion();\necho pi();\nclass Foo\n{\n public function Bar()\n {\n echo get_class();\n get_class(\$this);\n echo get_called_class();\n }\n}\n",
['functions' => ['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,
];
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class SilencedDeprecationErrorFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Ensures deprecation notices are silenced.',
[new CodeSample("<?php\ntrigger_error('Warning.', E_USER_DEPRECATED);\n")],
null,
'Silencing of deprecation errors might cause changes to code behaviour.'
);
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
return [new ErrorSuppressionFixer()];
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CombineConsecutiveIssetsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Using `isset($var) &&` multiple times should be done in one call.',
[new CodeSample("<?php\n\$a = isset(\$a) && isset(\$b);\n")]
);
}
public function getPriority()
{
return 3;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CombineConsecutiveUnsetsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Calling `unset` on multiple items should be done in one call.',
[new CodeSample("<?php\nunset(\$a); unset(\$b);\n")]
);
}
public function getPriority()
{
return 24;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class DirConstantFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Replaces `dirname(__FILE__)` expression with equivalent `__DIR__` constant.',
[new CodeSample("<?php\n\$a = dirname(__FILE__);\n")],
null,
'Risky when the function `dirname` is overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FileSpecificCodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
@gotink
@alt
@gmail
*/
final class PsrAutoloadingFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.',
[
new FileSpecificCodeSample(
'<?php
namespace PhpCsFixer\FIXER\Basic;
class InvalidName {}
',
new \SplFileInfo(__FILE__)
),
new FileSpecificCodeSample(
'<?php
namespace PhpCsFixer\FIXER\Basic;
class InvalidName {}
',
new \SplFileInfo(__FILE__),
['dir' => './src']
),
],
null,
'This fixer may change your class name, which will break the code that depends on the old name.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
public function isRisky()
{
return true;
}
public function getPriority()
{
return -10;
}
public function supports(\SplFileInfo $file)
{
if ($file instanceof StdinFileInfo) {
return false;
}
if (
('php' !== $file->getExtension())
|| 0 === Preg::match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $file->getBasename('.php'))
) {
return false;
}
try {
$tokens = Tokens::fromCode(sprintf('<?php class %s {}', $file->getBasename('.php')));
if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) {
return false;
}
} catch (\ParseError $e) {
return false;
}
return !Preg::match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath());
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('dir', 'If provided, the directory where the project code is placed.'))
->setAllowedTypes(['null', 'string'])
->setDefault(null)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$namespace = null;
$namespaceStartIndex = null;
$namespaceEndIndex = null;
$classyName = null;
$classyIndex = null;
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_NAMESPACE)) {
if (null !== $namespace) {
return;
}
$namespaceStartIndex = $tokens->getNextMeaningfulToken($index);
$namespaceEndIndex = $tokens->getNextTokenOfKind($namespaceStartIndex, [';']);
$namespace = trim($tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex - 1));
} elseif ($token->isClassy()) {
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW)) {
continue;
}
if (null !== $classyName) {
return;
}
$classyIndex = $tokens->getNextMeaningfulToken($index);
$classyName = $tokens[$classyIndex]->getContent();
}
}
if (null === $classyName) {
return;
}
$expectedClassyName = $this->calculateClassyName($file, $namespace, $classyName);
if ($classyName !== $expectedClassyName) {
$tokens[$classyIndex] = new Token([T_STRING, $expectedClassyName]);
}
if (null === $this->configuration['dir'] || null === $namespace) {
return;
}
if (!is_dir($this->configuration['dir'])) {
return;
}
$configuredDir = realpath($this->configuration['dir']);
$fileDir = \dirname($file->getRealPath());
if (\strlen($configuredDir) >= \strlen($fileDir)) {
return;
}
$newNamespace = substr(str_replace('/', '\\', $fileDir), \strlen($configuredDir) + 1);
$originalNamespace = substr($namespace, -\strlen($newNamespace));
if ($originalNamespace !== $newNamespace && strtolower($originalNamespace) === strtolower($newNamespace)) {
$tokens->clearRange($namespaceStartIndex, $namespaceEndIndex);
$namespace = substr($namespace, 0, -\strlen($newNamespace)).$newNamespace;
$newNamespace = Tokens::fromCode('<?php namespace '.$namespace.';');
$newNamespace->clearRange(0, 2);
$newNamespace->clearEmptyTokens();
$tokens->insertAt($namespaceStartIndex, $newNamespace);
}
}
private function calculateClassyName(\SplFileInfo $file, $namespace, $currentName)
{
$name = $file->getBasename('.php');
$maxNamespace = $this->calculateMaxNamespace($file, $namespace);
if (null !== $this->configuration['dir']) {
return ('' !== $maxNamespace ? (str_replace('\\', '_', $maxNamespace).'_') : '').$name;
}
$namespaceParts = array_reverse(explode('\\', $maxNamespace));
foreach ($namespaceParts as $namespacePart) {
$nameCandidate = sprintf('%s_%s', $namespacePart, $name);
if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) {
break;
}
$name = $nameCandidate;
}
return $name;
}
private function calculateMaxNamespace(\SplFileInfo $file, $namespace)
{
if (null === $this->configuration['dir']) {
$root = \dirname($file->getRealPath());
while ($root !== \dirname($root)) {
$root = \dirname($root);
}
} else {
$root = realpath($this->configuration['dir']);
}
$namespaceAccordingToFileLocation = trim(str_replace(\DIRECTORY_SEPARATOR, '\\', substr(\dirname($file->getRealPath()), \strlen($root))), '\\');
if (null === $namespace) {
return $namespaceAccordingToFileLocation;
}
$namespaceAccordingToFileLocationPartsReversed = array_reverse(explode('\\', $namespaceAccordingToFileLocation));
$namespacePartsReversed = array_reverse(explode('\\', $namespace));
foreach ($namespacePartsReversed as $key => $namespaceParte) {
if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) {
break;
}
if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) {
break;
}
unset($namespaceAccordingToFileLocationPartsReversed[$key]);
}
return implode('\\', array_reverse($namespaceAccordingToFileLocationPartsReversed));
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@gmail
@gotink
@alt
*/
final class Psr4Fixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
private $fixer;
public function __construct()
{
$this->fixer = new PsrAutoloadingFixer();
parent::__construct();
}
public function getDefinition()
{
$definition = $this->fixer->getDefinition();
return new FixerDefinition(
'Class names should match the file name.',
\array_slice($definition->getCodeSamples(), 0, 1),
$definition->getDescription(),
$definition->getRiskyDescription()
);
}
public function getSuccessorsNames()
{
return [$this->fixer->getName()];
}
protected function createProxyFixers()
{
return [$this->fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
final class NonPrintableCharacterFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $symbolsReplace;
private static $tokens = [
T_STRING_VARNAME,
T_INLINE_HTML,
T_VARIABLE,
T_COMMENT,
T_ENCAPSED_AND_WHITESPACE,
T_CONSTANT_ENCAPSED_STRING,
T_DOC_COMMENT,
];
public function __construct()
{
parent::__construct();
$this->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(
'<?php echo "'.pack('H*', 'e2808b').'Hello'.pack('H*', 'e28087').'World'.pack('H*', 'c2a0')."!\";\n"
),
new VersionSpecificCodeSample(
'<?php echo "'.pack('H*', 'e2808b').'Hello'.pack('H*', 'e28087').'World'.pack('H*', 'c2a0')."!\";\n",
new VersionSpecification(70000),
['use_escape_sequences_in_strings' => 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)]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@gmail
@gotink
@alt
*/
final class Psr0Fixer extends AbstractProxyFixer implements ConfigurationDefinitionFixerInterface, DeprecatedFixerInterface
{
private $fixer;
public function __construct()
{
$this->fixer = new PsrAutoloadingFixer();
parent::__construct();
}
public function getDefinition()
{
$definition = $this->fixer->getDefinition();
return new FixerDefinition(
'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.',
$definition->getCodeSamples(),
$definition->getDescription(),
$definition->getRiskyDescription()
);
}
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->fixer->configure($configuration);
}
public function getSuccessorsNames()
{
return [$this->fixer->getName()];
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('dir', 'The directory where the project code is placed.'))
->setAllowedTypes(['string'])
->setDefault('')
->getOption(),
]);
}
protected function createProxyFixers()
{
return [$this->fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class BracesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const LINE_NEXT = 'next';
const LINE_SAME = 'same';
public function getDefinition()
{
return new FixerDefinition(
'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.',
[
new CodeSample(
'<?php
class Foo {
public function bar($baz) {
if ($baz = 900) echo "Hello!";
if ($baz = 9000)
echo "Wait!";
if ($baz == true)
{
echo "Why?";
}
else
{
echo "Ha?";
}
if (is_array($baz))
foreach ($baz as $b)
{
echo $b;
}
}
}
'
),
new CodeSample(
'<?php
$positive = function ($item) { return $item >= 0; };
$negative = function ($item) {
return $item < 0; };
',
['allow_single_line_closure' => true]
),
new CodeSample(
'<?php
class Foo
{
public function bar($baz)
{
if ($baz = 900) echo "Hello!";
if ($baz = 9000)
echo "Wait!";
if ($baz == true)
{
echo "Why?";
}
else
{
echo "Ha?";
}
if (is_array($baz))
foreach ($baz as $b)
{
echo $b;
}
}
}
',
['position_after_functions_and_oop_constructs' => 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_anonymous_class_with_empty_body', 'Whether single line anonymous class with empty body notation should be allowed.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(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().WhitespacesAnalyzer::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_anonymous_class_with_empty_body']
&& $token->isGivenKind(T_CLASS)
) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(T_NEW)) {
$braceStartIndex = $tokens->getNextTokenOfKind($index, ['{']);
$braceEndIndex = $tokens->getNextMeaningfulToken($braceStartIndex);
if ('}' === $tokens[$braceEndIndex]->getContent() && !$this->isMultilined($tokens, $index, $braceEndIndex)) {
$index = $braceEndIndex;
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 = WhitespacesAnalyzer::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().WhitespacesAnalyzer::detectIndent($tokens, $index)
: ' '
);
}
$prevToken = $tokens[$index - 1];
if (!$prevToken->isWhitespace() && !$prevToken->isComment() && !$prevToken->isGivenKind(T_OPEN_TAG)) {
$tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
}
}
}
}
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)'.WhitespacesAnalyzer::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;
}
}
<?php
namespace PhpCsFixer\Fixer\Basic;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class EncodingFixer extends AbstractFixer
{
private $BOM;
public function __construct()
{
parent::__construct();
$this->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.'<?php
echo "Hello!";
'
),
]
);
}
public function getPriority()
{
return 100;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$content = $tokens[0]->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]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SpaceAfterSemicolonFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Fix whitespace after a semicolon.',
[
new CodeSample(
"<?php
sample(); \$test = 1;
sample();\$test = 2;
for ( ;;++\$sample) {
}\n"
),
new CodeSample("<?php\nfor (\$i = 0; ; ++\$i) {\n}\n", [
'remove_in_empty_for_expressions' => 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, ' ']);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class NoEmptyStatementFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Remove useless (semicolon) statements.',
[
new CodeSample("<?php \$a = 1;;\n"),
new CodeSample("<?php echo 1;2;\n"),
new CodeSample("<?php while(foo()){\n continue 1;\n}\n"),
]
);
}
public function getPriority()
{
return 26;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(';');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind([T_BREAK, T_CONTINUE])) {
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->equals([T_LNUMBER, '1'])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
continue;
}
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);
continue;
}
$prePreviousMeaningfulIndex = $tokens->getPrevMeaningfulToken($previousMeaningfulIndex);
if (
$tokens[$prePreviousMeaningfulIndex]->equalsAny([';', '{', '}', [T_OPEN_TAG]])
&& $tokens[$previousMeaningfulIndex]->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_DNUMBER, T_LNUMBER, T_STRING, T_VARIABLE])
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$tokens->clearTokenAndMergeSurroundingWhitespace($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);
$beforeCurlyOpeningIndex = $tokens->getPrevMeaningfulToken($curlyOpeningIndex);
if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind($beforeCurlyOpeningKinds) || $tokens[$beforeCurlyOpeningIndex]->equalsAny([';', '{', '}'])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind(T_STRING)) {
$classyTestIndex = $tokens->getPrevMeaningfulToken($beforeCurlyOpeningIndex);
while ($tokens[$classyTestIndex]->equals(',') || $tokens[$classyTestIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR, T_EXTENDS, T_IMPLEMENTS])) {
$classyTestIndex = $tokens->getPrevMeaningfulToken($classyTestIndex);
}
$tokensAnalyzer = new TokensAnalyzer($tokens);
if (
$tokens[$classyTestIndex]->isGivenKind(T_NAMESPACE)
|| ($tokens[$classyTestIndex]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTestIndex))
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
return;
}
if (!$tokens[$beforeCurlyOpeningIndex]->equals(')')) {
return;
}
$openingBraceIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpeningIndex);
$beforeOpeningBraceIndex = $tokens->getPrevMeaningfulToken($openingBraceIndex);
if ($tokens[$beforeOpeningBraceIndex]->isGivenKind([T_IF, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_SWITCH, T_CATCH, T_DECLARE])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
if ($tokens[$beforeOpeningBraceIndex]->isGivenKind(T_STRING)) {
$beforeStringIndex = $tokens->getPrevMeaningfulToken($beforeOpeningBraceIndex);
if ($tokens[$beforeStringIndex]->isGivenKind(T_FUNCTION)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoSinglelineWhitespaceBeforeSemicolonsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Single-line whitespace before closing semicolon are prohibited.',
[new CodeSample("<?php \$this->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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SemicolonAfterInstructionFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Instructions must be terminated with a semicolon.',
[new CodeSample("<?php echo 1 ?>\n")]
);
}
public function getPriority()
{
return 2;
}
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(';'));
}
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class NoMultilineWhitespaceBeforeSemicolonsFixer extends AbstractProxyFixer implements DeprecatedFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Multi-line whitespace before closing semicolon are prohibited.',
[
new CodeSample(
'<?php
function foo () {
return 1 + 2
;
}
'
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new MultilineWhitespaceBeforeSemicolonsFixer();
$fixer->configure(['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NO_MULTI_LINE]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const STRATEGY_NO_MULTI_LINE = 'no_multi_line';
const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls';
public function getDefinition()
{
return new FixerDefinition(
'Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.',
[
new CodeSample(
'<?php
function foo () {
return 1 + 2
;
}
'
),
new CodeSample(
'<?php
$this->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;
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\WhitespacesFixerConfig;
interface WhitespacesAwareFixerInterface extends FixerInterface
{
public function setWhitespacesConfig(WhitespacesFixerConfig $config);
}
<?php
namespace PhpCsFixer\Fixer;
interface DeprecatedFixerInterface extends FixerInterface
{
public function getSuccessorsNames();
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'In array declaration, there MUST be a whitespace after each comma.',
[new CodeSample("<?php\n\$sample = array(1,'a',\$b,);\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$tokensToInsert = [];
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
continue;
}
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()) {
$tokensToInsert[$i + 1] = new Token([T_WHITESPACE, ' ']);
}
}
}
if ([] !== $tokensToInsert) {
$tokens->insertSlices($tokensToInsert);
}
}
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;
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
@rollerscapes
*/
final class NoTrailingCommaInSinglelineArrayFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'PHP single-line arrays should not have trailing comma.',
[new CodeSample("<?php\n\$a = array('sample', );\n")]
);
}
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 = 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NormalizeIndexBraceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Array index should always be written by using square braces.',
[new CodeSample("<?php\necho \$sample{\$index};\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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(']');
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class TrimArraySpacesFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Arrays should be formatted like function/method arguments, without leading or trailing single line space.',
[new CodeSample("<?php\n\$sample = array( );\n\$sample = array( 'a', 'b' );\n")]
);
}
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 = 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Options;
/**
@gmail
*/
final class TrailingCommaInMultilineArrayFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'PHP multi-line arrays should have a trailing comma.',
[
new CodeSample("<?php\narray(\n 1,\n 2\n);\n"),
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
$x = [
'foo',
<<<EOD
bar
EOD
];
SAMPLE
,
new VersionSpecification(70300),
['after_heredoc' => 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, ' ');
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
final class NoWhitespaceBeforeCommaInArrayFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'In array declaration, there MUST NOT be a whitespace before each comma.',
[
new CodeSample("<?php \$x = array(1 , \"2\");\n"),
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
$x = [<<<EOD
foo
EOD
, 'bar'
];
SAMPLE
,
new VersionSpecification(70300),
['after_heredoc' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@rollerscapes
@gmail
*/
final class ArraySyntaxFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $candidateTokenKind;
private $fixCallback;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->resolveCandidateTokenKind();
$this->resolveFixCallback();
}
public function getDefinition()
{
return new FixerDefinition(
'PHP arrays should be declared using the configured syntax.',
[
new CodeSample(
"<?php\n[1,2];\n"
),
new VersionSpecificCodeSample(
"<?php\narray(1,2);\n",
new VersionSpecification(50400),
['syntax' => '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;
}
}
<?php
namespace PhpCsFixer\Fixer\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
@alt
*/
final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Operator `=>` should not be surrounded by multi-line whitespaces.',
[new CodeSample("<?php\n\$a = array(1\n\n=> 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()).' ']);
}
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractIncrementOperatorFixer extends AbstractFixer
{
final protected function findStart(Tokens $tokens, $index)
{
do {
$index = $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\ConstantNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class NativeConstantInvocationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $constantsToEscape = [];
private $caseInsensitiveConstantsToEscape = [];
public function getDefinition()
{
return new FixerDefinition(
'Add leading `\` before constant invocation of internal constant to speed up resolving. Constant name match is case-sensitive, except for `null`, `false` and `true`.',
[
new CodeSample("<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n"),
new CodeSample(
'<?php
namespace space1 {
echo PHP_VERSION;
}
namespace {
echo M_PI;
}
',
['scope' => 'namespaced']
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'include' => [
'MY_CUSTOM_PI',
],
]
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'fix_built_in' => false,
'include' => [
'MY_CUSTOM_PI',
],
]
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'exclude' => [
'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(),
(new FixerOptionBuilder('strict', 'Whether leading `\` of constant invocation not meant to have it should be removed.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
private function fixConstantInvocations(Tokens $tokens, $startIndex, $endIndex)
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
$useConstantDeclarations = [];
foreach ($useDeclarations as $use) {
if ($use->isConstant()) {
$useConstantDeclarations[$use->getShortName()] = true;
}
}
$tokenAnalyzer = new TokensAnalyzer($tokens);
for ($index = $endIndex; $index > $startIndex; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_STRING)) {
continue;
}
if (!$tokenAnalyzer->isConstantInvocation($index)) {
continue;
}
$tokenContent = $token->getContent();
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!isset($this->constantsToEscape[$tokenContent]) && !isset($this->caseInsensitiveConstantsToEscape[strtolower($tokenContent)])) {
if (!$this->configuration['strict']) {
continue;
}
if (!$tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
continue;
}
$prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if ($tokens[$prevPrevIndex]->isGivenKind(T_STRING)) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
continue;
}
if (isset($useConstantDeclarations[$tokenContent])) {
continue;
}
if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
continue;
}
$tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\']));
}
}
}
<?php
namespace PhpCsFixer\Fixer;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Indicator\PhpUnitTestCaseIndicator;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractPhpUnitFixer extends AbstractFixer
{
final public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
final class PhpdocReturnSelfReferenceFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private static $toTypes = [
'$this',
'static',
'self',
];
public function getDefinition()
{
return new FixerDefinition(
'The type of `@return` annotations of methods returning a reference to itself must the configured one.',
[
new CodeSample(
'<?php
class Sample
{
/**
* @return this
*/
public function test1()
{
return $this;
}
/**
* @return $self
*/
public function test2()
{
return $this;
}
}
'
),
new CodeSample(
'<?php
class Sample
{
/**
* @return this
*/
public function test1()
{
return $this;
}
/**
* @return $self
*/
public function test2()
{
return $this;
}
}
',
['replacements' => ['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()]);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocTrimFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'PHPDoc should start and end with content, excluding the very first and last line of the docblocks.',
[new CodeSample('<?php
/**
*
* Foo must be final class.
*
*
*/
final class Foo {}
')]
);
}
public function getPriority()
{
return -5;
}
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();
$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
(?:
(?<!/\*\*) # not preceded by a DocComment start
\R\h*(?:\*\h*)? # lines without useful content
)+
(\R\h*\*/$) # DocComment end
~xu',
'$1$2',
$content
);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocInlineTagNormalizerFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
public function getDefinition()
{
return new FixerDefinition(
'Fixes PHPDoc inline tags.',
[
new CodeSample(
"<?php\n/**\n * @{TUTORIAL}\n * {{ @link }}\n * @inheritDoc\n */\n"
),
new CodeSample(
"<?php\n/**\n * @{TUTORIAL}\n * {{ @link }}\n * @inheritDoc\n */\n",
['tags' => ['TUTORIAL']]
),
]
);
}
public function getPriority()
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
if (!$this->configuration['tags']) {
return;
}
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$content = Preg::replaceCallback(
sprintf(
'#(?:@{+|{+\h*@)\h*(%s)s?([^}]*)(?:}+)#i',
implode('|', array_map(function ($tag) {
return preg_quote($tag, '/');
}, $this->configuration['tags']))
),
function (array $matches) {
$doc = trim($matches[2]);
if ('' === $doc) {
return '{@'.$matches[1].'}';
}
return '{@'.$matches[1].' '.$doc.'}';
},
$token->getContent()
);
$tokens[$index] = new Token([T_DOC_COMMENT, $content]);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('tags', 'The list of tags to normalize'))
->setAllowedTypes(['array'])
->setDefault(['example', 'id', 'internal', 'inheritdoc', 'inheritdocs', 'link', 'source', 'toc', 'tutorial'])
->getOption(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\TagComparator;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocSeparationFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Annotations in PHPDoc should be grouped together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line.',
[
new CodeSample(
'<?php
/**
* Description.
* @param string $foo
*
*
* @param bool $bar Bar
* @throws Exception|RuntimeException
* @return bool
*/
function fnc($foo, $bar) {}
'
),
]
);
}
public function getPriority()
{
return -3;
}
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());
$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();
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoSuperfluousPhpdocTagsFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Removes `@param`, `@return` and `@var` tags that don\'t provide any useful information.',
[
new CodeSample('<?php
class Foo {
/**
* @param Bar $bar
* @param mixed $baz
*/
public function doFoo(Bar $bar, $baz) {}
}
'),
new CodeSample('<?php
class Foo {
/**
* @param Bar $bar
* @param mixed $baz
*/
public function doFoo(Bar $bar, $baz) {}
}
', ['allow_mixed' => true]),
new VersionSpecificCodeSample('<?php
class Foo {
/**
* @param Bar $bar
* @param mixed $baz
*
* @return Baz
*/
public function doFoo(Bar $bar, $baz): Baz {}
}
', new VersionSpecification(70000)),
new CodeSample('<?php
class Foo {
/**
* @inheritDoc
*/
public function doFoo(Bar $bar, $baz) {}
}
', ['remove_inheritdoc' => true]),
new CodeSample('<?php
class Foo {
/**
* @param Bar $bar
* @param mixed $baz
* @param string|int|null $qux
*/
public function doFoo(Bar $bar, $baz /*, $qux = null */) {}
}
', ['allow_unused_params' => 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);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class PhpdocInlineTagFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
public function getDefinition()
{
return new FixerDefinition(
'Fix PHPDoc inline tags, make `@inheritdoc` always inline.',
[new CodeSample(
'<?php
/**
* @{TUTORIAL}
* {{ @link }}
* {@examples}
* @inheritdocs
*/
'
)]
);
}
public function getPriority()
{
return 0;
}
protected function createProxyFixers()
{
$inlineNormalizerFixer = new PhpdocInlineTagNormalizerFixer();
$renameFixer = new GeneralPhpdocTagRenameFixer();
$renameFixer->configure([
'fix_annotation' => true,
'fix_inline' => true,
'replacements' => [
'inheritdoc' => 'inheritdoc',
'inheritdocs' => 'inheritdoc',
],
'case_sensitive' => false,
]);
$tagTypeFixer = new PhpdocTagTypeFixer();
$tagTypeFixer->configure([
'tags' => ['inheritdoc' => 'inline'],
]);
return [$inlineNormalizerFixer, $renameFixer, $tagTypeFixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocOrderFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'<?php
/**
* Hello there!
*
* @throws Exception|RuntimeException foo
* @custom Test!
* @return int Return the number of changes.
* @param string $foo
* @param bool $bar Bar
*/
'
),
]
);
}
public function getPriority()
{
return -2;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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();
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Tokens;
final class NoEmptyPhpdocFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There should not be empty PHPDoc blocks.',
[new CodeSample("<?php /** */\n")]
);
}
public function getPriority()
{
return 3;
}
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;
}
if (Preg::match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@gmail
*/
final class PhpdocNoPackageFixer extends AbstractProxyFixer
{
public function getDefinition()
{
return new FixerDefinition(
'`@package` and `@subpackage` annotations should be omitted from PHPDoc.',
[
new CodeSample(
'<?php
/**
* @internal
* @package Foo
* subpackage Bar
*/
class Baz
{
}
'
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
protected function createProxyFixers()
{
$fixer = new GeneralPhpdocAnnotationRemoveFixer();
$fixer->configure(['annotations' => ['package', 'subpackage']]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
final class PhpdocTypesOrderFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Sorts PHPDoc types.',
[
new CodeSample(
'<?php
/**
* @param string|null $bar
*/
'
),
new CodeSample(
'<?php
/**
* @param null|string $bar
*/
',
['null_adjustment' => 'always_last']
),
new CodeSample(
'<?php
/**
* @param null|string|int|\Foo $bar
*/
',
['sort_algorithm' => 'alpha']
),
new CodeSample(
'<?php
/**
* @param null|string|int|\Foo $bar
*/
',
[
'sort_algorithm' => 'alpha',
'null_adjustment' => 'always_last',
]
),
new CodeSample(
'<?php
/**
* @param null|string|int|\Foo $bar
*/
',
[
'sort_algorithm' => '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));
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocVarAnnotationCorrectOrderFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'`@var` and `@type` annotations must have type and name in the correct order.',
[new CodeSample('<?php
/** @var $foo int */
$foo = 2 + 2;
')]
);
}
public function getPriority()
{
return 0;
}
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;
}
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]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\ShortDescription;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'PHPDoc summary should end in either a full stop, exclamation mark, or question mark.',
[new CodeSample('<?php
/**
* Foo function is great
*/
function foo () {}
')]
);
}
public function getPriority()
{
return 0;
}
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());
$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, '.。!?¡¿!?');
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
final class GeneralPhpdocTagRenameFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Renames PHPDoc tags.',
[
new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [
'replacements' => [
'inheritDocs' => 'inheritDoc',
],
]),
new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [
'replacements' => [
'inheritDocs' => 'inheritDoc',
],
'fix_annotation' => false,
]),
new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [
'replacements' => [
'inheritDocs' => 'inheritDoc',
],
'fix_inline' => false,
]),
new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [
'replacements' => [
'inheritDocs' => 'inheritDoc',
],
'case_sensitive' => true,
]),
]
);
}
public function getPriority()
{
return 11;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('fix_annotation', 'Whether annotation tags should be fixed.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('fix_inline', 'Whether inline tags should be fixed.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('replacements', 'A map of tags to replace.'))
->setAllowedTypes(['array'])
->setNormalizer(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
));
}
$from = trim($from);
$to = trim($to);
if (!$options['case_sensitive']) {
$lowercaseFrom = strtolower($from);
if (isset($normalizedValue[$lowercaseFrom]) && $normalizedValue[$lowercaseFrom] !== $to) {
throw new InvalidOptionsException(sprintf(
'Tag "%s" cannot be configured to be replaced with several different tags when case sensitivity is off.',
$from
));
}
$from = $lowercaseFrom;
}
$normalizedValue[$from] = $to;
}
foreach ($normalizedValue as $from => $to) {
if (isset($normalizedValue[$to]) && $normalizedValue[$to] !== $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([])
->getOption(),
(new FixerOptionBuilder('case_sensitive', 'Whether tags should be replaced only if they have exact same casing.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
if (!$this->configuration['replacements']) {
return;
}
if ($this->configuration['fix_annotation']) {
if ($this->configuration['fix_inline']) {
$regex = '/\b(?<=@)(%s)\b/';
} else {
$regex = '/(?<!\{@)(?<=@)(%s)(?!\})/';
}
} else {
$regex = '/(?<={@)(%s)(?=[ \t}])/';
}
$caseInsensitive = !$this->configuration['case_sensitive'];
$replacements = $this->configuration['replacements'];
$regex = sprintf($regex, implode('|', array_keys($replacements)));
if ($caseInsensitive) {
$regex .= 'i';
}
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$tokens[$index] = new Token([T_DOC_COMMENT, Preg::replaceCallback(
$regex,
function (array $matches) use ($caseInsensitive, $replacements) {
if ($caseInsensitive) {
$matches[1] = strtolower($matches[1]);
}
return $replacements[$matches[1]];
},
$token->getContent()
)]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractPhpdocTypesFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@gmail
*/
final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurationDefinitionFixerInterface
{
private static $possibleTypes = [
'simple' => [
'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(
'<?php
/**
* @param STRING|String[] $bar
*
* @return inT[]
*/
'
),
new CodeSample(
'<?php
/**
* @param BOOL $foo
*
* @return MIXED
*/
',
['groups' => ['simple', 'alias']]
),
]
);
}
public function getPriority()
{
return 16;
}
protected function normalize($type)
{
$lower = strtolower($type);
return \in_array($lower, $this->typesToFix, true) ? $lower : $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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
final class PhpdocTagCasingFixer extends AbstractProxyFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Fixes casing of PHPDoc tags.',
[
new CodeSample("<?php\n/**\n * @inheritdoc\n */\n"),
new CodeSample("<?php\n/**\n * @inheritdoc\n * @Foo\n */\n", [
'tags' => ['foo'],
]),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function configure(array $configuration = null)
{
parent::configure($configuration);
$replacements = [];
foreach ($this->configuration['tags'] as $tag) {
$replacements[$tag] = $tag;
}
$generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename'];
try {
$generalPhpdocTagRenameFixer->configure([
'fix_annotation' => true,
'fix_inline' => true,
'replacements' => $replacements,
'case_sensitive' => false,
]);
} catch (InvalidConfigurationException $exception) {
throw new InvalidFixerConfigurationException(
$this->getName(),
Preg::replace('/^\[.+?\] /', '', $exception->getMessage()),
$exception
);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('tags', 'List of tags to fix with their expected casing.'))
->setAllowedTypes(['array'])
->setDefault(['inheritDoc'])
->getOption(),
]);
}
protected function createProxyFixers()
{
return [new GeneralPhpdocTagRenameFixer()];
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
/**
@gmail
*/
final class PhpdocNoAliasTagFixer extends AbstractProxyFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'No alias PHPDoc tags should be used.',
[
new CodeSample(
'<?php
/**
* @property string $foo
* @property-read string $bar
*
* @link baz
*/
final class Example
{
}
'
),
new CodeSample(
'<?php
/**
* @property string $foo
* @property-read string $bar
*
* @link baz
*/
final class Example
{
}
',
['replacements' => ['link' => 'website']]
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function configure(array $configuration = null)
{
parent::configure($configuration);
$generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename'];
try {
$generalPhpdocTagRenameFixer->configure([
'fix_annotation' => true,
'fix_inline' => false,
'replacements' => $this->configuration['replacements'],
'case_sensitive' => true,
]);
} catch (InvalidConfigurationException $exception) {
throw new InvalidFixerConfigurationException(
$this->getName(),
Preg::replace('/^\[.+?\] /', '', $exception->getMessage()),
$exception
);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolverRootless('replacements', [
(new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.'))
->setAllowedTypes(['array'])
->setDefault([
'property-read' => 'property',
'property-write' => 'property',
'type' => 'var',
'link' => 'see',
])
->getOption(),
], $this->getName());
}
protected function createProxyFixers()
{
return [new GeneralPhpdocTagRenameFixer()];
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
/**
@alt
*/
final class PhpdocIndentFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Docblocks should have the same indentation as the documented subject.',
[new CodeSample('<?php
class DocBlocks
{
/**
* Test constants
*/
const INDENT = 1;
}
')]
);
}
public function getPriority()
{
return 20;
}
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;
}
$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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@seld
@rollerscapes
@alt
@gmail
*/
final class PhpdocAlignFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const ALIGN_LEFT = 'left';
const ALIGN_VERTICAL = 'vertical';
private $regex;
private $regexCommentLine;
private $align;
private static $alignableTags = [
'param',
'property',
'property-read',
'property-write',
'return',
'throws',
'type',
'var',
'method',
];
private static $tagsWithName = [
'param',
'property',
];
private static $tagsWithMethodSignature = [
'method',
];
public function configure(array $configuration = null)
{
parent::configure($configuration);
$tagsWithNameToAlign = array_intersect($this->configuration['tags'], self::$tagsWithName);
$tagsWithMethodSignatureToAlign = array_intersect($this->configuration['tags'], self::$tagsWithMethodSignature);
$tagsWithoutNameToAlign = array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign);
$types = [];
$indent = '(?P<indent>(?: {2}|\t)*)';
if (!empty($tagsWithNameToAlign)) {
$types[] = '(?P<tag>'.implode('|', $tagsWithNameToAlign).')\s+(?P<hint>[^$]+?)\s+(?P<var>(?:&|\.{3})?\$[^\s]+)';
}
if (!empty($tagsWithoutNameToAlign)) {
$types[] = '(?P<tag2>'.implode('|', $tagsWithoutNameToAlign).')\s+(?P<hint2>[^\s]+?)';
}
if (!empty($tagsWithMethodSignatureToAlign)) {
$types[] = '(?P<tag3>'.implode('|', $tagsWithMethodSignatureToAlign).')(\s+(?P<hint3>[^\s(]+)|)\s+(?P<signature>.+\))';
}
$desc = '(?:\s+(?P<desc>\V*))';
$this->regex = '/^'.$indent.' \* @(?:'.implode('|', $types).')'.$desc.'\s*$/u';
$this->regexCommentLine = '/^'.$indent.' \*(?! @)(?:\s+(?P<desc>\V+))(?<!\*\/)\r?$/u';
$this->align = $this->configuration['align'];
}
public function getDefinition()
{
$code = <<<'EOF'
<?php
/**
* @param EngineInterface $templating
* @param string $format
* @param int $code an HTTP response status code
* @param bool $debug
* @param mixed &$reference a parameter passed by reference
*/
EOF;
return new FixerDefinition(
'All items of the given phpdoc tags must be either left-aligned or (by default) aligned vertically.',
[
new CodeSample($code),
new CodeSample($code, ['align' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoBlankLinesAfterPhpdocFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
public function getDefinition()
{
return new FixerDefinition(
'There should not be blank lines between docblock and the documented element.',
[
new CodeSample(
'<?php
/**
* This is the bar class.
*/
class Bar {}
'
),
]
);
}
public function getPriority()
{
return -20;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
static $forbiddenSuccessors = [
T_DOC_COMMENT,
T_COMMENT,
T_WHITESPACE,
T_RETURN,
T_THROW,
T_GOTO,
T_CONTINUE,
T_BREAK,
T_DECLARE,
T_USE,
];
foreach ($tokens as $index => $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"))]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class PhpdocLineSpanFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Changes doc blocks from single to multi line, or reversed. Works for class constants, properties and methods only.',
[
new CodeSample("<?php\n\nclass Foo{\n /** @var bool */\n public \$var;\n}\n"),
new CodeSample(
"<?php\n\nclass Foo{\n /**\n * @var bool\n */\n public \$var;\n}\n",
['property' => '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 = WhitespacesAnalyzer::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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Single line `@var` PHPDoc should have proper spacing.',
[new CodeSample("<?php /**@var MyClass \$a */\n\$a = test();\n")]
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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
);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
final class PhpdocTagTypeFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
public function getDefinition()
{
return new FixerDefinition(
'Forces PHPDoc tags to be either regular annotations or inline.',
[
new CodeSample(
"<?php\n/**\n * {@api}\n */\n"
),
new CodeSample(
"<?php\n/**\n * @inheritdoc\n */\n",
['tags' => ['inheritdoc' => 'inline']]
),
]
);
}
public function getPriority()
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
if (!$this->configuration['tags']) {
return;
}
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$parts = Preg::split(
sprintf(
'/({?@(?:%s)(?:}|\h.*?(?:}|(?=\R)|(?=\h+\*\/)))?)/i',
implode('|', array_map(
function ($tag) {
return preg_quote($tag, '/');
},
array_keys($this->configuration['tags'])
))
),
$token->getContent(),
-1,
PREG_SPLIT_DELIM_CAPTURE
);
for ($i = 1, $max = \count($parts) - 1; $i < $max; $i += 2) {
if (!Preg::match('/^{?(@(.*?)(?:\s[^}]*)?)}?$/', $parts[$i], $matches)) {
continue;
}
$tag = strtolower($matches[2]);
if (!isset($this->configuration['tags'][$tag])) {
continue;
}
if ('inline' === $this->configuration['tags'][$tag]) {
$parts[$i] = '{'.$matches[1].'}';
continue;
}
if (!$this->tagIsSurroundedByText($parts, $i)) {
$parts[$i] = $matches[1];
}
}
$tokens[$index] = new Token([T_DOC_COMMENT, implode('', $parts)]);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('tags', 'The list of tags to fix'))
->setAllowedTypes(['array'])
->setAllowedValues([function ($value) {
foreach ($value as $type) {
if (!\in_array($type, ['annotation', 'inline'], true)) {
throw new InvalidOptionsException("Unknown tag type \"{$type}\".");
}
}
return true;
}])
->setDefault([
'api' => 'annotation',
'author' => 'annotation',
'copyright' => 'annotation',
'deprecated' => 'annotation',
'example' => 'annotation',
'global' => 'annotation',
'inheritDoc' => 'annotation',
'internal' => 'annotation',
'license' => 'annotation',
'method' => 'annotation',
'package' => 'annotation',
'param' => 'annotation',
'property' => 'annotation',
'return' => 'annotation',
'see' => 'annotation',
'since' => 'annotation',
'throws' => 'annotation',
'todo' => 'annotation',
'uses' => 'annotation',
'var' => 'annotation',
'version' => 'annotation',
])
->setNormalizer(function (Options $options, $value) {
$normalized = [];
foreach ($value as $tag => $type) {
$normalized[strtolower($tag)] = $type;
}
return $normalized;
})
->getOption(),
]);
}
private function tagIsSurroundedByText(array $parts, $index)
{
return
Preg::match('/(^|\R)\h*[^@\s]\N*/', $this->cleanComment($parts[$index - 1]))
|| Preg::match('/^.*?\R\s*[^@\s]/', $this->cleanComment($parts[$index + 1]))
;
}
private function cleanComment($comment)
{
$comment = Preg::replace('/^\/\*\*|\*\/$/', '', $comment);
return Preg::replace('/(\R)(\h*\*)?\h*/', '$1', $comment);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractPhpdocTypesFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class PhpdocScalarFixer extends AbstractPhpdocTypesFixer implements ConfigurationDefinitionFixerInterface
{
private static $types = [
'boolean' => '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('<?php
/**
* @param integer $a
* @param boolean $b
* @param real $c
*
* @return double
*/
function sample($a, $b, $c)
{
return sample2($a, $b, $c);
}
'),
new CodeSample(
'<?php
/**
* @param integer $a
* @param boolean $b
* @param real $c
*/
function sample($a, $b, $c)
{
return sample2($a, $b, $c);
}
',
['types' => ['boolean']]
),
]
);
}
public function getPriority()
{
return 15;
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('types', 'A list 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class GeneralPhpdocAnnotationRemoveFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Configured annotations should be omitted from PHPDoc.',
[
new CodeSample(
'<?php
/**
* @internal
* @author John Doe
*/
function foo() {}
',
['annotations' => ['author']]
),
new CodeSample(
'<?php
/**
* @author John Doe
* @package ACME API
* @subpackage Authorization
* @version 1.0
*/
function foo() {}
',
['annotations' => ['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());
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
/**
@gmail
*/
final class PhpdocNoAccessFixer extends AbstractProxyFixer
{
public function getDefinition()
{
return new FixerDefinition(
'`@access` annotations should be omitted from PHPDoc.',
[
new CodeSample(
'<?php
class Foo
{
/**
* @internal
* @access private
*/
private $bar;
}
'
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
protected function createProxyFixers()
{
$fixer = new GeneralPhpdocAnnotationRemoveFixer();
$fixer->configure(['annotations' => ['access']]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocNoEmptyReturnFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
public function getDefinition()
{
return new FixerDefinition(
'`@return void` and `@return null` annotations should be omitted from PHPDoc.',
[
new CodeSample(
'<?php
/**
* @return null
*/
function foo() {}
'
),
new CodeSample(
'<?php
/**
* @return void
*/
function foo() {}
'
),
]
);
}
public function getPriority()
{
return 4;
}
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('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();
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
/**
@localheinz
*/
final class PhpdocOrderByValueFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Order phpdoc tags by value.',
[
new CodeSample(
'<?php
/**
* @covers Foo
* @covers Bar
*/
final class MyTest extends \PHPUnit_Framework_TestCase
{}
'
),
new CodeSample(
'<?php
/**
* @author Bob
* @author Alice
*/
final class MyTest extends \PHPUnit_Framework_TestCase
{}
',
[
'annotations' => [
'author',
],
]
),
]
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound([T_CLASS, T_DOC_COMMENT]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
if ([] === $this->configuration['annotations']) {
return;
}
for ($index = $tokens->count() - 1; $index > 0; --$index) {
foreach ($this->configuration['annotations'] as $type => $typeLowerCase) {
$findPattern = sprintf(
'/@%s\s.+@%s\s/s',
$type,
$type
);
if (
!$tokens[$index]->isGivenKind(T_DOC_COMMENT)
|| 0 === Preg::match($findPattern, $tokens[$index]->getContent())
) {
continue;
}
$docBlock = new DocBlock($tokens[$index]->getContent());
$annotations = $docBlock->getAnnotationsOfType($type);
$annotationMap = [];
if (\in_array($type, ['property', 'property-read', 'property-write'], true)) {
$replacePattern = sprintf(
'/(?s)\*\s*@%s\s+(?P<optionalTypes>.+\s+)?\$(?P<comparableContent>[^\s]+).*/',
$type
);
$replacement = '\2';
} elseif ('method' === $type) {
$replacePattern = '/(?s)\*\s*@method\s+(?P<optionalReturnTypes>.+\s+)?(?P<comparableContent>.+)\(.*/';
$replacement = '\2';
} else {
$replacePattern = sprintf(
'/\*\s*@%s\s+(?P<comparableContent>.+)/',
$typeLowerCase
);
$replacement = '\1';
}
foreach ($annotations as $annotation) {
$rawContent = $annotation->getContent();
$comparableContent = Preg::replace(
$replacePattern,
$replacement,
strtolower(trim($rawContent))
);
$annotationMap[$comparableContent] = $rawContent;
}
$orderedAnnotationMap = $annotationMap;
ksort($orderedAnnotationMap, SORT_STRING);
if ($orderedAnnotationMap === $annotationMap) {
continue;
}
$lines = $docBlock->getLines();
foreach (array_reverse($annotations) as $annotation) {
array_splice(
$lines,
$annotation->getStart(),
$annotation->getEnd() - $annotation->getStart() + 1,
array_pop($orderedAnnotationMap)
);
}
$tokens[$index] = new Token([T_DOC_COMMENT, implode('', $lines)]);
}
}
}
protected function createConfigurationDefinition()
{
$allowedValues = [
'author',
'covers',
'coversNothing',
'dataProvider',
'depends',
'group',
'internal',
'method',
'property',
'property-read',
'property-write',
'requires',
'throws',
'uses',
];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('annotations', 'List of annotations to order, e.g. `["covers"]`.'))
->setAllowedTypes([
'array',
])
->setAllowedValues([
new AllowedValueSubset($allowedValues),
])
->setNormalizer(function (Options $options, $value) {
$normalized = [];
foreach ($value as $index => $annotation) {
$normalized[$annotation] = strtolower($annotation);
}
return $normalized;
})
->setDefault([
'covers',
])
->getOption(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class PhpdocToCommentFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'<?php
$first = true;// needed because by default first docblock is never fixed.
/** This should not be a docblock */
foreach($connections as $key => $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(), '/*')]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocNoUselessInheritdocFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Classy that does not inherit must not have `@inheritdoc` tags.',
[
new CodeSample("<?php\n/** {@inheritdoc} */\nclass Sample\n{\n}\n"),
new CodeSample("<?php\nclass Sample\n{\n /**\n * @inheritdoc\n */\n public function Test()\n {\n }\n}\n"),
]
);
}
public function getPriority()
{
return 6;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class AlignMultilineCommentFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
private $tokenKinds;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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(
'<?php
/**
* This is a DOC Comment
with a line not prefixed with asterisk
*/
'
),
new CodeSample(
'<?php
/*
* This is a doc-like multiline comment
*/
',
['comment_type' => 'phpdocs_like']
),
new CodeSample(
'<?php
/*
* This is a doc-like multiline comment
with a line not prefixed with asterisk
*/
',
['comment_type' => '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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocAnnotationWithoutDotFixer extends AbstractFixer
{
private $tags = ['throws', 'return', 'param', 'internal', 'deprecated', 'var', 'type'];
public function getDefinition()
{
return new FixerDefinition(
'PHPDoc annotation descriptions should not be a sentence.',
[new CodeSample('<?php
/**
* @param string $bar Some string.
*/
function foo ($bar) {}
')]
);
}
public function getPriority()
{
return 17;
}
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->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('/(?<![.。])[.。]\h*(\H+)$/u', '\1', $endLine->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()]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocAddMissingParamAnnotationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'PHPDoc should contain `@param` for all params.',
[
new CodeSample(
'<?php
/**
* @param int $bar
*
* @return void
*/
function f9(string $foo, $bar, $baz) {}
'
),
new CodeSample(
'<?php
/**
* @param int $bar
*
* @return void
*/
function f9(string $foo, $bar, $baz) {}
',
['only_untyped' => true]
),
new CodeSample(
'<?php
/**
* @param int $bar
*
* @return void
*/
function f9(string $foo, $bar, $baz) {}
',
['only_untyped' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class PhpdocVarWithoutNameFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'`@var` and `@type` annotations of classy properties should not contain the name.',
[new CodeSample('<?php
final class Foo
{
/**
* @var int $bar
*/
public $bar;
/**
* @type $baz float
*/
public $baz;
}
')]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\DocBlock\ShortDescription;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class PhpdocTrimConsecutiveBlankLineSeparationFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Removes extra blank lines after summary and after description in PHPDoc.',
[
new CodeSample(
'<?php
/**
* Summary.
*
*
* Description that contain 4 lines,
*
*
* while 2 of them are blank!
*
*
* @param string $foo
*
*
* @dataProvider provideFixCases
*/
function fnc($foo) {}
'
),
]
);
}
public function getPriority()
{
return -41;
}
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());
$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;
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class LogicalOperatorsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Use `&&` and `||` logical operators instead of `and` and `or`.',
[
new CodeSample(
'<?php
if ($a == "foo" and ($b == "bar" or $c == "baz")) {
}
'
),
],
null,
'Risky, because you must double-check if using and/or with lower precedence was intentional.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, '||']);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ConcatSpaceFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $fixCallback;
public function configure(array $configuration = null)
{
parent::configure($configuration);
if ('one' === $this->configuration['spacing']) {
$this->fixCallback = 'fixConcatenationToSingleSpace';
} else {
$this->fixCallback = 'fixConcatenationToNoSpace';
}
}
public function getDefinition()
{
return new FixerDefinition(
'Concatenation should be spaced according configuration.',
[
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n"
),
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n",
['spacing' => 'none']
),
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n",
['spacing' => '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, ' ']);
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NotOperatorWithSpaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Logical NOT operators (`!`) should have leading and trailing whitespaces.',
[new CodeSample(
'<?php
if (!$bar) {
echo "Help!";
}
'
)]
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, ' ']));
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NewWithBracesFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'All instances created with new keyword must be followed by braces.',
[new CodeSample("<?php \$x = new X;\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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(')')]);
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class OperatorLinebreakFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const BOOLEAN_OPERATORS = [[T_BOOLEAN_AND], [T_BOOLEAN_OR], [T_LOGICAL_AND], [T_LOGICAL_OR], [T_LOGICAL_XOR]];
const NON_BOOLEAN_OPERATORS = ['%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '^', '|', [T_AND_EQUAL], [T_CONCAT_EQUAL], [T_DIV_EQUAL], [T_DOUBLE_ARROW], [T_IS_EQUAL], [T_IS_GREATER_OR_EQUAL], [T_IS_IDENTICAL], [T_IS_NOT_EQUAL], [T_IS_NOT_IDENTICAL], [T_IS_SMALLER_OR_EQUAL], [T_MINUS_EQUAL], [T_MOD_EQUAL], [T_MUL_EQUAL], [T_OBJECT_OPERATOR], [T_OR_EQUAL], [T_PAAMAYIM_NEKUDOTAYIM], [T_PLUS_EQUAL], [T_POW], [T_POW_EQUAL], [T_SL], [T_SL_EQUAL], [T_SR], [T_SR_EQUAL], [T_XOR_EQUAL]];
private $position = 'beginning';
private $operators = [];
public function getDefinition()
{
return new FixerDefinition(
'Operators - when multiline - must always be at the beginning or at the end of the line.',
[
new CodeSample('<?php
function foo() {
return $bar ||
$baz;
}
'),
new CodeSample(
'<?php
function foo() {
return $bar
|| $baz;
}
',
['position' => 'end']
),
]
);
}
public function getConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('only_booleans', 'whether to limit operators to only boolean ones'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('position', 'whether to place operators at the beginning or at the end of the line'))
->setAllowedValues(['beginning', 'end'])
->setDefault($this->position)
->getOption(),
]);
}
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->operators = self::BOOLEAN_OPERATORS;
if (!$this->configuration['only_booleans']) {
$this->operators = array_merge($this->operators, self::NON_BOOLEAN_OPERATORS);
if (\PHP_VERSION_ID >= 70000) {
$this->operators[] = [T_COALESCE];
$this->operators[] = [T_SPACESHIP];
}
}
$this->position = $this->configuration['position'];
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$referenceAnalyzer = new ReferenceAnalyzer();
$gotoLabelAnalyzer = new GotoLabelAnalyzer();
$excludedIndices = $this->getExcludedIndices($tokens);
$index = $tokens->count();
while ($index > 1) {
--$index;
if (!$tokens[$index]->equalsAny($this->operators, false)) {
continue;
}
if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) {
continue;
}
if ($referenceAnalyzer->isReference($tokens, $index)) {
continue;
}
if (\in_array($index, $excludedIndices, true)) {
continue;
}
$operatorIndices = [$index];
if ($tokens[$index]->equals(':')) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->equals('?')) {
$operatorIndices = [$prevIndex, $index];
$index = $prevIndex;
}
}
$this->fixOperatorLinebreak($tokens, $operatorIndices);
}
}
private function getExcludedIndices(Tokens $tokens)
{
$indices = [];
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind(T_SWITCH)) {
$indices = array_merge($indices, $this->getCasesColonsForSwitch($tokens, $index));
}
}
return $indices;
}
private function getCasesColonsForSwitch(Tokens $tokens, $switchIndex)
{
return array_map(
static function (CaseAnalysis $caseAnalysis) {
return $caseAnalysis->getColonIndex();
},
(new SwitchAnalyzer())->getSwitchAnalysis($tokens, $switchIndex)->getCases()
);
}
private function fixOperatorLinebreak(Tokens $tokens, array $operatorIndices)
{
$prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices));
$indexStart = $prevIndex + 1;
$nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices));
$indexEnd = $nextIndex - 1;
if (!$this->isMultiline($tokens, $indexStart, $indexEnd)) {
return;
}
if ('beginning' === $this->position) {
if (!$this->isMultiline($tokens, max($operatorIndices), $indexEnd)) {
return;
}
$this->fixMoveToTheBeginning($tokens, $operatorIndices);
return;
}
if (!$this->isMultiline($tokens, $indexStart, min($operatorIndices))) {
return;
}
$this->fixMoveToTheEnd($tokens, $operatorIndices);
}
private function fixMoveToTheBeginning(Tokens $tokens, array $operatorIndices)
{
$prevIndex = $tokens->getNonEmptySibling(min($operatorIndices), -1);
$nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices));
for ($i = $nextIndex - 1; $i > max($operatorIndices); --$i) {
if ($tokens[$i]->isWhitespace() && 1 === Preg::match('/\R/u', $tokens[$i]->getContent())) {
$isWhitespaceBefore = $tokens[$prevIndex]->isWhitespace();
$inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, -1);
if ($isWhitespaceBefore) {
$inserts[] = new Token([T_WHITESPACE, ' ']);
}
$tokens->insertAt($nextIndex, $inserts);
break;
}
}
}
private function fixMoveToTheEnd(Tokens $tokens, array $operatorIndices)
{
$prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices));
$nextIndex = $tokens->getNonEmptySibling(max($operatorIndices), 1);
for ($i = $prevIndex + 1; $i < max($operatorIndices); ++$i) {
if ($tokens[$i]->isWhitespace() && 1 === Preg::match('/\R/u', $tokens[$i]->getContent())) {
$isWhitespaceAfter = $tokens[$nextIndex]->isWhitespace();
$inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, 1);
if ($isWhitespaceAfter) {
array_unshift($inserts, new Token([T_WHITESPACE, ' ']));
}
$tokens->insertAt($prevIndex + 1, $inserts);
break;
}
}
}
private function getReplacementsAndClear(Tokens $tokens, array $indices, $direction)
{
return array_map(
static function ($index) use ($tokens, $direction) {
$clone = $tokens[$index];
if ($tokens[$index + $direction]->isWhitespace()) {
$tokens->clearAt($index + $direction);
}
$tokens->clearAt($index);
return $clone;
},
$indices
);
}
private function isMultiline(Tokens $tokens, $indexStart, $indexEnd)
{
for ($index = $indexStart; $index <= $indexEnd; ++$index) {
if (false !== strpos($tokens[$index]->getContent(), "\n")) {
return true;
}
}
return false;
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class UnaryOperatorSpacesFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Unary operators should be placed adjacent to their operands.',
[new CodeSample("<?php\n\$sample ++;\n-- \$sample;\n\$sample = ! ! \$a;\n\$sample = ~ \$c;\nfunction & foo(){}\n")]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->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;
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class StandardizeIncrementFixer extends AbstractIncrementOperatorFixer
{
const EXPRESSION_END_TOKENS = [
';',
')',
']',
',',
':',
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[T_CLOSE_TAG],
];
public function getDefinition()
{
return new FixerDefinition(
'Increment and decrement operators should be used if possible.',
[
new CodeSample("<?php\n\$i += 1;\n"),
new CodeSample("<?php\n\$i -= 1;\n"),
]
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class TernaryOperatorSpacesFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Standardize spaces around ternary operator.',
[new CodeSample("<?php \$a = \$a ?1 :0;\n")]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound(['?', ':']);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$gotoLabelAnalyzer = new GotoLabelAnalyzer();
$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 ($gotoLabelAnalyzer->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 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, ' ']));
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractAlignFixerHelper;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@alt
*/
final class AlignEqualsFixerHelper extends AbstractAlignFixerHelper
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will be removed in 3.0 version.',
__CLASS__
),
E_USER_DEPRECATED
);
}
protected function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt)
{
for ($index = $startAt; $index < $endAt; ++$index) {
$token = $tokens[$index];
if ($token->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;
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
@gmail
*/
final class IncrementStyleFixer extends AbstractIncrementOperatorFixer implements ConfigurationDefinitionFixerInterface
{
const STYLE_PRE = 'pre';
const STYLE_POST = 'post';
public function getDefinition()
{
return new FixerDefinition(
'Pre- or post-increment and decrement operators should be used if possible.',
[
new CodeSample("<?php\n\$a++;\n\$b--;\n"),
new CodeSample(
"<?php\n++\$a;\n--\$b;\n",
['style' => 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NotOperatorWithSuccessorSpaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Logical NOT operators (`!`) should have one trailing whitespace.',
[new CodeSample(
'<?php
if (!$bar) {
echo "Help!";
}
'
)]
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, ' ']);
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class StandardizeNotEqualsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Replace all `<>` with `!=`.',
[new CodeSample("<?php\n\$a = \$b <> \$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, '!=']);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class TernaryToNullCoalescingFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Use `null` coalescing operator `??` where possible. Requires PHP >= 7.0.',
[
new VersionSpecificCodeSample(
"<?php\n\$sample = isset(\$a) ? \$a : \$b;\n",
new VersionSpecification(70000)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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;
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Console\Command\HelpCommand;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class BinaryOperatorSpacesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const SINGLE_SPACE = 'single_space';
const NO_SPACE = 'no_space';
const ALIGN = 'align';
const ALIGN_SINGLE_SPACE = 'align_single_space';
const ALIGN_SINGLE_SPACE_MINIMAL = 'align_single_space_minimal';
/**
@const
*/
const ALIGN_PLACEHOLDER = "\x2 ALIGNABLE%d \x3";
private $deepestLevel;
private $currentLevel;
private static $allowedValues = [
self::ALIGN,
self::ALIGN_SINGLE_SPACE,
self::ALIGN_SINGLE_SPACE_MINIMAL,
self::SINGLE_SPACE,
self::NO_SPACE,
null,
];
private static $supportedOperators = [
'=',
'*',
'/',
'%',
'<',
'>',
'|',
'^',
'+',
'-',
'&',
'&=',
'&&',
'||',
'.=',
'/=',
'=>',
'==',
'>=',
'===',
'!=',
'<>',
'!==',
'<=',
'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(
"<?php\n\$a= 1 + \$b^ \$d !== \$e or \$f;\n"
),
new CodeSample(
'<?php
$aa= 1;
$b=2;
$c = $d xor $e;
$f -= 1;
',
['operators' => ['=' => 'align', 'xor' => null]]
),
new CodeSample(
'<?php
$a = $b +=$c;
$d = $ee+=$f;
$g = $b +=$c;
$h = $ee+=$f;
',
['operators' => ['+=' => 'align_single_space']]
),
new CodeSample(
'<?php
$a = $b===$c;
$d = $f === $g;
$h = $i=== $j;
',
['operators' => ['===' => 'align_single_space_minimal']]
),
new CodeSample(
'<?php
$foo = \json_encode($bar, JSON_PRESERVE_ZERO_FRACTION | JSON_PRETTY_PRINT);
',
['operators' => ['|' => '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;
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class ObjectOperatorWithoutWhitespaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There should not be space before or after object `T_OBJECT_OPERATOR` `->`.',
[new CodeSample("<?php \$a -> 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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractAlignFixerHelper;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
@alt
*/
final class AlignDoubleArrowFixerHelper extends AbstractAlignFixerHelper
{
private $currentLevel = 0;
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will be removed in 3.0 version.',
__CLASS__
),
E_USER_DEPRECATED
);
}
protected function injectAlignmentPlaceholders(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, $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;
}
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class PreIncrementFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Pre incrementation/decrementation should be used if possible.',
[new CodeSample("<?php\n\$a++;\n\$b--;\n")]
);
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new IncrementStyleFixer();
$fixer->configure(['style' => 'pre']);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class TernaryToElvisOperatorFixer extends AbstractFixer
{
const VALID_BEFORE_ENDTYPES = [
'=',
[T_OPEN_TAG],
[T_OPEN_TAG_WITH_ECHO],
'(',
',',
';',
'[',
'{',
'}',
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[T_AND_EQUAL],
[T_CONCAT_EQUAL],
[T_DIV_EQUAL],
[T_MINUS_EQUAL],
[T_MOD_EQUAL],
[T_MUL_EQUAL],
[T_OR_EQUAL],
[T_PLUS_EQUAL],
[T_POW_EQUAL],
[T_SL_EQUAL],
[T_SR_EQUAL],
[T_XOR_EQUAL],
];
public function getDefinition()
{
return new FixerDefinition(
'Use the Elvis operator `?:` where possible.',
[
new CodeSample(
"<?php\n\$foo = \$foo ? \$foo : 1;\n"
),
new CodeSample(
"<?php \$foo = \$bar[a()] ? \$bar[a()] : 1; # \"risky\" sample, \"a()\" only gets called once after fixing\n"
),
],
null,
'Risky when relying on functions called on both sides of the `?` operator.'
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound('?');
}
public function isRisky()
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$blockEdgeDefinitions = Tokens::getBlockEdgeDefinitions();
for ($index = \count($tokens) - 5; $index > 1; --$index) {
if (!$tokens[$index]->equals('?')) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->equals(':')) {
continue;
}
$beforeOperator = $this->getBeforeOperator($tokens, $index, $blockEdgeDefinitions);
if (null === $beforeOperator) {
continue;
}
$afterOperator = $this->getAfterOperator($tokens, $index);
if ($this->rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) {
$this->clearMeaningfulFromRange($tokens, $afterOperator);
}
}
}
private function getBeforeOperator(Tokens $tokens, $index, array $blockEdgeDefinitions)
{
$index = $tokens->getPrevMeaningfulToken($index);
$before = ['end' => $index];
while (!$tokens[$index]->equalsAny(self::VALID_BEFORE_ENDTYPES)) {
if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) {
return null;
}
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null === $blockType || $blockType['isStart']) {
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
continue;
}
$blockType = $blockEdgeDefinitions[$blockType['type']];
$openCount = 1;
do {
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) {
return null;
}
if ($tokens[$index]->equals($blockType['start'])) {
++$openCount;
continue;
}
if ($tokens[$index]->equals($blockType['end'])) {
--$openCount;
}
} while (1 >= $openCount);
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
}
if (!isset($before['start'])) {
return null;
}
return $before;
}
private function getAfterOperator(Tokens $tokens, $index)
{
$index = $tokens->getNextMeaningfulToken($index);
$after = ['start' => $index];
while (!$tokens[$index]->equals(':')) {
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
}
$after['end'] = $index;
$index = $tokens->getNextMeaningfulToken($index);
}
return $after;
}
private function rangeEqualsRange(Tokens $tokens, array $range1, array $range2)
{
$leftStart = $range1['start'];
$leftEnd = $range1['end'];
while ($tokens[$leftStart]->equals('(') && $tokens[$leftEnd]->equals(')')) {
$leftStart = $tokens->getNextMeaningfulToken($leftStart);
$leftEnd = $tokens->getPrevMeaningfulToken($leftEnd);
}
$rightStart = $range2['start'];
$rightEnd = $range2['end'];
while ($tokens[$rightStart]->equals('(') && $tokens[$rightEnd]->equals(')')) {
$rightStart = $tokens->getNextMeaningfulToken($rightStart);
$rightEnd = $tokens->getPrevMeaningfulToken($rightEnd);
}
while ($leftStart <= $leftEnd && $rightStart <= $rightEnd) {
if (
!$tokens[$leftStart]->equals($tokens[$rightStart])
&& !($tokens[$leftStart]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]]) && $tokens[$rightStart]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]]))
&& !($tokens[$leftStart]->equalsAny([']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]) && $tokens[$rightStart]->equalsAny([']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]))
) {
return false;
}
$leftStart = $tokens->getNextMeaningfulToken($leftStart);
$rightStart = $tokens->getNextMeaningfulToken($rightStart);
}
return $leftStart > $leftEnd && $rightStart > $rightEnd;
}
private function clearMeaningfulFromRange(Tokens $tokens, array $range)
{
for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class SelfAccessorFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Inside class or interface element `self` should be preferred to the class name itself.',
[
new CodeSample(
'<?php
class Sample
{
const BAZ = 1;
const BAR = Sample::BAZ;
public function getBar()
{
return Sample::BAR;
}
}
'
),
],
null,
'Risky when using dynamic calls like get_called_class() or late static binding.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUnneededFinalMethodFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'A `final` class must not have `final` methods and `private` methods must not be `final`.',
[
new CodeSample(
'<?php
final class Foo
{
final public function foo1() {}
final protected function bar() {}
final private function baz() {}
}
class Bar
{
final private function bar1() {}
}
'
),
new CodeSample(
'<?php
final class Foo
{
final private function baz() {}
}
class Bar
{
final private function bar1() {}
}
',
['private_methods' => false]
),
],
null,
'Risky when child class overrides a `private` method.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('private_methods', 'Private methods of non-`final` classes must not be declared `final`.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
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) || !$this->configuration['private_methods'])) {
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());
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class OrderedTraitsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Trait `use` statements must be sorted alphabetically.',
[
new CodeSample("<?php class Foo { \nuse Z; use A; }\n"),
],
null,
'Risky when depending on order of the imports.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(CT::T_USE_TRAIT);
}
public function isRisky()
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($this->findUseStatementsGroups($tokens) as $uses) {
$this->sortUseStatements($tokens, $uses);
}
}
private function findUseStatementsGroups(Tokens $tokens)
{
$uses = [];
for ($index = 1, $max = \count($tokens); $index < $max; ++$index) {
$token = $tokens[$index];
if ($token->isWhitespace() || $token->isComment()) {
continue;
}
if (!$token->isGivenKind(CT::T_USE_TRAIT)) {
if (\count($uses) > 0) {
yield $uses;
$uses = [];
}
continue;
}
$endIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
if ($tokens[$endIndex]->equals('{')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex);
}
$use = [];
for ($i = $index; $i <= $endIndex; ++$i) {
$use[] = $tokens[$i];
}
$uses[$index] = Tokens::fromArray($use);
$index = $endIndex;
}
}
private function sortUseStatements(Tokens $tokens, array $uses)
{
foreach ($uses as $use) {
$this->sortMultipleTraitsInStatement($use);
}
$this->sort($tokens, $uses);
}
private function sortMultipleTraitsInStatement(Tokens $use)
{
$traits = [];
$indexOfName = null;
$name = [];
for ($index = 0, $max = \count($use); $index < $max; ++$index) {
$token = $use[$index];
if ($token->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
$name[] = $token;
if (null === $indexOfName) {
$indexOfName = $index;
}
continue;
}
if ($token->equalsAny([',', ';', '{'])) {
$traits[$indexOfName] = Tokens::fromArray($name);
$name = [];
$indexOfName = null;
}
if ($token->equals('{')) {
$index = $use->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
}
$this->sort($use, $traits);
}
private function sort(Tokens $tokens, array $elements)
{
$toTraitName = static function (Tokens $use) {
$string = '';
foreach ($use as $token) {
if ($token->equalsAny([';', '{'])) {
break;
}
if ($token->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
$string .= $token->getContent();
}
}
return ltrim($string, '\\');
};
$sortedElements = $elements;
uasort($sortedElements, static function (Tokens $useA, Tokens $useB) use ($toTraitName) {
return strcasecmp($toTraitName($useA), $toTraitName($useB));
});
$sortedElements = array_combine(
array_keys($elements),
array_values($sortedElements)
);
foreach (array_reverse($sortedElements, true) as $index => $tokensToInsert) {
$tokens->overrideRange(
$index,
$index + \count($elements[$index]) - 1,
$tokensToInsert
);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class OrderedInterfacesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const OPTION_DIRECTION = 'direction';
const OPTION_ORDER = 'order';
const DIRECTION_ASCEND = 'ascend';
const DIRECTION_DESCEND = 'descend';
const ORDER_ALPHA = 'alpha';
const ORDER_LENGTH = 'length';
private $supportedDirectionOptions = [
self::DIRECTION_ASCEND,
self::DIRECTION_DESCEND,
];
private $supportedOrderOptions = [
self::ORDER_ALPHA,
self::ORDER_LENGTH,
];
public function getDefinition()
{
return new FixerDefinition(
'Orders the interfaces in an `implements` or `interface extends` clause.',
[
new CodeSample(
"<?php\n\nfinal class ExampleA implements Gamma, Alpha, Beta {}\n\ninterface ExampleB extends Gamma, Alpha, Beta {}\n"
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements Gamma, Alpha, Beta {}\n\ninterface ExampleB extends Gamma, Alpha, Beta {}\n",
[self::OPTION_DIRECTION => self::DIRECTION_DESCEND]
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements MuchLonger, Short, Longer {}\n\ninterface ExampleB extends MuchLonger, Short, Longer {}\n",
[self::OPTION_ORDER => self::ORDER_LENGTH]
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements MuchLonger, Short, Longer {}\n\ninterface ExampleB extends MuchLonger, Short, Longer {}\n",
[
self::OPTION_ORDER => 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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ProtectedToPrivateFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Converts `protected` variables and methods to `private` where possible.',
[
new CodeSample(
'<?php
final class Sample
{
protected $a;
protected function test()
{
}
}
'
),
]
);
}
public function getPriority()
{
return 66;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class VisibilityRequiredFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Visibility MUST be declared on all properties and methods; `abstract` and `final` MUST be declared before the visibility; `static` MUST be declared after the visibility.',
[
new CodeSample(
'<?php
class Sample
{
var $a;
static protected $var_foo2;
function A()
{
}
}
'
),
new VersionSpecificCodeSample(
'<?php
class Sample
{
const SAMPLE = 1;
}
',
new VersionSpecification(70100),
['elements' => ['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);
$propertyTypeDeclarationKinds = [T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION];
foreach (array_reverse($tokensAnalyzer->getClassyElements(), 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class MethodSeparationFixer extends AbstractProxyFixer implements DeprecatedFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Methods must be separated with one blank line.',
[
new CodeSample(
'<?php
final class Sample
{
protected function foo()
{
}
protected function bar()
{
}
}
'
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new ClassAttributesSeparationFixer();
$fixer->configure(['elements' => ['method' => ClassAttributesSeparationFixer::SPACING_ONE]]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class SelfStaticAccessorFixer extends AbstractFixer
{
private $tokensAnalyzer;
public function getDefinition()
{
return new FixerDefinition(
'Inside a `final` class or anonymous class `self` should be preferred to `static`.',
[
new CodeSample(
'<?php
final class Sample
{
private static $A = 1;
public function getBar()
{
return static::class.static::test().static::$A;
}
private static function test()
{
return \'test\';
}
}
'
),
new CodeSample(
'<?php
final class Foo
{
public function bar()
{
return new static();
}
}
'
),
new CodeSample(
'<?php
final class Foo
{
public function isBar()
{
return $foo instanceof static;
}
}
'
),
new VersionSpecificCodeSample(
'<?php
$a = new class() {
public function getBar()
{
return static::class;
}
};
',
new VersionSpecification(70000)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleTraitInsertPerStatementFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Each trait `use` must be done as single statement.',
[
new CodeSample(
'<?php
final class Example
{
use Foo, Bar;
}
'
),
]
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class OrderedClassElementsFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const SORT_ALPHA = 'alpha';
const SORT_NONE = 'none';
private static $typeHierarchy = [
'use_trait' => 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_abstract' => ['method'],
'method_static' => ['method'],
'method_public' => ['method', 'public'],
'method_protected' => ['method', 'protected'],
'method_private' => ['method', 'private'],
'method_public_abstract' => ['method_abstract', 'method_public'],
'method_protected_abstract' => ['method_abstract', 'method_protected'],
'method_public_abstract_static' => ['method_abstract', 'method_static', 'method_public'],
'method_protected_abstract_static' => ['method_abstract', 'method_static', 'method_protected'],
'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(
'<?php
final class Example
{
use BarTrait;
use BazTrait;
const C1 = 1;
const C2 = 2;
protected static $protStatProp;
public static $pubStatProp1;
public $pubProp1;
protected $protProp;
var $pubProp2;
private static $privStatProp;
private $privProp;
public static $pubStatProp2;
public $pubProp3;
protected function __construct() {}
private static function privStatFunc() {}
public function pubFunc1() {}
public function __toString() {}
protected function protFunc() {}
function pubFunc2() {}
public static function pubStatFunc1() {}
public function pubFunc3() {}
static function pubStatFunc2() {}
private function privFunc() {}
public static function pubStatFunc3() {}
protected static function protStatFunc() {}
public function __destruct() {}
}
'
),
new CodeSample(
'<?php
class Example
{
public function A(){}
private function B(){}
}
',
['order' => ['method_private', 'method_public']]
),
new CodeSample(
'<?php
class Example
{
public function D(){}
public function B(){}
public function A(){}
public function C(){}
}
',
['order' => ['method_public'], 'sort_algorithm' => '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 AliasedFixerOptionBuilder(
new FixerOptionBuilder('sort_algorithm', 'How multiple occurrences of same type statements should be sorted'),
'sortAlgorithm'
))
->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',
'abstract' => false,
'static' => false,
];
for ($i = $startIndex;; ++$i) {
$token = $tokens[$i];
if ($token->equals('}')) {
return $elements;
}
if ($token->isGivenKind(T_ABSTRACT)) {
$element['abstract'] = true;
continue;
}
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['abstract']) {
$type .= '_abstract';
}
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['sort_algorithm'];
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);
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class ClassDefinitionFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Whitespace around the keywords of a class, trait or interfaces definition should be one space.',
[
new CodeSample(
'<?php
class Foo extends Bar implements Baz, BarBaz
{
}
final class Foo extends Bar implements Baz, BarBaz
{
}
trait Foo
{
}
'
),
new VersionSpecificCodeSample(
'<?php
$foo = new class extends Bar implements Baz, BarBaz {};
',
new VersionSpecification(70100)
),
new CodeSample(
'<?php
class Foo
extends Bar
implements Baz, BarBaz
{}
',
['single_line' => true]
),
new CodeSample(
'<?php
class Foo
extends Bar
implements Baz
{}
',
['single_item_single_line' => true]
),
new CodeSample(
'<?php
interface Bar extends
Bar, BarBaz, FooBarBaz
{}
',
['multi_line_extends_each_single_line' => 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;
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class NoPhp4ConstructorFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Convert PHP4-style constructors to `__construct`.',
[
new CodeSample('<?php
class Foo
{
public function Foo($bar)
{
}
}
'),
],
null,
'Risky when old style constructor being fixed is overridden or overrides parent one.'
);
}
public function getPriority()
{
return 75;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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,
];
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
@gmail
*/
final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
'<?php
final class Example
{
const FOO_1 = 1, FOO_2 = 2;
private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
}
'
),
new CodeSample(
'<?php
final class Example
{
const FOO_1 = 1, FOO_2 = 2;
private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
}
',
['elements' => ['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;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoNullPropertyInitializationFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Properties MUST not be explicitly initialized with `null` except when they have a type declaration (PHP 7.4).',
[
new CodeSample(
'<?php
class Foo {
public $foo = null;
}
'
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class FinalClassFixer extends AbstractProxyFixer
{
public function getDefinition()
{
return new FixerDefinition(
'All classes must be final, except abstract ones and Doctrine entities.',
[
new CodeSample(
'<?php
class MyApp {}
'
),
],
'No exception and no configuration are intentional. Beside Doctrine entities and of course abstract classes, there is no single reason not to declare all classes final. '
.'If you want to subclass a class, mark the parent class as abstract and create two child classes, one empty if necessary: you\'ll gain much more fine grained type-hinting. '
.'If you need to mock a standalone class, create an interface, or maybe it\'s a value-object that shouldn\'t be mocked at all. '
.'If you need to extend a standalone class, create an interface and use the Composite pattern. '
.'If you aren\'t ready yet for serious OOP, go with FinalInternalClassFixer, it\'s fine.',
'Risky when subclassing non-abstract classes.'
);
}
protected function createProxyFixers()
{
$fixer = new FinalInternalClassFixer();
$fixer->configure([
'annotation_include' => [],
'consider_absent_docblock_as_internal_class' => true,
]);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
const SPACING_NONE = 'none';
const SPACING_ONE = 'one';
const SUPPORTED_SPACINGS = [self::SPACING_NONE, self::SPACING_ONE];
const SUPPORTED_TYPES = ['const', 'method', 'property'];
private $classElementTypes = [];
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->classElementTypes = [];
foreach ($this->configuration['elements'] as $elementType => $spacing) {
$this->classElementTypes[$elementType] = $spacing;
}
}
public function getDefinition()
{
return new FixerDefinition(
'Class, trait and interface elements must be separated with one or none blank line.',
[
new CodeSample(
'<?php
final class Sample
{
protected function foo()
{
}
protected function bar()
{
}
}
'
),
new CodeSample(
'<?php
class Sample
{private $a; // a is awesome
/** second in a hour */
private $b;
}
',
['elements' => ['property' => self::SPACING_ONE]]
),
new CodeSample(
'<?php
class Sample
{
const A = 1;
/** seconds in some hours */
const B = 3600;
}
',
['elements' => ['const' => self::SPACING_ONE]]
),
]
);
}
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;
}
$spacing = $this->classElementTypes[$element['type']];
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, $spacing);
$this->fixSpaceAboveClassElement($tokens, $classStart, $index, $spacing);
continue;
}
$this->fixSpaceBelowClassElement($tokens, $classEnd, $tokens->getNextTokenOfKind($index, [';']), $spacing);
$this->fixSpaceAboveClassElement($tokens, $classStart, $index, $spacing);
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'Dictionary of `const|method|property` => `none|one` values.'))
->setNormalizer(static function (Options $options, $values) {
$deprecated = array_intersect($values, self::SUPPORTED_TYPES);
if (\count($deprecated) > 0) {
$message = 'A list of elements is deprecated, use a dictionary of `const|method|property` => `none|one` instead.';
@trigger_error($message, E_USER_DEPRECATED);
return array_fill_keys($deprecated, self::SPACING_ONE);
}
return $values;
})
->setAllowedTypes(['array'])
->setAllowedValues([static function ($option) {
$deprecated = array_intersect($option, self::SUPPORTED_TYPES);
if (\count($deprecated) > 0) {
$option = array_fill_keys($deprecated, self::SPACING_ONE);
}
foreach ($option as $type => $spacing) {
if (!\in_array($type, self::SUPPORTED_TYPES, true)) {
throw new InvalidOptionsException(
sprintf(
'Unexpected element type, expected any of "%s", got "%s".',
implode('", "', self::SUPPORTED_TYPES),
\is_object($type) ? \get_class($type) : \gettype($type).'#'.$type
)
);
}
if (!\in_array($spacing, self::SUPPORTED_SPACINGS, true)) {
throw new InvalidOptionsException(
sprintf(
'Unexpected spacing for element type "%s", expected any of "%s", got "%s".',
$spacing,
implode('", "', self::SUPPORTED_SPACINGS),
\is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing)
)
);
}
}
return true;
}])
->setDefault([
'const' => self::SPACING_ONE,
'method' => self::SPACING_ONE,
'property' => self::SPACING_ONE,
])
->getOption(),
]);
}
private function fixSpaceBelowClassElement(Tokens $tokens, $classEndIndex, $elementEndIndex, $spacing)
{
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);
}
if ($tokens[$nextNotWhite]->isGivenKind(T_FUNCTION)) {
$this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, 2);
return;
}
$this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex || self::SPACING_NONE === $spacing ? 1 : 2);
}
private function fixSpaceBelowClassMethod(Tokens $tokens, $classEndIndex, $elementEndIndex, $spacing)
{
$nextNotWhite = $tokens->getNextNonWhitespace($elementEndIndex);
$this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex || self::SPACING_NONE === $spacing ? 1 : 2);
}
private function fixSpaceAboveClassElement(Tokens $tokens, $classStartIndex, $elementIndex, $spacing)
{
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 ($tokens[$nonWhiteAbove]->isGivenKind(T_DOC_COMMENT)) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1);
$nonWhiteAbovePHPDoc = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1);
$this->correctLineBreaks($tokens, $nonWhiteAbovePHPDoc, $nonWhiteAbove, $nonWhiteAbovePHPDoc === $classStartIndex ? 1 : 2);
return;
}
if ($tokens[$nonWhiteAbove]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1);
$nonWhiteAbove = $this->findAttributeBlockStart($tokens, $nonWhiteAbove);
$nonWhiteAboveComment = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1);
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $classStartIndex ? 1 : 2);
return;
}
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, $nonWhiteAbove === $classStartIndex || self::SPACING_NONE === $spacing ? 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;
}
private function findAttributeBlockStart(Tokens $tokens, $index)
{
$start = $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
for ($i = $index - 1; $i > 0; --$i) {
if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i);
continue;
}
if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) {
break;
}
}
return $start;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class FinalStaticAccessFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Converts `static` access to `self` access in `final` classes.',
[
new CodeSample(
'<?php
final class Sample
{
public function getFoo()
{
return static::class;
}
}
'
),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
return [new SelfStaticAccessorFixer()];
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
public function getDefinition()
{
return new FixerDefinition(
'There should be no empty lines after class opening brace.',
[
new CodeSample(
'<?php
final class Sample
{
protected function foo()
{
}
}
'
),
]
);
}
public function getPriority()
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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)]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
final class FinalInternalClassFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function configure(array $configuration = null)
{
parent::configure($configuration);
$intersect = array_intersect_assoc(
$this->configuration['annotation_include'],
$this->configuration['annotation_exclude']
);
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("<?php\n/**\n * @internal\n */\nclass Sample\n{\n}\n"),
new CodeSample(
"<?php\n/**\n * @CUSTOM\n */\nclass A{}\n\n/**\n * @CUSTOM\n * @not-fix\n */\nclass B{}\n",
[
'annotation_include' => ['@Custom'],
'annotation_exclude' => ['@not-fix'],
]
),
],
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 AliasedFixerOptionBuilder(
new FixerOptionBuilder('annotation_include', 'Class level annotations tags that must be set in order to fix the class. (case insensitive)'),
'annotation-white-list'
))
->setAllowedTypes(['array'])
->setAllowedValues($annotationsAsserts)
->setDefault(['@internal'])
->setNormalizer($annotationsNormalizer)
->getOption(),
(new AliasedFixerOptionBuilder(
new FixerOptionBuilder('annotation_exclude', 'Class level annotations tags that must be omitted to fix the class, even if all of the white list ones are used as well. (case insensitive)'),
'annotation-black-list'
))
->setAllowedTypes(['array'])
->setAllowedValues($annotationsAsserts)
->setDefault([
'@final',
'@Entity',
'@ORM\Entity',
'@ORM\Mapping\Entity',
'@Mapping\Entity',
])
->setNormalizer($annotationsNormalizer)
->getOption(),
(new AliasedFixerOptionBuilder(
new FixerOptionBuilder('consider_absent_docblock_as_internal_class', 'Should classes without any DocBlock be fixed to final?'),
'consider-absent-docblock-as-internal-class'
))
->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_exclude'] as $tagStart => $true) {
if (0 === strpos($tag, $tagStart)) {
return false;
}
}
$tags[$tag] = true;
}
foreach ($this->configuration['annotation_include'] as $tag => $true) {
if (!isset($tags[$tag])) {
return false;
}
}
return true;
}
}
<?php
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FinalPublicMethodForAbstractClassFixer extends AbstractFixer
{
private $magicMethods = [
'__construct' => 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(
'<?php
abstract class AbstractMachine
{
public function start()
{}
}
'
),
],
'Enforce API encapsulation in an inheritance architecture. '
.'If you want to override a method, use the Template method pattern.',
'Risky when overriding `public` methods of `abstract` classes.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, ' ']),
]
);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ClassUsage;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class DateTimeImmutableFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Class `DateTimeImmutable` should be used instead of `DateTime`.',
[new CodeSample("<?php\nnew DateTime();\n")],
null,
'Risky when the code relies on modifying `DateTime` objects or if any of the `date_create*` functions are overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]);
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoTrailingWhitespaceInStringFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML]);
}
public function isRisky()
{
return true;
}
public function getDefinition()
{
return new FixerDefinition(
'There must be no trailing whitespace in strings.',
[
new CodeSample(
"<?php \$a = ' \n foo \n';\n"
),
],
null,
'Changing the whitespaces in strings might affect string comparisons and outputs.'
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = $tokens->count() - 1, $last = true; $index >= 0; --$index, $last = false) {
$token = $tokens[$index];
if (!$token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML])) {
continue;
}
$isInlineHtml = $token->isGivenKind(T_INLINE_HTML);
$regex = $isInlineHtml && $last ? '/\h+(?=\R|$)/' : '/\h+(?=\R)/';
$content = Preg::replace($regex, '', $token->getContent());
if ($token->getContent() === $content) {
continue;
}
if (!$isInlineHtml || 0 === $index) {
$this->updateContent($tokens, $index, $content);
continue;
}
$prev = $index - 1;
if ($tokens[$prev]->equals([T_CLOSE_TAG, '?>']) && Preg::match('/^\R/', $content, $match)) {
$tokens[$prev] = new Token([T_CLOSE_TAG, $tokens[$prev]->getContent().$match[0]]);
$content = substr($content, \strlen($match[0]));
$content = false === $content ? '' : $content;
}
$this->updateContent($tokens, $index, $content);
}
}
private function updateContent(Tokens $tokens, $index, $content)
{
if ('' === $content) {
$tokens->clearAt($index);
return;
}
$tokens[$index] = new Token([$tokens[$index]->getId(), $content]);
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoBinaryStringFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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("<?php \$a = b'foo';\n"),
new CodeSample("<?php \$a = b<<<EOT\nfoo\nEOT;\n"),
]
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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)]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SimpleToComplexStringVariableFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Converts explicit variables in double-quoted strings and heredoc syntax from simple to complex format (`${` to `{$`).',
[
new CodeSample(
<<<'EOT'
<?php
$name = 'World';
echo "Hello ${name}!";
EOT
),
new CodeSample(
<<<'EOT'
<?php
$name = 'World';
echo <<<TEST
Hello ${name}!
TEST;
EOT
),
],
"Doesn't touch implicit variables. Works together nicely with `explicit_string_variable`."
);
}
public function getPriority()
{
return -10;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, '}']),
]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class StringLineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->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(
"<?php \$a = 'my\r\nmulti\nline\r\nstring';\r\n"
),
],
null,
'Changing the line endings of multi-line strings might affect string comparisons and outputs.'
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$ending = $this->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()
),
]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleQuoteFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
$codeSample = <<<'EOF'
<?php
$a = "sample";
$b = "sample with 'single-quotes'";
EOF;
return new FixerDefinition(
'Convert double quotes to single quotes for simple strings.',
[
new CodeSample($codeSample),
new CodeSample(
$codeSample,
['strings_containing_single_quote_chars' => 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('/(?<!\\\\)(?:\\\\{2})*\\\\(?!["$\\\\])/', $content)
) {
$content = substr($content, 1, -1);
$content = str_replace(['\\"', '\\$', '\''], ['"', '$', '\\\''], $content);
$tokens[$index] = new Token([T_CONSTANT_ENCAPSED_STRING, $prefix.'\''.$content.'\'']);
}
}
}
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('strings_containing_single_quote_chars', 'Whether to fix double-quoted strings that contains single-quotes.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class EscapeImplicitBackslashesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
$codeSample = <<<'EOF'
<?php
$singleQuoted = 'String with \" and My\Prefix\\';
$doubleQuoted = "Interpret my \n but not my \a";
$hereDoc = <<<HEREDOC
Interpret my \100 but not my \999
HEREDOC;
EOF;
return new FixerDefinition(
'Escape implicit backslashes in strings and heredocs to ease the understanding of which are special chars interpreted by PHP and which not.',
[
new CodeSample($codeSample),
new CodeSample(
$codeSample,
['single_quoted' => 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 = '/(?<!\\\\)\\\\((?:\\\\\\\\)*)(?![\\\'\\\\])/';
static $doubleQuotedRegex = '/(?<!\\\\)\\\\((?:\\\\\\\\)*)(?![efnrtv$"\\\\0-7]|x[0-9A-Fa-f]|u{)/';
static $heredocSyntaxRegex = '/(?<!\\\\)\\\\((?:\\\\\\\\)*)(?![efnrtv$\\\\0-7]|x[0-9A-Fa-f]|u{)/';
$doubleQuoteOpened = false;
foreach ($tokens as $index => $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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class HeredocToNowdocFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Convert `heredoc` to `nowdoc` where possible.',
[
new CodeSample(
<<<'EOF'
<?php $a = <<<"TEST"
Foo
TEST;
EOF
),
]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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('/(?<!\\\\)(?:\\\\{2})*\\\\(?![$\\\\])/', $content)) {
continue;
}
$tokens[$index] = $this->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()),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ExplicitStringVariableFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax.',
[new CodeSample(
<<<'EOT'
<?php
$a = "My name is $name !";
$b = "I live in $state->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())
;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class StaticLambdaFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Lambdas not (indirect) referencing `$this` must be declared `static`.',
[new CodeSample("<?php\n\$a = function () use (\$b)\n{ echo \$b;\n};\n")],
null,
'Risky when using `->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;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NullableTypeDeclarationForDefaultNullValueFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Adds or removes `?` before type declarations for parameters with a default `null` value.',
[
new VersionSpecificCodeSample(
"<?php\nfunction sample(string \$str = null)\n{}\n",
new VersionSpecification(70100)
),
new VersionSpecificCodeSample(
"<?php\nfunction sample(?string \$str = null)\n{}\n",
new VersionSpecification(70100),
['use_nullable_type_declaration' => 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()
|| false !== strpos($argumentInfo->getTypeAnalysis()->getName(), '|')
|| !$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());
}
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ImplodeCallFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Function `implode` must be called with 2 arguments in the documented order.',
[
new CodeSample("<?php\nimplode(\$pieces, '');\n"),
new CodeSample("<?php\nimplode(\$pieces);\n"),
],
null,
'Risky when the function `implode` is overridden.'
);
}
public function isRisky()
{
return true;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class NoSpacesAfterFunctionNameFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.',
[new CodeSample("<?php\nrequire ('sample.php');\necho (test (3));\nexit (1);\n\$func ();\n")]
);
}
public function getPriority()
{
return 2;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class UseArrowFunctionsFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Anonymous functions with one-liner return statement must use arrow functions.',
[
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
foo(function ($a) use ($b) {
return $a + $b;
});
SAMPLE
,
new VersionSpecification(70400)
),
],
null,
'Risky when using `isset()` on outside variables that are not imported with `use ()`.'
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 70400 && $tokens->isAllTokenKindsFound([T_FUNCTION, T_RETURN]);
}
public function isRisky()
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$analyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$analyzer->isLambda($index)) {
continue;
}
$parametersStart = $tokens->getNextMeaningfulToken($index);
if ($tokens[$parametersStart]->isGivenKind(CT::T_RETURN_REF)) {
$parametersStart = $tokens->getNextMeaningfulToken($parametersStart);
}
$parametersEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $parametersStart);
if ($this->isMultilined($tokens, $parametersStart, $parametersEnd)) {
continue;
}
$next = $tokens->getNextMeaningfulToken($parametersEnd);
$useStart = null;
$useEnd = null;
if ($tokens[$next]->isGivenKind(CT::T_USE_LAMBDA)) {
$useStart = $next;
if ($tokens[$useStart - 1]->isGivenKind(T_WHITESPACE)) {
--$useStart;
}
$next = $tokens->getNextMeaningfulToken($next);
while (!$tokens[$next]->equals(')')) {
if ($tokens[$next]->equals('&')) {
continue 2;
}
$next = $tokens->getNextMeaningfulToken($next);
}
$useEnd = $next;
$next = $tokens->getNextMeaningfulToken($next);
}
$braceOpen = $tokens[$next]->equals('{') ? $next : $tokens->getNextTokenOfKind($next, ['{']);
$return = $braceOpen + 1;
if ($tokens[$return]->isGivenKind(T_WHITESPACE)) {
++$return;
}
if (!$tokens[$return]->isGivenKind(T_RETURN)) {
continue;
}
$semicolon = $tokens->getNextTokenOfKind($return, ['{', ';']);
if (!$tokens[$semicolon]->equals(';')) {
continue;
}
$braceClose = $semicolon + 1;
if ($tokens[$braceClose]->isGivenKind(T_WHITESPACE)) {
++$braceClose;
}
if (!$tokens[$braceClose]->equals('}')) {
continue;
}
if ($this->isMultilined($tokens, $return, $semicolon)) {
continue;
}
$this->transform($tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose);
}
}
private function isMultilined(Tokens $tokens, $start, $end)
{
for ($i = $start; $i < $end; ++$i) {
if (false !== strpos($tokens[$i]->getContent(), "\n")) {
return true;
}
}
return false;
}
private function transform(Tokens $tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose)
{
$tokens->clearRange($semicolon, $braceClose);
$tokens->clearRange($braceOpen + 1, $return);
$tokens[$braceOpen] = new Token([T_DOUBLE_ARROW, '=>']);
if ($useStart) {
$tokens->clearRange($useStart, $useEnd);
}
$tokens[$index] = new Token([T_FN, 'fn']);
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CombineNestedDirnameFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Replace multiple nested calls of `dirname` by only one call with second `$level` parameter. Requires PHP >= 7.0.',
[
new VersionSpecificCodeSample(
"<?php\ndirname(dirname(dirname(\$path)));\n",
new VersionSpecification(70000)
),
],
null,
'Risky when the function `dirname` is overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class VoidReturnFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Add `void` return type to functions with missing or empty return statements, but priority is given to `@return` annotations. Requires PHP >= 7.1.',
[
new VersionSpecificCodeSample(
"<?php\nfunction foo(\$a) {};\n",
new VersionSpecification(70100)
),
],
null,
'Modifies the signature of functions.'
);
}
public function getPriority()
{
return 5;
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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');
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleLineThrowFixer extends AbstractFixer
{
const REMOVE_WHITESPACE_AFTER_TOKENS = ['['];
const REMOVE_WHITESPACE_AROUND_TOKENS = ['(', [T_OBJECT_OPERATOR], [T_DOUBLE_COLON]];
const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';'];
public function getDefinition()
{
return new FixerDefinition(
'Throwing exception must be done in single line.',
[
new CodeSample("<?php\nthrow new Exception(\n 'Error.',\n 500\n);\n"),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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, ' ']);
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ReturnTypeDeclarationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
$versionSpecification = new VersionSpecification(70000);
return new FixerDefinition(
'There should be one or no space before colon, and one space after it in return type declarations, according to configuration.',
[
new VersionSpecificCodeSample(
"<?php\nfunction foo(int \$a):string {};\n",
$versionSpecification
),
new VersionSpecificCodeSample(
"<?php\nfunction foo(int \$a):string {};\n",
$versionSpecification,
['space_before' => 'none']
),
new VersionSpecificCodeSample(
"<?php\nfunction foo(int \$a):string {};\n",
$versionSpecification,
['space_before' => '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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class RegularCallableCallFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Callables must be called without using `call_user_func*` when possible.',
[
new CodeSample(
'<?php
call_user_func("var_dump", 1, 2);
call_user_func("Bar\Baz::d", 1, 2);
call_user_func_array($callback, [1, 2]);
'
),
new VersionSpecificCodeSample(
'<?php
call_user_func(function ($a, $b) { var_dump($a, $b); }, 1, 2);
call_user_func(static function ($a, $b) { var_dump($a, $b); }, 1, 2);
',
new VersionSpecification(70000)
),
],
null,
'Risky when the `call_user_func` or `call_user_func_array` function is overridden or when are used in constructions that should be avoided, like `call_user_func_array(\'foo\', [\'bar\' => \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.'
);
}
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();
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->equalsAny([[T_STRING, 'call_user_func'], [T_STRING, 'call_user_func_array']], false)) {
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$openParenthesis = $tokens->getNextMeaningfulToken($index);
$closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis);
$arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis);
if (1 > \count($arguments)) {
return;
}
$this->processCall($tokens, $index, $arguments);
}
}
private function processCall(Tokens $tokens, $index, array $arguments)
{
$firstArgIndex = $tokens->getNextMeaningfulToken(
$tokens->getNextMeaningfulToken($index)
);
$firstArgToken = $tokens[$firstArgIndex];
if ($firstArgToken->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) {
$afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex);
if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) {
return;
}
$newCallTokens = Tokens::fromCode('<?php '.substr($firstArgToken->getContent(), 1, -1).'();');
$newCallTokensSize = $newCallTokens->count();
$newCallTokens->clearAt(0);
$newCallTokens->clearRange($newCallTokensSize - 3, $newCallTokensSize - 1);
$newCallTokens->clearEmptyTokens();
$this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgIndex);
} elseif ($firstArgToken->isGivenKind([T_FUNCTION, T_STATIC])) {
if (\PHP_VERSION_ID >= 70000) {
$firstArgEndIndex = $tokens->findBlockEnd(
Tokens::BLOCK_TYPE_CURLY_BRACE,
$tokens->getNextTokenOfKind($firstArgIndex, ['{'])
);
$newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex);
$newCallTokens->insertAt($newCallTokens->count(), new Token(')'));
$newCallTokens->insertAt(0, new Token('('));
$this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex);
}
} elseif ($firstArgToken->isGivenKind(T_VARIABLE)) {
$firstArgEndIndex = reset($arguments);
foreach ($arguments as $argumentStart => $argumentEnd) {
if ($firstArgEndIndex === $argumentEnd) {
continue;
}
for ($i = $argumentStart; $i <= $argumentEnd; ++$i) {
if ($tokens[$i]->equals($firstArgToken)) {
return;
}
}
}
$newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex);
$complex = false;
for ($newCallIndex = \count($newCallTokens) - 1; $newCallIndex >= 0; --$newCallIndex) {
if ($newCallTokens[$newCallIndex]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_VARIABLE])) {
continue;
}
$blockType = Tokens::detectBlockType($newCallTokens[$newCallIndex]);
if (null !== $blockType && (Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $blockType['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $blockType['type'])) {
$newCallIndex = $newCallTokens->findBlockStart($blockType['type'], $newCallIndex);
continue;
}
$complex = true;
break;
}
if ($complex) {
if (\PHP_VERSION_ID < 70000) {
return;
}
$newCallTokens->insertAt($newCallTokens->count(), new Token(')'));
$newCallTokens->insertAt(0, new Token('('));
}
$this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex);
}
}
private function replaceCallUserFuncWithCallback(Tokens $tokens, $callIndex, Tokens $newCallTokens, $firstArgStartIndex, $firstArgEndIndex)
{
$tokens->clearRange($firstArgStartIndex, $firstArgEndIndex);
$afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex);
$afterFirstArgToken = $tokens[$afterFirstArgIndex];
if ($afterFirstArgToken->equals(',')) {
$useEllipsis = $tokens[$callIndex]->equals([T_STRING, 'call_user_func_array']);
if ($useEllipsis) {
$secondArgIndex = $tokens->getNextMeaningfulToken($afterFirstArgIndex);
$tokens->insertAt($secondArgIndex, new Token([T_ELLIPSIS, '...']));
}
$tokens->clearAt($afterFirstArgIndex);
$tokens->removeTrailingWhitespace($afterFirstArgIndex);
}
$tokens->overrideRange($callIndex, $callIndex, $newCallTokens);
$prevIndex = $tokens->getPrevMeaningfulToken($callIndex);
if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
}
}
private function getTokensSubcollection(Tokens $tokens, $indexStart, $indexEnd)
{
$size = $indexEnd - $indexStart + 1;
$subcollection = new Tokens($size);
for ($i = 0; $i < $size; ++$i) {
$toClone = $tokens[$i + $indexStart];
$subcollection[$i] = clone $toClone;
}
return $subcollection;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocToParamTypeFixer extends AbstractPhpdocToTypeDeclarationFixer
{
const CLASS_REGEX = '/^\\\\?[a-zA-Z_\\x7f-\\xff](?:\\\\?[a-zA-Z0-9_\\x7f-\\xff]+)*(?<array>\[\])*$/';
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(
'<?php
/** @param string $bar */
function my_foo($bar)
{}
',
new VersionSpecification(70000)
),
new VersionSpecificCodeSample(
'<?php
/** @param string|null $bar */
function my_foo($bar)
{}
',
new VersionSpecification(70100)
),
],
null,
'This rule is EXPERIMENTAL and [1] is not covered with backward compatibility promise. [2] `@param` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. [3] Manual actions are required if inherited signatures are not properly documented.'
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID >= 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('<?php function f(%s $x) {}', $paramType))) {
continue;
}
$this->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);
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUselessSprintfFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There must be no `sprintf` calls with only the first argument.',
[
new CodeSample(
"<?php\n\$foo = sprintf('bar');\n"
),
],
null,
'Risky when if the `sprintf` function is overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_STRING);
}
public function isRisky()
{
return true;
}
public function getPriority()
{
return 27;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$functionAnalyzer = new FunctionsAnalyzer();
$argumentsAnalyzer = new ArgumentsAnalyzer();
for ($index = \count($tokens) - 1; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(T_STRING)) {
continue;
}
if ('sprintf' !== strtolower($tokens[$index]->getContent())) {
continue;
}
if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']);
if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(T_ELLIPSIS)) {
continue;
}
$closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex);
if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex);
$prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex);
if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_NS_SEPARATOR)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class LambdaNotUsedImportFixer extends AbstractFixer
{
private $argumentsAnalyzer;
private $functionAnalyzer;
private $tokensAnalyzer;
public function getDefinition()
{
return new FixerDefinition(
'Lambda must not import variables it doesn\'t use.',
[new CodeSample("<?php\n\$foo = function() use (\$bar) {};\n")]
);
}
public function getPriority()
{
return 3;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound([T_FUNCTION, CT::T_USE_LAMBDA]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$this->argumentsAnalyzer = new ArgumentsAnalyzer();
$this->functionAnalyzer = new FunctionsAnalyzer();
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 4; $index > 0; --$index) {
$lambdaUseIndex = $this->getLambdaUseIndex($tokens, $index);
if (false !== $lambdaUseIndex) {
$this->fixLambda($tokens, $lambdaUseIndex);
}
}
}
private function fixLambda(Tokens $tokens, $lambdaUseIndex)
{
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($lambdaUseIndex, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->filterArguments($tokens, $arguments);
if (0 === \count($imports)) {
return;
}
$notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex);
$notUsedImportsCount = \count($notUsedImports);
if (0 === $notUsedImportsCount) {
return;
}
if ($notUsedImportsCount === \count($arguments)) {
$this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex);
return;
}
$this->clearImports($tokens, array_reverse($notUsedImports));
}
private function findNotUsedLambdaImports(Tokens $tokens, array $imports, $lambdaUseCloseBraceIndex)
{
static $riskyKinds = [
CT::T_DYNAMIC_VAR_BRACE_OPEN,
T_EVAL,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
];
$lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']);
$curlyBracesLevel = 0;
for ($index = $lambdaOpenIndex;; ++$index) {
$token = $tokens[$index];
if ($token->equals('{')) {
++$curlyBracesLevel;
continue;
}
if ($token->equals('}')) {
--$curlyBracesLevel;
if (0 === $curlyBracesLevel) {
break;
}
continue;
}
if ($token->isGivenKind(T_STRING) && 'compact' === strtolower($token->getContent()) && $this->functionAnalyzer->isGlobalFunctionCall($tokens, $index)) {
return [];
}
if ($token->isGivenKind($riskyKinds)) {
return [];
}
if ($token->equals('$')) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) {
return [];
}
}
if ($token->isGivenKind(T_VARIABLE)) {
$content = $token->getContent();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
if ($token->isGivenKind(T_STRING_VARNAME)) {
$content = '$'.$token->getContent();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
if ($token->isClassy()) {
$index = $tokens->getNextTokenOfKind($index, ['(', '{']);
if ($tokens[$index]->equals('(')) {
$closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $index, $closeBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
$index = $tokens->getNextTokenOfKind($closeBraceIndex, ['{']);
}
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
$index = $tokens->getNextTokenOfKind($index, [[CT::T_USE_LAMBDA], '{']);
if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) {
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
$index = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']);
}
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
}
return $imports;
}
private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments)
{
foreach ($arguments as $start => $end) {
$info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end);
$content = $info->getName();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
return $imports;
}
private function getLambdaUseIndex(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) {
return false;
}
$lambdaUseIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) {
$lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex);
}
$lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex);
$lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex);
if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) {
return false;
}
return $lambdaUseIndex;
}
private function filterArguments(Tokens $tokens, array $arguments)
{
$imports = [];
foreach ($arguments as $start => $end) {
$info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end);
$argument = $info->getNameIndex();
if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) {
continue;
}
$argumentCandidate = $tokens[$argument];
if ('$this' === $argumentCandidate->getContent()) {
continue;
}
if ($this->tokensAnalyzer->isSuperGlobal($argument)) {
continue;
}
$imports[$argumentCandidate->getContent()] = $argument;
}
return $imports;
}
private function clearImports(Tokens $tokens, array $imports)
{
foreach ($imports as $content => $removeIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex);
$previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex);
if ($tokens[$previousRemoveIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex);
} elseif ($tokens[$previousRemoveIndex]->equals('(')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex));
}
}
}
private function clearImportsAndUse(Tokens $tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex)
{
for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) {
if ($tokens[$i]->isComment()) {
continue;
}
if ($tokens[$i]->isWhitespace()) {
$previousIndex = $tokens->getPrevNonWhitespace($i);
if ($tokens[$previousIndex]->isComment()) {
continue;
}
}
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const SET_ALL = '@all';
const SET_COMPILER_OPTIMIZED = '@compiler_optimized';
const SET_INTERNAL = '@internal';
private $functionFilter;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->functionFilter = $this->getFunctionFilter();
}
public function getDefinition()
{
return new FixerDefinition(
'Add leading `\` before function invocation to speed up resolving.',
[
new CodeSample(
'<?php
function baz($options)
{
if (!array_key_exists("foo", $options)) {
throw new \InvalidArgumentException();
}
return json_encode($options);
}
'
),
new CodeSample(
'<?php
function baz($options)
{
if (!array_key_exists("foo", $options)) {
throw new \InvalidArgumentException();
}
return json_encode($options);
}
',
[
'exclude' => [
'json_encode',
],
]
),
new CodeSample(
'<?php
namespace space1 {
echo count([1]);
}
namespace {
echo count([1]);
}
',
['scope' => 'all']
),
new CodeSample(
'<?php
namespace space1 {
echo count([1]);
}
namespace {
echo count([1]);
}
',
['scope' => 'namespaced']
),
new CodeSample(
'<?php
myGlobalFunction();
count();
',
['include' => ['myGlobalFunction']]
),
new CodeSample(
'<?php
myGlobalFunction();
count();
',
['include' => ['@all']]
),
new CodeSample(
'<?php
myGlobalFunction();
count();
',
['include' => ['@internal']]
),
new CodeSample(
'<?php
$a .= str_repeat($a, 4);
$c = get_class($d);
',
['include' => ['@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();
$tokensToInsert = [];
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;
}
$tokensToInsert[$index] = new Token([T_NS_SEPARATOR, '\\']);
}
$tokens->insertSlices($tokensToInsert);
}
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;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
final class MethodArgumentSpaceFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function fixSpace(Tokens $tokens, $index)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
$this->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(
"<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n",
null
),
new CodeSample(
"<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n",
['keep_multiple_spaces_after_comma' => false]
),
new CodeSample(
"<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n",
['keep_multiple_spaces_after_comma' => true]
),
new CodeSample(
"<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1,\n 2);\n",
['on_multiline' => 'ensure_fully_multiline']
),
new CodeSample(
"<?php\nfunction sample(\n \$a=10,\n \$b=20,\n \$c=30\n) {}\nsample(\n 1,\n 2\n);\n",
['on_multiline' => 'ensure_single_line']
),
new CodeSample(
"<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1, \n 2);\nsample('foo', 'foobarbaz', 'baz');\nsample('foobar', 'bar', 'baz');\n",
[
'on_multiline' => 'ensure_fully_multiline',
'keep_multiple_spaces_after_comma' => true,
]
),
new CodeSample(
"<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1, \n 2);\nsample('foo', 'foobarbaz', 'baz');\nsample('foobar', 'bar', 'baz');\n",
[
'on_multiline' => 'ensure_fully_multiline',
'keep_multiple_spaces_after_comma' => false,
]
),
new VersionSpecificCodeSample(
<<<'SAMPLE'
<?php
sample(
<<<EOD
foo
EOD
,
'bar'
);
SAMPLE
,
new VersionSpecification(70300),
['after_heredoc' => 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");
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpdocToReturnTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurationDefinitionFixerInterface
{
private $excludeFuncNames = [
[T_STRING, '__construct'],
[T_STRING, '__destruct'],
[T_STRING, '__clone'],
];
private $versionSpecificTypes = [
'void' => 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]+)*(?<array>\[\])*$/';
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(
'<?php
/** @return \My\Bar */
function my_foo()
{}
',
new VersionSpecification(70000)
),
new VersionSpecificCodeSample(
'<?php
/** @return void */
function my_foo()
{}
',
new VersionSpecification(70100)
),
new VersionSpecificCodeSample(
'<?php
/** @return object */
function my_foo()
{}
',
new VersionSpecification(70200)
),
new VersionSpecificCodeSample(
'<?php
/** @return Foo */
function foo() {}
/** @return string */
function bar() {}
',
new VersionSpecification(70100),
['scalar_types' => false]
),
new VersionSpecificCodeSample(
'<?php
final class Foo {
/**
* @return static
*/
public function create($prototype) {
return new static($prototype);
}
}
',
new VersionSpecification(80000)
),
],
null,
'This rule is EXPERIMENTAL and [1] is not covered with backward compatibility promise. [2] `@return` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. [3] Manual actions are required if inherited signatures are not properly documented. [4] `@inheritdocs` support is under construction.'
);
}
public function isCandidate(Tokens $tokens)
{
if (\PHP_VERSION_ID >= 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('<?php function f():%s {}', $returnType))) {
continue;
}
$this->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');
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFopenFlagFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FopenFlagsFixer extends AbstractFopenFlagFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'The flags in `fopen` calls must omit `t`, and `b` must be omitted or included consistently.',
[
new CodeSample("<?php\n\$a = fopen(\$foo, 'rwt');\n"),
new CodeSample("<?php\n\$a = fopen(\$foo, 'rwt');\n", ['b_mode' => 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]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
final class FunctionTypehintSpaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Ensure single space between function\'s argument and its typehint.',
[
new CodeSample("<?php\nfunction sample(array\$a)\n{}\n"),
new CodeSample("<?php\nfunction sample(array \$a)\n{}\n"),
]
);
}
public function isCandidate(Tokens $tokens)
{
if (\PHP_VERSION_ID >= 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, ' ');
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class FunctionDeclarationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const SPACING_NONE = 'none';
const SPACING_ONE = 'one';
private $supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE];
private $singleLineWhitespaceOptions = " \t";
public function isCandidate(Tokens $tokens)
{
if (\PHP_VERSION_ID >= 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(
'<?php
class Foo
{
public static function bar ( $baz , $foo )
{
return false;
}
}
function foo ($bar, $baz)
{
return false;
}
'
),
new CodeSample(
'<?php
$f = function () {};
',
['closure_function_spacing' => self::SPACING_NONE]
),
new VersionSpecificCodeSample(
'<?php
$f = fn () => 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFopenFlagFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FopenFlagOrderFixer extends AbstractFopenFlagFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Order the flags in `fopen` calls, `b` and `t` must be last.',
[new CodeSample("<?php\n\$a = fopen(\$foo, 'br+');\n")],
null,
'Risky when the function `fopen` is overridden.'
);
}
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);
}
$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;
}
}
<?php
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
@web
*/
final class NoUnreachableDefaultArgumentValueFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'In function arguments there must not be arguments with default values before non-default ones.',
[
new CodeSample(
'<?php
function example($foo = "two words", $bar) {}
'
),
],
null,
'Modifies the signature of functions; therefore risky when using systems (such as some Symfony components) that rely on those (for example through reflection).'
);
}
public function getPriority()
{
return 0;
}
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)
{
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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Naming;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class NoHomoglyphNamesFixer extends AbstractFixer
{
private static $replacements = [
'O' => '0',
'' => '0',
'I' => '1',
'' => '1',
'' => '2',
'' => '3',
'' => '4',
'' => '5',
'' => '6',
'' => '7',
'' => '8',
'' => '9',
'Α' => 'A',
'А' => 'A',
'' => 'A',
'ʙ' => 'B',
'Β' => 'B',
'В' => 'B',
'' => 'B',
'Ϲ' => 'C',
'С' => 'C',
'' => 'C',
'' => 'C',
'' => 'D',
'' => 'D',
'Ε' => 'E',
'Е' => 'E',
'' => 'E',
'Ϝ' => 'F',
'' => 'F',
'ɢ' => 'G',
'Ԍ' => 'G',
'' => 'G',
'ʜ' => 'H',
'Η' => 'H',
'Н' => 'H',
'' => 'H',
'l' => 'I',
'Ι' => 'I',
'І' => 'I',
'' => 'I',
'' => 'I',
'Ј' => 'J',
'' => 'J',
'Κ' => 'K',
'К' => 'K',
'K' => 'K',
'' => 'K',
'ʟ' => 'L',
'' => 'L',
'' => 'L',
'Μ' => 'M',
'М' => 'M',
'' => 'M',
'' => 'M',
'ɴ' => 'N',
'Ν' => 'N',
'' => 'N',
'Ο' => 'O',
'О' => 'O',
'' => 'O',
'Ρ' => 'P',
'Р' => 'P',
'' => 'P',
'' => 'Q',
'ʀ' => 'R',
'' => 'R',
'Ѕ' => 'S',
'' => 'S',
'Τ' => 'T',
'Т' => 'T',
'' => 'T',
'' => 'U',
'Ѵ' => 'V',
'' => 'V',
'' => 'V',
'' => 'W',
'Χ' => 'X',
'Х' => 'X',
'' => 'X',
'' => 'X',
'ʏ' => 'Y',
'Υ' => 'Y',
'Ү' => 'Y',
'' => 'Y',
'Ζ' => 'Z',
'' => 'Z',
'_' => '_',
'ɑ' => 'a',
'а' => 'a',
'' => 'a',
'Ь' => 'b',
'' => 'b',
'ϲ' => 'c',
'с' => 'c',
'' => 'c',
'' => 'c',
'ԁ' => 'd',
'' => 'd',
'' => 'd',
'е' => 'e',
'' => 'e',
'' => 'f',
'ɡ' => 'g',
'' => 'g',
'һ' => 'h',
'' => 'h',
'ɩ' => 'i',
'і' => 'i',
'' => 'i',
'' => 'i',
'ј' => 'j',
'' => 'j',
'' => 'k',
'' => 'l',
'' => 'l',
'ⅿ' => 'm',
'' => 'm',
'' => 'n',
'ο' => 'o',
'о' => 'o',
'' => 'o',
'р' => 'p',
'' => 'p',
'' => 'q',
'' => 'r',
'ѕ' => 's',
'' => 's',
'' => 't',
'' => 'u',
'ν' => 'v',
'ѵ' => 'v',
'' => 'v',
'' => 'v',
'ѡ' => 'w',
'' => 'w',
'х' => 'x',
'' => 'x',
'' => 'x',
'у' => 'y',
'' => 'y',
'' => 'z',
];
public function getDefinition()
{
return new FixerDefinition(
'Replace accidental usage of homoglyphs (non ascii characters) in names.',
[new CodeSample("<?php \$nаmе = 'wrong \"a\" character';\n")],
null,
'Renames classes and cannot rename the files. You might have string references to renamed code (`$$name`).'
);
}
public function isRisky()
{
return true;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]));
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class MagicConstantCasingFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Magic constants should be referred to using the correct casing.',
[new CodeSample("<?php\necho __dir__;\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NativeFunctionCasingFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Function defined by PHP should be called using the correct casing.',
[new CodeSample("<?php\nSTRLEN(\$str);\n")]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ConstantCaseFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $fixFunction;
public function configure(array $configuration = null)
{
parent::configure($configuration);
if ('lower' === $this->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("<?php\n\$a = FALSE;\n\$b = True;\n\$c = nuLL;\n"),
new CodeSample("<?php\n\$a = FALSE;\n\$b = True;\n\$c = nuLL;\n", ['case' => '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);
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
final class LowercaseConstantsFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'The PHP constants `true`, `false`, and `null` MUST be in lower case.',
[new CodeSample("<?php\n\$a = FALSE;\n\$b = True;\n\$c = nuLL;\n")]
);
}
public function getSuccessorsNames()
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers()
{
$fixer = new ConstantCaseFixer();
$fixer->configure(['case' => 'lower']);
return [$fixer];
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class LowercaseKeywordsFixer extends AbstractFixer
{
private static $excludedTokens = [T_HALT_COMPILER];
public function getDefinition()
{
return new FixerDefinition(
'PHP keywords MUST be in lower case.',
[
new CodeSample(
'<?php
FOREACH($a AS $B) {
TRY {
NEW $C($a, ISSET($B));
WHILE($B) {
INCLUDE "test.php";
}
} CATCH(\Exception $e) {
EXIT(1);
}
}
'
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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())]);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class MagicMethodCasingFixer extends AbstractFixer
{
private static $magicNames = [
'__call' => '__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(
'<?php
class Foo
{
public function __Sleep()
{
}
}
'
),
new CodeSample(
'<?php
$foo->__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]);
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class LowercaseStaticReferenceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Class static references `self`, `static` and `parent` MUST be in lower case.',
[
new CodeSample('<?php
class Foo extends Bar
{
public function baz1()
{
return STATIC::baz2();
}
public function baz2($x)
{
return $x instanceof Self;
}
public function baz3(PaRent $x)
{
return true;
}
}
'),
new VersionSpecificCodeSample(
'<?php
class Foo extends Bar
{
public function baz(?self $x) : SELF
{
return false;
}
}
',
new VersionSpecification(70100)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NativeFunctionTypeDeclarationCasingFixer extends AbstractFixer
{
private $hints;
private $functionsAnalyzer;
public function __construct()
{
parent::__construct();
$this->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("<?php\nclass Bar {\n public function Foo(CALLABLE \$bar)\n {\n return 1;\n }\n}\n"),
new VersionSpecificCodeSample(
"<?php\nfunction Foo(INT \$a): Bool\n{\n return true;\n}\n",
new VersionSpecification(70000)
),
new VersionSpecificCodeSample(
"<?php\nfunction Foo(Iterable \$a): VOID\n{\n echo 'Hello world';\n}\n",
new VersionSpecification(70100)
),
new VersionSpecificCodeSample(
"<?php\nfunction Foo(Object \$a)\n{\n return 'hi!';\n}\n",
new VersionSpecification(70200)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]);
}
}
<?php
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class BlankLineAfterNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'There MUST be one blank line after the namespace declaration.',
[
new CodeSample("<?php\nnamespace Sample\\Sample;\n\n\n\$a;\n"),
new CodeSample("<?php\nnamespace Sample\\Sample;\nClass Test{}\n"),
]
);
}
public function getPriority()
{
return -20;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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]);
}
}
<?php
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractLinesBeforeNamespaceFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Tokens;
final class CleanNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
public function getDefinition()
{
$samples = [];
foreach (['namespace Foo \\ Bar;', 'echo foo /* comment */ \\ bar();'] as $sample) {
$samples[] = new VersionSpecificCodeSample(
"<?php\n".$sample."\n",
new VersionSpecification(null, 80000 - 1)
);
}
return new FixerDefinition(
'Namespace must not contain spacing, comments or PHPDoc.',
$samples
);
}
public function isCandidate(Tokens $tokens)
{
return \PHP_VERSION_ID < 80000 && $tokens->isTokenKindFound(T_NS_SEPARATOR);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$count = $tokens->count();
for ($index = 0; $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) {
$previousIndex = $tokens->getPrevMeaningfulToken($index);
$index = $this->fixNamespace(
$tokens,
$tokens[$previousIndex]->isGivenKind(T_STRING) ? $previousIndex : $index
);
}
}
}
private function fixNamespace(Tokens $tokens, $index)
{
$tillIndex = $index;
while ($tokens[$tillIndex]->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
$tillIndex = $tokens->getNextMeaningfulToken($tillIndex);
}
$tillIndex = $tokens->getPrevMeaningfulToken($tillIndex);
$spaceIndexes = [];
for (; $index <= $tillIndex; ++$index) {
if ($tokens[$index]->isGivenKind(T_WHITESPACE)) {
$spaceIndexes[] = $index;
} elseif ($tokens[$index]->isComment()) {
$tokens->clearAt($index);
}
}
if ($tokens[$index - 1]->isWhiteSpace()) {
array_pop($spaceIndexes);
}
foreach ($spaceIndexes as $i) {
$tokens->clearAt($i);
}
return $index;
}
}
<?php
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class NoLeadingNamespaceWhitespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_NAMESPACE);
}
public function getDefinition()
{
return new FixerDefinition(
'The namespace declaration line shouldn\'t contain leading whitespace.',
[
new CodeSample(
'<?php
namespace Test8a;
namespace Test8b;
'
),
]
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->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));
}
}
<?php
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractLinesBeforeNamespaceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class SingleBlankLineBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
public function getDefinition()
{
return new FixerDefinition(
'There should be exactly one blank line before a namespace declaration.',
[
new CodeSample("<?php namespace A {}\n"),
new CodeSample("<?php\n\n\nnamespace A{}\n"),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractLinesBeforeNamespaceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoBlankLinesBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_NAMESPACE);
}
public function getDefinition()
{
return new FixerDefinition(
'There should be no blank lines before a namespace declaration.',
[
new CodeSample(
"<?php\n\n\n\nnamespace Example;\n"
),
]
);
}
public function getPriority()
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_NAMESPACE)) {
continue;
}
$this->fixLinesBeforeNamespace($tokens, $index, 0, 1);
}
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class LowercaseCastFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Cast should be written in lower case.',
[
new VersionSpecificCodeSample(
'<?php
$a = (BOOLEAN) $b;
$a = (BOOL) $b;
$a = (INTEGER) $b;
$a = (INT) $b;
$a = (DOUBLE) $b;
$a = (FLoaT) $b;
$a = (reaL) $b;
$a = (flOAT) $b;
$a = (sTRING) $b;
$a = (ARRAy) $b;
$a = (OBJect) $b;
$a = (UNset) $b;
$a = (Binary) $b;
',
new VersionSpecification(null, 70399)
),
new VersionSpecificCodeSample(
'<?php
$a = (BOOLEAN) $b;
$a = (BOOL) $b;
$a = (INTEGER) $b;
$a = (INT) $b;
$a = (DOUBLE) $b;
$a = (FLoaT) $b;
$a = (flOAT) $b;
$a = (sTRING) $b;
$a = (ARRAy) $b;
$a = (OBJect) $b;
$a = (UNset) $b;
$a = (Binary) $b;
',
new VersionSpecification(70400)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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())]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CastSpacesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
const INSIDE_CAST_SPACE_REPLACE_MAP = [
' ' => '',
"\t" => '',
"\n" => '',
"\r" => '',
"\0" => '',
"\x0B" => '',
];
public function getDefinition()
{
return new FixerDefinition(
'A single space or none should be between cast and variable.',
[
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int)\$b;\n"
),
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int)\$b;\n",
['space' => 'single']
),
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int) \$b;\n",
['space' => '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(),
]);
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUnsetCastFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Variables must be set `null` instead of using `(unset)` casting.',
[new CodeSample("<?php\n\$a = (unset) \$b;\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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']));
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoShortBoolCastFixer extends AbstractFixer
{
public function getPriority()
{
return -9;
}
public function getDefinition()
{
return new FixerDefinition(
'Short cast `bool` using double exclamation mark should not be used.',
[new CodeSample("<?php\n\$a = !!\$b;\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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)']));
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ShortScalarCastFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`.',
[
new VersionSpecificCodeSample(
"<?php\n\$a = (boolean) \$b;\n\$a = (integer) \$b;\n\$a = (double) \$b;\n\$a = (real) \$b;\n\n\$a = (binary) \$b;\n",
new VersionSpecification(null, 70399)
),
new VersionSpecificCodeSample(
"<?php\n\$a = (boolean) \$b;\n\$a = (integer) \$b;\n\$a = (double) \$b;\n\n\$a = (binary) \$b;\n",
new VersionSpecification(70400)
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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()),
]);
}
}
}
<?php
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ModernizeTypesCastingFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Replaces `intval`, `floatval`, `doubleval`, `strval` and `boolval` function calls with according type casting operator.',
[
new CodeSample(
'<?php
$a = intval($b);
$a = floatval($b);
$a = doubleval($b);
$a = strval ($b);
$a = boolval($b);
'
),
],
null,
'Risky if any of the functions `intval`, `floatval`, `doubleval`, `strval` or `boolval` are overridden.'
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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;
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SwitchContinueToBreakFixer extends AbstractFixer
{
private $switchLevels = [];
public function getDefinition()
{
return new FixerDefinition(
'Switch case must not be ended with `continue` but with `break`.',
[
new CodeSample(
'<?php
switch ($foo) {
case 1:
continue;
}
'
),
new CodeSample(
'<?php
switch ($foo) {
case 1:
while($bar) {
do {
continue 3;
} while(false);
if ($foo + 1 > 3) {
continue;
}
continue 2;
}
}
'
),
]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound([T_SWITCH, T_CONTINUE, T_LNUMBER]) && !$tokens->hasAlternativeSyntax();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$count = \count($tokens);
for ($index = 1; $index < $count - 1; ++$index) {
$index = $this->doFix($tokens, $index, 0, false);
}
}
private function doFix(Tokens $tokens, $index, $depth, $isInSwitch)
{
$token = $tokens[$index];
if ($token->isGivenKind([T_FOREACH, T_FOR, T_WHILE])) {
$index = $tokens->getNextTokenOfKind($index, ['(']);
$index = $tokens->getNextTokenOfKind($index, [')']);
$index = $tokens->getNextTokenOfKind($index, ['{', ';', [T_CLOSE_TAG]]);
if (!$tokens[$index]->equals('{')) {
return $index;
}
return $this->fixInLoop($tokens, $index, $depth + 1);
}
if ($token->isGivenKind(T_DO)) {
return $this->fixInLoop($tokens, $tokens->getNextTokenOfKind($index, ['{']), $depth + 1);
}
if ($token->isGivenKind(T_SWITCH)) {
return $this->fixInSwitch($tokens, $index, $depth + 1);
}
if ($token->isGivenKind(T_CONTINUE)) {
return $this->fixContinueWhenActsAsBreak($tokens, $index, $isInSwitch, $depth);
}
return $index;
}
private function fixInSwitch(Tokens $tokens, $switchIndex, $depth)
{
$this->switchLevels[] = $depth;
$openIndex = $tokens->getNextTokenOfKind($switchIndex, ['{']);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
for ($index = $openIndex + 1; $index < $closeIndex; ++$index) {
$index = $this->doFix($tokens, $index, $depth, true);
}
array_pop($this->switchLevels);
return $closeIndex;
}
private function fixInLoop(Tokens $tokens, $openIndex, $depth)
{
$openCount = 1;
do {
++$openIndex;
$token = $tokens[$openIndex];
if ($token->equals('{')) {
++$openCount;
continue;
}
if ($token->equals('}')) {
--$openCount;
if (0 === $openCount) {
break;
}
continue;
}
$openIndex = $this->doFix($tokens, $openIndex, $depth, false);
} while (true);
return $openIndex;
}
private function fixContinueWhenActsAsBreak(Tokens $tokens, $continueIndex, $isInSwitch, $depth)
{
$followingContinueIndex = $tokens->getNextMeaningfulToken($continueIndex);
$followingContinueToken = $tokens[$followingContinueIndex];
if ($isInSwitch && $followingContinueToken->equals(';')) {
$this->replaceContinueWithBreakToken($tokens, $continueIndex);
return $followingContinueIndex;
}
if (!$followingContinueToken->isGivenKind(T_LNUMBER)) {
return $followingContinueIndex;
}
$afterFollowingContinueIndex = $tokens->getNextMeaningfulToken($followingContinueIndex);
if (!$tokens[$afterFollowingContinueIndex]->equals(';')) {
return $afterFollowingContinueIndex;
}
$jump = $followingContinueToken->getContent();
$jump = str_replace('_', '', $jump);
if (\strlen($jump) > 2 && 'x' === $jump[1]) {
$jump = hexdec($jump);
} elseif (\strlen($jump) > 2 && 'b' === $jump[1]) {
$jump = bindec($jump);
} elseif (\strlen($jump) > 1 && '0' === $jump[0]) {
$jump = octdec($jump);
} elseif (1 === Preg::match('#^\d+$#', $jump)) {
$jump = (float) $jump;
} else {
return $afterFollowingContinueIndex;
}
if ($jump > PHP_INT_MAX) {
return $afterFollowingContinueIndex;
}
$jump = (int) $jump;
if ($isInSwitch && (1 === $jump || 0 === $jump)) {
$this->replaceContinueWithBreakToken($tokens, $continueIndex);
return $afterFollowingContinueIndex;
}
$jumpDestination = $depth - $jump + 1;
if (\in_array($jumpDestination, $this->switchLevels, true)) {
$this->replaceContinueWithBreakToken($tokens, $continueIndex);
return $afterFollowingContinueIndex;
}
return $afterFollowingContinueIndex;
}
private function replaceContinueWithBreakToken(Tokens $tokens, $index)
{
$tokens[$index] = new Token([T_BREAK, 'break']);
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
@gmail
*/
final class IncludeFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Include/Require and file path should be divided with a single space. File path should not be placed under brackets.',
[
new CodeSample(
'<?php
require ("sample1.php");
require_once "sample2.php";
include "sample3.php";
include_once("sample4.php");
'
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUnneededCurlyBracesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'Removes unneeded curly braces that are superfluous and aren\'t part of a control structure\'s body.',
[
new CodeSample(
'<?php {
echo 1;
}
switch ($b) {
case 1: {
break;
}
}
'
),
new CodeSample(
'<?php
namespace Foo {
function Bar(){}
}
',
['namespaces' => 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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractNoUselessElseFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUselessElseFixer extends AbstractNoUselessElseFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_ELSE);
}
public function getDefinition()
{
return new FixerDefinition(
'There should not be useless `else` cases.',
[
new CodeSample("<?php\nif (\$a) {\n return 1;\n} else {\n return 2;\n}\n"),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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);
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoAlternativeSyntaxFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Replace control structure alternative syntax to use braces.',
[
new CodeSample(
"<?php\nif(true):echo 't';else:echo 'f';endif;\n"
),
new CodeSample(
"<?php\nwhile(true):echo 'red';endwhile;\n"
),
new CodeSample(
"<?php\nfor(;;):echo 'xc';endfor;\n"
),
new CodeSample(
"<?php\nforeach(array('a') as \$item):echo 'xc';endforeach;\n"
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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
);
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class SwitchCaseSpaceFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Removes extra spaces between colon and case value.',
[
new CodeSample(
'<?php
switch($a) {
case 1 :
break;
default :
return 2;
}
'
),
]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
@web
*/
final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private static $loops = [
'break' => ['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, '??'];
}
if (\defined('T_YIELD_FROM')) {
self::$loops['yield_from'] = ['lookupTokens' => T_YIELD_FROM, 'neededSuccessors' => [';', ')']];
}
}
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(
'<?php
while ($x) { while ($y) { break (2); } }
clone($a);
while ($y) { continue (2); }
echo("foo");
print("foo");
return (1 + 2);
switch ($a) { case($x); }
yield(2);
'
),
new CodeSample(
'<?php
while ($x) { while ($y) { break (2); } }
clone($a);
while ($y) { continue (2); }
echo("foo");
print("foo");
return (1 + 2);
switch ($a) { case($x); }
yield(2);
',
['statements' => ['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());
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
final class NoBreakCommentFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
public function getDefinition()
{
return new FixerDefinition(
'There must be a comment when fall-through is intentional in a non-empty case body.',
[
new CodeSample(
'<?php
switch ($foo) {
case 1:
foo();
case 2:
bar();
// no break
break;
case 3:
baz();
}
'
),
new CodeSample(
'<?php
switch ($foo) {
case 1:
foo();
case 2:
foo();
}
',
['comment_text' => '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 = WhitespacesAnalyzer::detectIndent($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.WhitespacesAnalyzer::detectIndent($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 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;
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SwitchCaseSemicolonToColonFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'A case should be followed by a colon and not a semicolon.',
[
new CodeSample(
'<?php
switch ($a) {
case 1;
break;
default;
break;
}
'
),
]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound([T_CASE, T_DEFAULT]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_CASE)) {
$this->fixSwitchCase($tokens, $index);
}
if ($token->isGivenKind(T_DEFAULT)) {
$this->fixSwitchDefault($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(':');
}
}
protected function fixSwitchDefault(Tokens $tokens, $index)
{
do {
if ($tokens[$index]->equalsAny([':', ';', [T_DOUBLE_ARROW]])) {
break;
}
} while (++$index);
if ($tokens[$index]->equals(';')) {
$tokens[$index] = new Token(':');
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ElseifFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words.',
[new CodeSample("<?php\nif (\$a) {\n} else if (\$b) {\n}\n")]
);
}
public function getPriority()
{
return 0;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
final class NoTrailingCommaInListCallFixer extends AbstractFixer
{
public function getDefinition()
{
return new FixerDefinition(
'Remove trailing commas in list function calls.',
[new CodeSample("<?php\nlist(\$a, \$b,) = foo();\n")]
);
}
public function isCandidate(Tokens $tokens)
{
return $tokens->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
);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
@gmail
*/
final class YodaStyleFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
private $candidatesMap;
private $candidateTypesConfiguration;
private $candidateTypes;
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->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(
'<?php
if ($a === null) {
echo "null";
}
'
),
new CodeSample(
'<?php
$b = $c != 1; // equal
$a = 1 === $b; // identical
$c = $c > 3; // less than
',
[
'equal' => true,
'identical' => false,
'less_and_greater' => null,
]
),
new CodeSample(
'<?php
return $foo === count($bar);
',
[
'always_move_variable' => true,
]
),
new CodeSample(
'<?php
// Enforce non-Yoda style.
if (null === $a) {
echo "null";
}
',
[
'equal' => 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('<?php %s;', $newTokens)));
$newTokens->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);
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SimplifiedIfReturnFixer extends AbstractFixer
{
private $sequences = [
[
'isNegative' => false,
'sequence' => [
'{', [T_RETURN], [T_STRING, 'true'], ';', '}',
[T_RETURN], [T_STRING, 'false'], ';',
],
],
[
'isNegative' => true,
'sequence' => [
'{', [T_RETURN], [T_STRING, 'false'], ';', '}',
[T_RETURN], [T_STRING, 'true'], ';',
],
],
[
'isNegative' => false,
'sequence' => [
[T_RETURN], [T_STRING, 'true'], ';',
[T_RETURN], [T_STRING, 'false'], ';',
],
],
[
'isNegative' => true,
'sequence' => [
[T_RETURN], [T_STRING, 'false'], ';',
[T_RETURN], [T_STRING, 'true'], ';',
],
],
];
public function getDefinition()
{
return new FixerDefinition(
'Simplify `if` control structures that return the boolean result of their condition.',
[new CodeSample("<?php\nif (\$foo) { return true; } return false;\n")]
);
}
public function getPriority()
{
return 1;
}
public function isCandidate(Tokens $tokens)
{
return $tokens->isAllTokenKindsFound([T_IF, T_RETURN, T_STRING]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($ifIndex = $tokens->count() - 1; 0 <= $ifIndex; --$ifIndex) {
$ifToken = $tokens[$ifIndex];
if (!$ifToken->isGivenKind([T_IF, T_ELSEIF])) {
continue;
}
$startParenthesisIndex = $tokens->getNextTokenOfKind($ifIndex, ['(']);
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$firstCandidateIndex = $tokens->getNextMeaningfulToken($endParenthesisIndex);
foreach ($this->sequences as $sequenceSpec) {
$sequenceFound = $tokens->findSequence($sequenceSpec['sequence'], $firstCandidateIndex);
if (null === $sequenceFound) {
continue;
}
$firstSequenceIndex = key($sequenceFound);
if ($firstSequenceIndex !== $firstCandidateIndex) {
continue;
}
$indexesToClear = array_keys($sequenceFound);
array_pop($indexesToClear);
rsort($indexesToClear);
foreach ($indexesToClear as $index) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
$newTokens = [
new Token([T_RETURN, 'return']),
new Token([T_WHITESPACE, ' ']),
];
if ($sequenceSpec['isNegative']) {
$newTokens[] = new Token('!');
} else {
$newTokens[] = new Token([T_BOOL_CAST, '(bool)']);
}
$tokens->overrideRange($ifIndex, $ifIndex, $newTokens);
}
}
}
}
<?php
namespace PhpCsFixer\Fixer\ControlStructure;
use PhpCsFixer\AbstractNoUselessElseFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoSuperfluousElseifFixer extends AbstractNoUselessElseFixer
{
public function isCandidate(Tokens $tokens)
{
return $tokens->isAnyTokenKindsFound([T_ELSE, T_ELSEIF]);
}
public function getDefinition()
{
return new FixerDefinition(
'Replaces superfluous `elseif` with `if`.',
[
new CodeSample("<?php\nif (\$a) {\n return 1;\n} elseif (\$b) {\n return 2;\n}\n"),
]
);
}
public function getPriority()
{
return parent::getPriority();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $index => $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]);
}
}
}
<?php
namespace PhpCsFixer;
final class PregException extends \RuntimeException
{
}
<?php
namespace PhpCsFixer\Indicator;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Tokens;
final class PhpUnitTestCaseIndicator
{
public function isPhpUnitClass(Tokens $tokens, $index)
{
if (!$tokens[$index]->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];
}
}
}
<?php
namespace PhpCsFixer\ConfigurationException;
final class RequiredFixerConfigurationException extends InvalidFixerConfigurationException
{
}
<?php
namespace PhpCsFixer\ConfigurationException;
final class InvalidForEnvFixerConfigurationException extends InvalidFixerConfigurationException
{
}
<?php
namespace PhpCsFixer\ConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
class InvalidFixerConfigurationException extends InvalidConfigurationException
{
private $fixerName;
public function __construct($fixerName, $message, $previous = null)
{
parent::__construct(
sprintf('[%s] %s', $fixerName, $message),
FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG,
$previous
);
$this->fixerName = $fixerName;
}
public function getFixerName()
{
return $this->fixerName;
}
}
<?php
namespace PhpCsFixer\ConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
class InvalidConfigurationException extends \InvalidArgumentException
{
public function __construct($message, $code = null, $previous = null)
{
parent::__construct(
$message,
null === $code ? FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG : $code,
$previous
);
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Tokenizer\Token;
/**
@alt
@gmail
*/
final class Utils
{
public static function calculateBitmask(array $options)
{
$bitmask = 0;
foreach ($options as $optionName) {
if (\defined($optionName)) {
$bitmask |= \constant($optionName);
}
}
return $bitmask;
}
public static function camelCaseToUnderscore($string)
{
return strtolower(Preg::replace('/(?<!^)((?=[A-Z][^A-Z])|(?<![A-Z])(?=[A-Z]))/', '_', $string));
}
public static function cmpInt($a, $b)
{
if ($a === $b) {
return 0;
}
return $a < $b ? -1 : 1;
}
public static function calculateTrailingWhitespaceIndent(Token $token)
{
if (!$token->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;
}
}
<?php
namespace PhpCsFixer\Tokenizer;
use PhpCsFixer\Utils;
class Token
{
private $content;
private $id;
private $isArray;
private $changed = false;
public function __construct($token)
{
if (\is_array($token)) {
if (!\is_int($token[0])) {
throw new \InvalidArgumentException(sprintf(
'Id must be an int, got "%s".',
\is_object($token[0]) ? \get_class($token[0]) : \gettype($token[0])
));
}
if (!\is_string($token[1])) {
throw new \InvalidArgumentException(sprintf(
'Content must be a string, got "%s".',
\is_object($token[1]) ? \get_class($token[1]) : \gettype($token[1])
));
}
if ('' === $token[1]) {
throw new \InvalidArgumentException('Cannot set empty content for id-based Token.');
}
$this->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 === $keywords) {
$keywords = self::getTokenKindsForNames(['T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE',
'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO',
'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH',
'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL',
'T_FINALLY', 'T_FN', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER',
'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF',
'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
'T_NAMESPACE', 'T_MATCH', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE',
'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY',
'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'T_YIELD_FROM',
]) + [
CT::T_ARRAY_TYPEHINT => CT::T_ARRAY_TYPEHINT,
CT::T_CLASS_CONSTANT => CT::T_CLASS_CONSTANT,
CT::T_CONST_IMPORT => CT::T_CONST_IMPORT,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
CT::T_FUNCTION_IMPORT => CT::T_FUNCTION_IMPORT,
CT::T_NAMESPACE_OPERATOR => CT::T_NAMESPACE_OPERATOR,
CT::T_USE_LAMBDA => CT::T_USE_LAMBDA,
CT::T_USE_TRAIT => CT::T_USE_TRAIT,
];
}
return $keywords;
}
public static function getMagicConstants()
{
static $magicConstants = null;
if (null === $magicConstants) {
$magicConstants = self::getTokenKindsForNames(['T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C']);
}
return $magicConstants;
}
public function isArray()
{
return $this->isArray;
}
public function isCast()
{
return $this->isGivenKind(self::getCastTokenKinds());
}
public function isChanged()
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
return $this->changed;
}
public function isClassy()
{
return $this->isGivenKind(self::getClassyTokenKinds());
}
public function isComment()
{
static $commentTokens = [T_COMMENT, T_DOC_COMMENT];
return $this->isGivenKind($commentTokens);
}
public function isEmpty()
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
return null === $this->id && ('' === $this->content || null === $this->content);
}
public function isGivenKind($possibleKind)
{
return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, true) : $this->id === $possibleKind);
}
public function isKeyword()
{
$keywords = static::getKeywords();
return $this->isArray && isset($keywords[$this->id]);
}
public function isNativeConstant()
{
static $nativeConstantStrings = ['true', 'false', 'null'];
return $this->isArray && \in_array(strtolower($this->content), $nativeConstantStrings, true);
}
public function isMagicConstant()
{
$magicConstants = static::getMagicConstants();
return $this->isArray && isset($magicConstants[$this->id]);
}
public function isWhitespace($whitespaces = " \t\n\r\0\x0B")
{
if (null === $whitespaces) {
$whitespaces = " \t\n\r\0\x0B";
}
if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) {
return false;
}
return '' === trim($this->content, $whitespaces);
}
public function override($other)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
Tokens::setLegacyMode(true);
$prototype = $other instanceof self ? $other->getPrototype() : $other;
if ($this->equals($prototype)) {
return;
}
$this->changed = true;
if (\is_array($prototype)) {
$this->isArray = true;
$this->id = $prototype[0];
$this->content = $prototype[1];
return;
}
$this->isArray = false;
$this->id = null;
$this->content = $prototype;
}
public function setContent($content)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
Tokens::setLegacyMode(true);
if ($this->content === $content) {
return;
}
$this->changed = true;
$this->content = $content;
if ('' === $content) {
@trigger_error(__METHOD__.' shall not be used to clear token, use Tokens::clearAt instead.', E_USER_DEPRECATED);
$this->id = null;
$this->isArray = false;
}
}
public function toArray()
{
return [
'id' => $this->id,
'name' => $this->getName(),
'content' => $this->content,
'isArray' => $this->isArray,
'changed' => $this->changed,
];
}
public function toJson(array $options = null)
{
static $defaultOptions = null;
if (null === $options) {
if (null === $defaultOptions) {
$defaultOptions = Utils::calculateBitmask(['JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK']);
}
$options = $defaultOptions;
} else {
$options = Utils::calculateBitmask($options);
}
return json_encode($this->toArray(), $options);
}
private static function getTokenKindsForNames(array $tokenNames)
{
$keywords = [];
foreach ($tokenNames as $keywordName) {
if (\defined($keywordName)) {
$keyword = \constant($keywordName);
$keywords[$keyword] = $keyword;
}
}
return $keywords;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Resolver;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
final class TypeShortNameResolver
{
public function resolve(Tokens $tokens, $typeName)
{
$useMap = $this->getUseMapFromTokens($tokens);
foreach ($useMap as $shortName => $fullName) {
$regex = '/^\\\\?'.preg_quote($fullName, '/').'$/';
if (Preg::match($regex, $typeName)) {
return $shortName;
}
}
$namespaces = $this->getNamespacesFromTokens($tokens);
if (1 === \count($namespaces)) {
foreach ($namespaces as $fullName) {
$matches = [];
$regex = '/^\\\\?'.preg_quote($fullName, '/').'\\\\(?P<className>.+)$/';
if (Preg::match($regex, $typeName, $matches)) {
return $matches['className'];
}
}
}
foreach ($useMap as $shortName => $fullName) {
$matches = [];
$regex = '/^\\\\?'.preg_quote($fullName, '/').'\\\\(?P<className>.+)$/';
if (Preg::match($regex, $typeName, $matches)) {
return $shortName.'\\'.$matches['className'];
}
}
return $typeName;
}
private function getNamespacesFromTokens(Tokens $tokens)
{
return array_map(static function (NamespaceAnalysis $info) {
return $info->getFullName();
}, (new NamespacesAnalyzer())->getDeclarations($tokens));
}
private function getUseMapFromTokens(Tokens $tokens)
{
$map = [];
foreach ((new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens) as $useDeclaration) {
$map[$useDeclaration->getShortName()] = $useDeclaration->getFullName();
}
return $map;
}
}
<?php
namespace PhpCsFixer\Tokenizer;
interface TransformerInterface
{
public function getCustomTokens();
public function getName();
public function getPriority();
public function getRequiredPhpVersionId();
public function process(Tokens $tokens, Token $token, $index);
}
<?php
namespace PhpCsFixer\Tokenizer;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
/**
@web
*/
final class TokensAnalyzer
{
private $tokens;
private $gotoLabelAnalyzer;
public function __construct(Tokens $tokens)
{
$this->tokens = $tokens;
}
public function getClassyElements($returnTraitsImports = false)
{
$elements = [];
for ($index = 1, $count = \count($this->tokens) - 2; $index < $count; ++$index) {
if ($this->tokens[$index]->isClassy()) {
list($index, $newElements) = $this->findClassyElements($index, $index, $returnTraitsImports);
$elements += $newElements;
}
}
ksort($elements);
return $elements;
}
public function getImportUseIndexes($perNamespace = false)
{
$tokens = $this->tokens;
$uses = [];
$namespaceIndex = 0;
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_NAMESPACE)) {
$nextTokenIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
$nextToken = $tokens[$nextTokenIndex];
if ($nextToken->equals('{')) {
$index = $nextTokenIndex;
}
if ($perNamespace) {
++$namespaceIndex;
}
continue;
}
if ($token->isGivenKind(T_USE)) {
$uses[$namespaceIndex][] = $index;
}
}
if (!$perNamespace && isset($uses[$namespaceIndex])) {
return $uses[$namespaceIndex];
}
return $uses;
}
public function isArray($index)
{
return $this->tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
}
public function isArrayMultiLine($index)
{
if (!$this->isArray($index)) {
throw new \InvalidArgumentException(sprintf('Not an array at given index %d.', $index));
}
$tokens = $this->tokens;
if ($tokens[$index]->isGivenKind(T_ARRAY)) {
$index = $tokens->getNextMeaningfulToken($index);
}
$endIndex = $tokens[$index]->equals('(')
? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index)
: $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index)
;
for (++$index; $index < $endIndex; ++$index) {
$token = $tokens[$index];
$blockType = Tokens::detectBlockType($token);
if ($blockType && $blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
continue;
}
if (
$token->isWhitespace()
&& !$tokens[$index - 1]->isGivenKind(T_END_HEREDOC)
&& false !== strpos($token->getContent(), "\n")
) {
return true;
}
}
return false;
}
public function getMethodAttributes($index)
{
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isGivenKind(T_FUNCTION)) {
throw new \LogicException(sprintf('No T_FUNCTION at given index %d, got "%s".', $index, $token->getName()));
}
$attributes = [
'visibility' => null,
'static' => false,
'abstract' => false,
'final' => false,
];
for ($i = $index; $i >= 0; --$i) {
$tokenIndex = $tokens->getPrevMeaningfulToken($i);
$i = $tokenIndex;
$token = $tokens[$tokenIndex];
if ($token->isGivenKind(T_STATIC)) {
$attributes['static'] = true;
continue;
}
if ($token->isGivenKind(T_FINAL)) {
$attributes['final'] = true;
continue;
}
if ($token->isGivenKind(T_ABSTRACT)) {
$attributes['abstract'] = true;
continue;
}
if ($token->isGivenKind(T_PRIVATE)) {
$attributes['visibility'] = T_PRIVATE;
continue;
}
if ($token->isGivenKind(T_PROTECTED)) {
$attributes['visibility'] = T_PROTECTED;
continue;
}
if ($token->isGivenKind(T_PUBLIC)) {
$attributes['visibility'] = T_PUBLIC;
continue;
}
break;
}
return $attributes;
}
public function isAnonymousClass($index)
{
if (!$this->tokens[$index]->isClassy()) {
throw new \LogicException(sprintf('No classy token at given index %d.', $index));
}
if (!$this->tokens[$index]->isGivenKind(T_CLASS)) {
return false;
}
return $this->tokens[$this->tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW);
}
public function isLambda($index)
{
if (
!$this->tokens[$index]->isGivenKind(T_FUNCTION)
&& (\PHP_VERSION_ID < 70400 || !$this->tokens[$index]->isGivenKind(T_FN))
) {
throw new \LogicException(sprintf('No T_FUNCTION or T_FN at given index %d, got "%s".', $index, $this->tokens[$index]->getName()));
}
$startParenthesisIndex = $this->tokens->getNextMeaningfulToken($index);
$startParenthesisToken = $this->tokens[$startParenthesisIndex];
if ($startParenthesisToken->isGivenKind(CT::T_RETURN_REF)) {
$startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex);
$startParenthesisToken = $this->tokens[$startParenthesisIndex];
}
return $startParenthesisToken->equals('(');
}
public function isConstantInvocation($index)
{
if (!$this->tokens[$index]->isGivenKind(T_STRING)) {
throw new \LogicException(sprintf('No T_STRING at given index %d, got "%s".', $index, $this->tokens[$index]->getName()));
}
$nextIndex = $this->tokens->getNextMeaningfulToken($index);
if (
$this->tokens[$nextIndex]->equalsAny(['(', '{'])
|| $this->tokens[$nextIndex]->isGivenKind([T_AS, T_DOUBLE_COLON, T_ELLIPSIS, T_NS_SEPARATOR, CT::T_RETURN_REF, CT::T_TYPE_ALTERNATION, T_VARIABLE])
) {
return false;
}
$prevIndex = $this->tokens->getPrevMeaningfulToken($index);
if ($this->tokens[$prevIndex]->isGivenKind([T_AS, T_CLASS, T_CONST, T_DOUBLE_COLON, T_FUNCTION, T_GOTO, CT::T_GROUP_IMPORT_BRACE_OPEN, T_INTERFACE, T_OBJECT_OPERATOR, T_TRAIT, CT::T_TYPE_COLON])) {
return false;
}
while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_NS_SEPARATOR, T_STRING])) {
$prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex);
}
if ($this->tokens[$prevIndex]->isGivenKind([CT::T_CONST_IMPORT, T_EXTENDS, CT::T_FUNCTION_IMPORT, T_IMPLEMENTS, T_INSTANCEOF, T_INSTEADOF, T_NAMESPACE, T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, T_USE, CT::T_USE_TRAIT])) {
return false;
}
if ($this->tokens[$nextIndex]->equals('&') && $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(T_VARIABLE)) {
$checkIndex = $this->tokens->getPrevTokenOfKind($prevIndex, [';', '{', '}', [T_FUNCTION], [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]]);
if ($this->tokens[$checkIndex]->isGivenKind(T_FUNCTION)) {
return false;
}
}
if ($this->tokens[$prevIndex]->equals(',')) {
$checkIndex = $prevIndex;
while ($this->tokens[$checkIndex]->equalsAny([',', [T_AS], [CT::T_NAMESPACE_OPERATOR], [T_NS_SEPARATOR], [T_STRING]])) {
$checkIndex = $this->tokens->getPrevMeaningfulToken($checkIndex);
}
if ($this->tokens[$checkIndex]->isGivenKind([T_EXTENDS, CT::T_GROUP_IMPORT_BRACE_OPEN, T_IMPLEMENTS, T_USE, CT::T_USE_TRAIT])) {
return false;
}
}
if ($this->tokens[$prevIndex]->equals('[') && $this->tokens[$nextIndex]->equals(']')) {
$checkToken = $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)];
if ($checkToken->equals('"') || $checkToken->isGivenKind([T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES, T_ENCAPSED_AND_WHITESPACE, T_VARIABLE])) {
return false;
}
}
if ($this->tokens[$nextIndex]->equals(':')) {
if (null === $this->gotoLabelAnalyzer) {
$this->gotoLabelAnalyzer = new GotoLabelAnalyzer();
}
if ($this->gotoLabelAnalyzer->belongsToGoToLabel($this->tokens, $nextIndex)) {
return false;
}
}
return true;
}
public function isUnarySuccessorOperator($index)
{
static $allowedPrevToken = [
']',
[T_STRING],
[T_VARIABLE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
];
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isGivenKind([T_INC, T_DEC])) {
return false;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
return $prevToken->equalsAny($allowedPrevToken);
}
public function isUnaryPredecessorOperator($index)
{
static $potentialSuccessorOperator = [T_INC, T_DEC];
static $potentialBinaryOperator = ['+', '-', '&', [CT::T_RETURN_REF]];
static $otherOperators;
if (null === $otherOperators) {
$otherOperators = ['!', '~', '@', [T_ELLIPSIS]];
}
static $disallowedPrevTokens;
if (null === $disallowedPrevTokens) {
$disallowedPrevTokens = [
']',
'}',
')',
'"',
'`',
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[T_CLASS_C],
[T_CONSTANT_ENCAPSED_STRING],
[T_DEC],
[T_DIR],
[T_DNUMBER],
[T_FILE],
[T_FUNC_C],
[T_INC],
[T_LINE],
[T_LNUMBER],
[T_METHOD_C],
[T_NS_C],
[T_STRING],
[T_TRAIT_C],
[T_VARIABLE],
];
}
$tokens = $this->tokens;
$token = $tokens[$index];
if ($token->isGivenKind($potentialSuccessorOperator)) {
return !$this->isUnarySuccessorOperator($index);
}
if ($token->equalsAny($otherOperators)) {
return true;
}
if (!$token->equalsAny($potentialBinaryOperator)) {
return false;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny($disallowedPrevTokens)) {
return true;
}
if (!$token->equals('&') || !$prevToken->isGivenKind(T_STRING)) {
return false;
}
static $searchTokens = [
';',
'{',
'}',
[T_FUNCTION],
[T_OPEN_TAG],
[T_OPEN_TAG_WITH_ECHO],
];
$prevToken = $tokens[$tokens->getPrevTokenOfKind($index, $searchTokens)];
return $prevToken->isGivenKind(T_FUNCTION);
}
public function isBinaryOperator($index)
{
static $nonArrayOperators = [
'=' => true,
'*' => true,
'/' => true,
'%' => true,
'<' => true,
'>' => true,
'|' => true,
'^' => true,
'.' => true,
];
static $potentialUnaryNonArrayOperators = [
'+' => true,
'-' => true,
'&' => true,
];
static $arrayOperators;
if (null === $arrayOperators) {
$arrayOperators = [
T_AND_EQUAL => true,
T_BOOLEAN_AND => true,
T_BOOLEAN_OR => true,
T_CONCAT_EQUAL => true,
T_DIV_EQUAL => true,
T_DOUBLE_ARROW => 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_LOGICAL_AND => true,
T_LOGICAL_OR => true,
T_LOGICAL_XOR => true,
T_MINUS_EQUAL => true,
T_MOD_EQUAL => true,
T_MUL_EQUAL => true,
T_OR_EQUAL => true,
T_PLUS_EQUAL => true,
T_POW => true,
T_POW_EQUAL => true,
T_SL => true,
T_SL_EQUAL => true,
T_SR => true,
T_SR_EQUAL => true,
T_XOR_EQUAL => true,
CT::T_TYPE_ALTERNATION => true,
];
if (\defined('T_SPACESHIP')) {
$arrayOperators[T_SPACESHIP] = true;
}
if (\defined('T_COALESCE')) {
$arrayOperators[T_COALESCE] = true;
}
if (\defined('T_COALESCE_EQUAL')) {
$arrayOperators[T_COALESCE_EQUAL] = true;
}
}
$tokens = $this->tokens;
$token = $tokens[$index];
if ($token->isArray()) {
return isset($arrayOperators[$token->getId()]);
}
if (isset($nonArrayOperators[$token->getContent()])) {
return true;
}
if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) {
return !$this->isUnaryPredecessorOperator($index);
}
return false;
}
public function isWhilePartOfDoWhile($index)
{
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isGivenKind(T_WHILE)) {
throw new \LogicException(sprintf('No T_WHILE at given index %d, got "%s".', $index, $token->getName()));
}
$endIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$endIndex]->equals('}')) {
return false;
}
$startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex);
$beforeStartIndex = $tokens->getPrevMeaningfulToken($startIndex);
return $tokens[$beforeStartIndex]->isGivenKind(T_DO);
}
public function isSuperGlobal($index)
{
static $superNames = [
'$_COOKIE' => true,
'$_ENV' => true,
'$_FILES' => true,
'$_GET' => true,
'$_POST' => true,
'$_REQUEST' => true,
'$_SERVER' => true,
'$_SESSION' => true,
'$GLOBALS' => true,
];
$token = $this->tokens[$index];
if (!$token->isGivenKind(T_VARIABLE)) {
return false;
}
return isset($superNames[strtoupper($token->getContent())]);
}
private function findClassyElements($classIndex, $index, $returnTraitsImports = false)
{
$elements = [];
$curlyBracesLevel = 0;
$bracesLevel = 0;
++$index;
for ($count = \count($this->tokens); $index < $count; ++$index) {
$token = $this->tokens[$index];
if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) {
continue;
}
if ($token->isClassy()) {
$nestedClassIndex = $index;
$index = $this->tokens->getNextMeaningfulToken($index);
if ($this->tokens[$index]->equals('(')) {
++$index;
for ($nestedBracesLevel = 1; $index < $count; ++$index) {
$token = $this->tokens[$index];
if ($token->equals('(')) {
++$nestedBracesLevel;
continue;
}
if ($token->equals(')')) {
--$nestedBracesLevel;
if (0 === $nestedBracesLevel) {
list($index, $newElements) = $this->findClassyElements($nestedClassIndex, $index, $returnTraitsImports);
$elements += $newElements;
break;
}
continue;
}
if ($token->isClassy()) {
list($index, $newElements) = $this->findClassyElements($index, $index, $returnTraitsImports);
$elements += $newElements;
}
}
} else {
list($index, $newElements) = $this->findClassyElements($nestedClassIndex, $nestedClassIndex, $returnTraitsImports);
$elements += $newElements;
}
continue;
}
if ($token->equals('(')) {
++$bracesLevel;
continue;
}
if ($token->equals(')')) {
--$bracesLevel;
continue;
}
if ($token->equals('{')) {
++$curlyBracesLevel;
continue;
}
if ($token->equals('}')) {
--$curlyBracesLevel;
if (0 === $curlyBracesLevel) {
break;
}
continue;
}
if (1 !== $curlyBracesLevel || !$token->isArray()) {
continue;
}
if (0 === $bracesLevel && $token->isGivenKind(T_VARIABLE)) {
$elements[$index] = [
'token' => $token,
'type' => 'property',
'classIndex' => $classIndex,
];
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
$elements[$index] = [
'token' => $token,
'type' => 'method',
'classIndex' => $classIndex,
];
} elseif ($token->isGivenKind(T_CONST)) {
$elements[$index] = [
'token' => $token,
'type' => 'const',
'classIndex' => $classIndex,
];
} elseif ($returnTraitsImports && $token->isGivenKind(CT::T_USE_TRAIT)) {
$elements[$index] = [
'token' => $token,
'type' => 'trait_import',
'classIndex' => $classIndex,
];
}
}
return [$index, $elements];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Generator;
use PhpCsFixer\Tokenizer\Token;
final class NamespacedStringTokenGenerator
{
public function generate($input)
{
$tokens = [];
$parts = explode('\\', $input);
foreach ($parts as $index => $part) {
$tokens[] = new Token([T_STRING, $part]);
if ($index !== \count($parts) - 1) {
$tokens[] = new Token([T_NS_SEPARATOR, '\\']);
}
}
return $tokens;
}
}
<?php
namespace PhpCsFixer\Tokenizer;
final class CodeHasher
{
private function __construct()
{
}
public static function calculateCodeHash($code)
{
return (string) crc32($code);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class WhitespacyCommentTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->isComment()) {
return;
}
$content = $token->getContent();
$trimmedContent = rtrim($content);
if ($content === $trimmedContent) {
return;
}
$whitespaces = substr($content, \strlen($trimmedContent));
$tokens[$index] = new Token([$token->getId(), $trimmedContent]);
if (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) {
$tokens[$index + 1] = new Token([T_WHITESPACE, $whitespaces.$tokens[$index + 1]->getContent()]);
} else {
$tokens->insertAt($index + 1, new Token([T_WHITESPACE, $whitespaces]));
}
}
protected function getDeprecatedCustomTokens()
{
return [];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NullableTypeTransformer extends AbstractTransformer
{
public function getPriority()
{
return -20;
}
public function getRequiredPhpVersionId()
{
return 70100;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->equals('?')) {
return;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->equalsAny([
'(',
',',
[CT::T_TYPE_COLON],
[CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC],
[CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED],
[CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE],
[T_PRIVATE],
[T_PROTECTED],
[T_PUBLIC],
[T_VAR],
[T_STATIC],
])) {
$tokens[$index] = new Token([CT::T_NULLABLE_TYPE, '?']);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_NULLABLE_TYPE];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CurlyBraceTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
$this->transformIntoCurlyCloseBrace($tokens, $token, $index);
$this->transformIntoDollarCloseBrace($tokens, $token, $index);
$this->transformIntoDynamicPropBraces($tokens, $token, $index);
$this->transformIntoDynamicVarBraces($tokens, $token, $index);
$this->transformIntoCurlyIndexBraces($tokens, $token, $index);
if (\PHP_VERSION_ID >= 70000) {
$this->transformIntoGroupUseBraces($tokens, $token, $index);
}
}
protected function getDeprecatedCustomTokens()
{
return [
CT::T_CURLY_CLOSE,
CT::T_DOLLAR_CLOSE_CURLY_BRACES,
CT::T_DYNAMIC_PROP_BRACE_OPEN,
CT::T_DYNAMIC_PROP_BRACE_CLOSE,
CT::T_DYNAMIC_VAR_BRACE_OPEN,
CT::T_DYNAMIC_VAR_BRACE_CLOSE,
CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN,
CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE,
CT::T_GROUP_IMPORT_BRACE_OPEN,
CT::T_GROUP_IMPORT_BRACE_CLOSE,
];
}
private function transformIntoCurlyCloseBrace(Tokens $tokens, Token $token, $index)
{
if (!$token->isGivenKind(T_CURLY_OPEN)) {
return;
}
$level = 1;
$nestIndex = $index;
while (0 < $level) {
++$nestIndex;
if ($tokens[$nestIndex]->equals('{')) {
++$level;
continue;
}
if ($tokens[$nestIndex]->equals('}')) {
--$level;
}
}
$tokens[$nestIndex] = new Token([CT::T_CURLY_CLOSE, '}']);
}
private function transformIntoDollarCloseBrace(Tokens $tokens, Token $token, $index)
{
if ($token->isGivenKind(T_DOLLAR_OPEN_CURLY_BRACES)) {
$nextIndex = $tokens->getNextTokenOfKind($index, ['}']);
$tokens[$nextIndex] = new Token([CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}']);
}
}
private function transformIntoDynamicPropBraces(Tokens $tokens, Token $token, $index)
{
if (!$token->isGivenKind(T_OBJECT_OPERATOR)) {
return;
}
if (!$tokens[$index + 1]->equals('{')) {
return;
}
$openIndex = $index + 1;
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
$tokens[$openIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_OPEN, '{']);
$tokens[$closeIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}']);
}
private function transformIntoDynamicVarBraces(Tokens $tokens, Token $token, $index)
{
if (!$token->equals('$')) {
return;
}
$openIndex = $tokens->getNextMeaningfulToken($index);
if (null === $openIndex) {
return;
}
$openToken = $tokens[$openIndex];
if (!$openToken->equals('{')) {
return;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
$tokens[$openIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_OPEN, '{']);
$tokens[$closeIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}']);
}
private function transformIntoCurlyIndexBraces(Tokens $tokens, Token $token, $index)
{
if (!$token->equals('{')) {
return;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->equalsAny([
[T_STRING],
[T_VARIABLE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
']',
')',
])) {
return;
}
if (
$tokens[$prevIndex]->isGivenKind(T_STRING)
&& !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(T_OBJECT_OPERATOR)
) {
return;
}
if (
$tokens[$prevIndex]->equals(')')
&& !$tokens[$tokens->getPrevMeaningfulToken(
$tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex)
)]->isGivenKind(T_ARRAY)
) {
return;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
$tokens[$index] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']);
$tokens[$closeIndex] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}']);
}
private function transformIntoGroupUseBraces(Tokens $tokens, Token $token, $index)
{
if (!$token->equals('{')) {
return;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
return;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
$tokens[$index] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']);
$tokens[$closeIndex] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class UseTransformer extends AbstractTransformer
{
public function getPriority()
{
return -5;
}
public function getRequiredPhpVersionId()
{
return 50300;
}
public function process(Tokens $tokens, Token $token, $index)
{
if ($token->isGivenKind(T_USE) && $this->isUseForLambda($tokens, $index)) {
$tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]);
return;
}
if (!$token->isGivenKind([T_CLASS, T_TRAIT])) {
return;
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_DOUBLE_COLON)) {
return;
}
$index = $tokens->getNextTokenOfKind($index, ['{']);
$innerLimit = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
while ($index < $innerLimit) {
$token = $tokens[++$index];
if (!$token->isGivenKind(T_USE)) {
continue;
}
if ($this->isUseForLambda($tokens, $index)) {
$tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]);
} else {
$tokens[$index] = new Token([CT::T_USE_TRAIT, $token->getContent()]);
}
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_USE_TRAIT, CT::T_USE_LAMBDA];
}
private function isUseForLambda(Tokens $tokens, $index)
{
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
return $nextToken->equals('(');
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ClassConstantTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50500;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->equalsAny([
[T_CLASS, 'class'],
[T_STRING, 'class'],
], false)) {
return;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(T_DOUBLE_COLON)) {
$tokens[$index] = new Token([CT::T_CLASS_CONSTANT, $token->getContent()]);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_CLASS_CONSTANT];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NamedArgumentTransformer extends AbstractTransformer
{
public function getPriority()
{
return -15;
}
public function getRequiredPhpVersionId()
{
return 80000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$tokens[$index]->equals(':')) {
return;
}
$stringIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$stringIndex]->isGivenKind(T_STRING)) {
return;
}
$preStringIndex = $tokens->getPrevMeaningfulToken($stringIndex);
if (!$tokens[$preStringIndex]->equalsAny([',', '('])) {
return;
}
$tokens[$stringIndex] = new Token([CT::T_NAMED_ARGUMENT_NAME, $tokens[$stringIndex]->getContent()]);
$tokens[$index] = new Token([CT::T_NAMED_ARGUMENT_COLON, ':']);
}
protected function getDeprecatedCustomTokens()
{
return [
CT::T_NAMED_ARGUMENT_COLON,
CT::T_NAMED_ARGUMENT_NAME,
];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ConstructorPromotionTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 80000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$tokens[$index]->isGivenKind(T_FUNCTION)) {
return;
}
$index = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$index]->isGivenKind(T_STRING) || '__construct' !== strtolower($tokens[$index]->getContent())) {
return;
}
$openIndex = $tokens->getNextMeaningfulToken($index);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
for ($index = $openIndex; $index < $closeIndex; ++$index) {
if ($tokens[$index]->isGivenKind(T_PUBLIC)) {
$tokens[$index] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, $tokens[$index]->getContent()]);
} elseif ($tokens[$index]->isGivenKind(T_PROTECTED)) {
$tokens[$index] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, $tokens[$index]->getContent()]);
} elseif ($tokens[$index]->isGivenKind(T_PRIVATE)) {
$tokens[$index] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, $tokens[$index]->getContent()]);
}
}
}
protected function getDeprecatedCustomTokens()
{
return [
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ArrayTypehintTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->isGivenKind(T_ARRAY)) {
return;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
if (!$nextToken->equals('(')) {
$tokens[$index] = new Token([CT::T_ARRAY_TYPEHINT, $token->getContent()]);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_ARRAY_TYPEHINT];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NameQualifiedTransformer extends AbstractTransformer
{
public function getPriority()
{
return 1;
}
public function getRequiredPhpVersionId()
{
return 80000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if ($token->isGivenKind([T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED])) {
return $this->transformQualified($tokens, $token, $index);
}
if ($token->isGivenKind(T_NAME_RELATIVE)) {
return $this->transformRelative($tokens, $token, $index);
}
}
protected function getDeprecatedCustomTokens()
{
return [];
}
private function transformQualified(Tokens $tokens, Token $token, $index)
{
$parts = explode('\\', $token->getContent());
$newTokens = [];
if ('' === $parts[0]) {
$newTokens[] = new Token([T_NS_SEPARATOR, '\\']);
array_shift($parts);
}
foreach ($parts as $part) {
$newTokens[] = new Token([T_STRING, $part]);
$newTokens[] = new Token([T_NS_SEPARATOR, '\\']);
}
array_pop($newTokens);
$tokens->overrideRange($index, $index, $newTokens);
}
private function transformRelative(Tokens $tokens, Token $token, $index)
{
$parts = explode('\\', $token->getContent());
$newTokens = [
new Token([T_NAMESPACE, array_shift($parts)]),
new Token([T_NS_SEPARATOR, '\\']),
];
foreach ($parts as $part) {
$newTokens[] = new Token([T_STRING, $part]);
$newTokens[] = new Token([T_NS_SEPARATOR, '\\']);
}
array_pop($newTokens);
$tokens->overrideRange($index, $index, $newTokens);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class AttributeTransformer extends AbstractTransformer
{
public function getPriority()
{
return 200;
}
public function getRequiredPhpVersionId()
{
return 80000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$tokens[$index]->isGivenKind(T_ATTRIBUTE)) {
return;
}
$level = 1;
do {
++$index;
if ($tokens[$index]->equals('[')) {
++$level;
} elseif ($tokens[$index]->equals(']')) {
--$level;
}
} while (0 < $level);
$tokens[$index] = new Token([CT::T_ATTRIBUTE_CLOSE, ']']);
}
protected function getDeprecatedCustomTokens()
{
return [
CT::T_ATTRIBUTE_CLOSE,
];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NamespaceOperatorTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50300;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->isGivenKind(T_NAMESPACE)) {
return;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(T_NS_SEPARATOR)) {
$tokens[$index] = new Token([CT::T_NAMESPACE_OPERATOR, $token->getContent()]);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_NAMESPACE_OPERATOR];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ImportTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50600;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->isGivenKind([T_CONST, T_FUNCTION])) {
return;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->isGivenKind(T_USE)) {
$tokens[$index] = new Token([
$token->isGivenKind(T_FUNCTION) ? CT::T_FUNCTION_IMPORT : CT::T_CONST_IMPORT,
$token->getContent(),
]);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class TypeColonTransformer extends AbstractTransformer
{
public function getPriority()
{
return -10;
}
public function getRequiredPhpVersionId()
{
return 70000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->equals(':')) {
return;
}
$endIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$endIndex]->equals(')')) {
return;
}
$startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex);
$prevIndex = $tokens->getPrevMeaningfulToken($startIndex);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(T_STRING)) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
$prevToken = $tokens[$prevIndex];
}
$prevKinds = [T_FUNCTION, CT::T_RETURN_REF, CT::T_USE_LAMBDA];
if (\PHP_VERSION_ID >= 70400) {
$prevKinds[] = T_FN;
}
if ($prevToken->isGivenKind($prevKinds)) {
$tokens[$index] = new Token([CT::T_TYPE_COLON, ':']);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_TYPE_COLON];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class BraceClassInstantiationTransformer extends AbstractTransformer
{
public function getPriority()
{
return -2;
}
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$tokens[$index]->equals('(') || !$tokens[$tokens->getNextMeaningfulToken($index)]->equals([T_NEW])) {
return;
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny([
']',
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[T_ARRAY],
[T_CLASS],
[T_ELSEIF],
[T_FOR],
[T_FOREACH],
[T_IF],
[T_STATIC],
[T_STRING],
[T_SWITCH],
[T_VARIABLE],
[T_WHILE],
])) {
return;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$tokens[$index] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '(']);
$tokens[$closeIndex] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')']);
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, CT::T_BRACE_CLASS_INSTANTIATION_CLOSE];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class TypeAlternationTransformer extends AbstractTransformer
{
public function getPriority()
{
return -15;
}
public function getRequiredPhpVersionId()
{
return 70100;
}
public function process(Tokens $tokens, Token $token, $index)
{
if (!$token->equals('|')) {
return;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->isGivenKind(T_STRING)) {
return;
}
do {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if (null === $prevIndex) {
return;
}
if (!$tokens[$prevIndex]->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
break;
}
} while (true);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind([
CT::T_TYPE_COLON,
CT::T_TYPE_ALTERNATION,
T_VAR, T_PUBLIC, T_PROTECTED, T_PRIVATE,
])) {
$this->replaceToken($tokens, $index);
return;
}
if (!$prevToken->equals('(')) {
return;
}
$prevPrevTokenIndex = $tokens->getPrevMeaningfulToken($prevIndex);
$prePrevToken = $tokens[$prevPrevTokenIndex];
if ($prePrevToken->isGivenKind([
T_CATCH,
T_FUNCTION,
])) {
$this->replaceToken($tokens, $index);
return;
}
if (\PHP_VERSION_ID >= 70400 && $prePrevToken->isGivenKind(T_FN)) {
$this->replaceToken($tokens, $index);
return;
}
if (
$prePrevToken->isGivenKind(T_STRING)
&& $tokens[$tokens->getPrevMeaningfulToken($prevPrevTokenIndex)]->isGivenKind(T_FUNCTION)
) {
$this->replaceToken($tokens, $index);
return;
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_TYPE_ALTERNATION];
}
private function replaceToken(Tokens $tokens, $index)
{
$tokens[$index] = new Token([CT::T_TYPE_ALTERNATION, '|']);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ReturnRefTransformer extends AbstractTransformer
{
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
$prevKinds = [T_FUNCTION];
if (\PHP_VERSION_ID >= 70400) {
$prevKinds[] = T_FN;
}
if (
$token->equals('&')
&& $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind($prevKinds)
) {
$tokens[$index] = new Token([CT::T_RETURN_REF, '&']);
}
}
protected function getDeprecatedCustomTokens()
{
return [CT::T_RETURN_REF];
}
}
<?php
namespace PhpCsFixer\Tokenizer\Transformer;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class SquareBraceTransformer extends AbstractTransformer
{
public function getPriority()
{
return -1;
}
public function getRequiredPhpVersionId()
{
return 50000;
}
public function process(Tokens $tokens, Token $token, $index)
{
if ($this->isArrayDestructing($tokens, $index)) {
$this->transformIntoDestructuringSquareBrace($tokens, $index);
return;
}
if ($this->isShortArray($tokens, $index)) {
$this->transformIntoArraySquareBrace($tokens, $index);
}
}
protected function getDeprecatedCustomTokens()
{
return [
CT::T_ARRAY_SQUARE_BRACE_OPEN,
CT::T_ARRAY_SQUARE_BRACE_CLOSE,
CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN,
CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE,
];
}
private function transformIntoArraySquareBrace(Tokens $tokens, $index)
{
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index);
$tokens[$index] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']);
$tokens[$endIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']);
}
private function transformIntoDestructuringSquareBrace(Tokens $tokens, $index)
{
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index);
$tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']);
$tokens[$endIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']);
$previousMeaningfulIndex = $index;
$index = $tokens->getNextMeaningfulToken($index);
while ($index < $endIndex) {
if ($tokens[$index]->equals('[') && $tokens[$previousMeaningfulIndex]->equalsAny([[CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], ','])) {
$tokens[$tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index)] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']);
$tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']);
}
$previousMeaningfulIndex = $index;
$index = $tokens->getNextMeaningfulToken($index);
}
}
private function isShortArray(Tokens $tokens, $index)
{
if (!$tokens[$index]->equals('[')) {
return false;
}
static $disallowedPrevTokens = [
')',
']',
'}',
'"',
[T_CONSTANT_ENCAPSED_STRING],
[T_STRING],
[T_STRING_VARNAME],
[T_VARIABLE],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
];
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->equalsAny($disallowedPrevTokens)) {
return false;
}
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if ($nextToken->equals(']')) {
return true;
}
return !$this->isArrayDestructing($tokens, $index);
}
private function isArrayDestructing(Tokens $tokens, $index)
{
if (\PHP_VERSION_ID < 70100 || !$tokens[$index]->equals('[')) {
return false;
}
static $disallowedPrevTokens = [
')',
']',
'"',
[T_CONSTANT_ENCAPSED_STRING],
[T_STRING],
[T_STRING_VARNAME],
[T_VARIABLE],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
];
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->equalsAny($disallowedPrevTokens)) {
return false;
}
$type = Tokens::detectBlockType($tokens[$index]);
$end = $tokens->findBlockEnd($type['type'], $index);
$nextToken = $tokens[$tokens->getNextMeaningfulToken($end)];
return $nextToken->equals('=');
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
@gmail
*/
final class ArgumentsAnalyzer
{
public function countArguments(Tokens $tokens, $openParenthesis, $closeParenthesis)
{
return \count($this->getArguments($tokens, $openParenthesis, $closeParenthesis));
}
public function getArguments(Tokens $tokens, $openParenthesis, $closeParenthesis)
{
$arguments = [];
$firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis);
if ($tokens[$firstSensibleToken]->equals(')')) {
return $arguments;
}
$paramContentIndex = $openParenthesis + 1;
$argumentsStart = $paramContentIndex;
for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) {
$token = $tokens[$paramContentIndex];
$blockDefinitionProbe = Tokens::detectBlockType($token);
if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) {
$paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex);
continue;
}
if ($token->equals(',')) {
if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) {
break;
}
$arguments[$argumentsStart] = $paramContentIndex - 1;
$argumentsStart = $paramContentIndex + 1;
}
}
$arguments[$argumentsStart] = $paramContentIndex - 1;
return $arguments;
}
public function getArgumentInfo(Tokens $tokens, $argumentStart, $argumentEnd)
{
$info = [
'default' => null,
'name' => null,
'name_index' => null,
'type' => null,
'type_index_start' => null,
'type_index_end' => null,
];
$sawName = false;
for ($index = $argumentStart; $index <= $argumentEnd; ++$index) {
$token = $tokens[$index];
if (
$token->isComment()
|| $token->isWhitespace()
|| $token->isGivenKind([T_ELLIPSIS, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE])
|| $token->equals('&')
) {
continue;
}
if ($token->isGivenKind(T_VARIABLE)) {
$sawName = true;
$info['name_index'] = $index;
$info['name'] = $token->getContent();
continue;
}
if ($token->equals('=')) {
continue;
}
if ($sawName) {
$info['default'] .= $token->getContent();
} else {
$info['type_index_start'] = ($info['type_index_start'] > 0) ? $info['type_index_start'] : $index;
$info['type_index_end'] = $index;
$info['type'] .= $token->getContent();
}
}
return new ArgumentAnalysis(
$info['name'],
$info['name_index'],
$info['default'],
$info['type'] ? new TypeAnalysis($info['type'], $info['type_index_start'], $info['type_index_end']) : null
);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class CommentsAnalyzer
{
const TYPE_HASH = 1;
const TYPE_DOUBLE_SLASH = 2;
const TYPE_SLASH_ASTERISK = 3;
public function isHeaderComment(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind([T_COMMENT, T_DOC_COMMENT])) {
throw new \InvalidArgumentException('Given index must point to a comment.');
}
if (null === $tokens->getNextMeaningfulToken($index)) {
return false;
}
$prevIndex = $tokens->getPrevNonWhitespace($index);
if ($tokens[$prevIndex]->equals(';')) {
$braceCloseIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if (!$tokens[$braceCloseIndex]->equals(')')) {
return false;
}
$braceOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceCloseIndex);
$declareIndex = $tokens->getPrevMeaningfulToken($braceOpenIndex);
if (!$tokens[$declareIndex]->isGivenKind(T_DECLARE)) {
return false;
}
$prevIndex = $tokens->getPrevNonWhitespace($declareIndex);
}
return $tokens[$prevIndex]->isGivenKind(T_OPEN_TAG);
}
public function isBeforeStructuralElement(Tokens $tokens, $index)
{
$token = $tokens[$index];
if (!$token->isGivenKind([T_COMMENT, T_DOC_COMMENT])) {
throw new \InvalidArgumentException('Given index must point to a comment.');
}
$nextIndex = $index;
do {
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (\defined('T_ATTRIBUTE')) {
while (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_ATTRIBUTE)) {
$nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex);
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
}
}
} while (null !== $nextIndex && $tokens[$nextIndex]->equals('('));
if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) {
return false;
}
$nextToken = $tokens[$nextIndex];
if ($this->isStructuralElement($nextToken)) {
return true;
}
if ($this->isValidControl($tokens, $token, $nextIndex)) {
return true;
}
if ($this->isValidVariable($tokens, $nextIndex)) {
return true;
}
if ($this->isValidLanguageConstruct($tokens, $token, $nextIndex)) {
return true;
}
return false;
}
public function getCommentBlockIndices(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_COMMENT)) {
throw new \InvalidArgumentException('Given index must point to a comment.');
}
$commentType = $this->getCommentType($tokens[$index]->getContent());
$indices = [$index];
if (self::TYPE_SLASH_ASTERISK === $commentType) {
return $indices;
}
$count = \count($tokens);
++$index;
for (; $index < $count; ++$index) {
if ($tokens[$index]->isComment()) {
if ($commentType === $this->getCommentType($tokens[$index]->getContent())) {
$indices[] = $index;
continue;
}
break;
}
if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) {
break;
}
}
return $indices;
}
private function isStructuralElement(Token $token)
{
static $skip = [
T_PRIVATE,
T_PROTECTED,
T_PUBLIC,
T_VAR,
T_FUNCTION,
T_ABSTRACT,
T_CONST,
T_NAMESPACE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_INCLUDE,
T_INCLUDE_ONCE,
T_FINAL,
T_STATIC,
];
return $token->isClassy() || $token->isGivenKind($skip);
}
private function isValidControl(Tokens $tokens, Token $docsToken, $controlIndex)
{
static $controlStructures = [
T_FOR,
T_FOREACH,
T_IF,
T_SWITCH,
T_WHILE,
];
if (!$tokens[$controlIndex]->isGivenKind($controlStructures)) {
return false;
}
$index = $tokens->getNextMeaningfulToken($controlIndex);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$docsContent = $docsToken->getContent();
for ($index = $index + 1; $index < $endIndex; ++$index) {
$token = $tokens[$index];
if (
$token->isGivenKind(T_VARIABLE)
&& false !== strpos($docsContent, $token->getContent())
) {
return true;
}
}
return false;
}
private function isValidLanguageConstruct(Tokens $tokens, Token $docsToken, $languageConstructIndex)
{
static $languageStructures = [
T_LIST,
T_PRINT,
T_ECHO,
CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN,
];
if (!$tokens[$languageConstructIndex]->isGivenKind($languageStructures)) {
return false;
}
$endKind = $tokens[$languageConstructIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)
? [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]
: ')';
$endIndex = $tokens->getNextTokenOfKind($languageConstructIndex, [$endKind]);
$docsContent = $docsToken->getContent();
for ($index = $languageConstructIndex + 1; $index < $endIndex; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_VARIABLE) && false !== strpos($docsContent, $token->getContent())) {
return true;
}
}
return false;
}
private function isValidVariable(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_VARIABLE)) {
return false;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
return $tokens[$nextIndex]->equals('=');
}
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());
}
return $lineCount;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Tokens;
final class GotoLabelAnalyzer
{
public 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]]);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class ReferenceAnalyzer
{
public function isReference(Tokens $tokens, $index)
{
if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) {
return true;
}
if (!$tokens[$index]->equals('&')) {
return false;
}
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->equalsAny(['=', [T_AS], [T_CALLABLE], [T_DOUBLE_ARROW], [CT::T_ARRAY_TYPEHINT]])) {
return true;
}
if ($tokens[$index]->isGivenKind(T_STRING)) {
$index = $tokens->getPrevMeaningfulToken($index);
}
return $tokens[$index]->equalsAny(['(', ',', [T_NS_SEPARATOR], [CT::T_NULLABLE_TYPE]]);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class BlocksAnalyzer
{
public function isBlock(Tokens $tokens, $openIndex, $closeIndex)
{
if (null === $openIndex || null === $closeIndex) {
return false;
}
if (!$tokens->offsetExists($openIndex)) {
return false;
}
if (!$tokens->offsetExists($closeIndex)) {
return false;
}
$blockType = $this->getBlockType($tokens[$openIndex]);
if (null === $blockType) {
return false;
}
return $closeIndex === $tokens->findBlockEnd($blockType, $openIndex);
}
private function getBlockType(Token $token)
{
foreach (Tokens::getBlockEdgeDefinitions() as $blockType => $definition) {
if ($token->equals($definition['start'])) {
return $blockType;
}
}
return null;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Tokens;
final class NamespacesAnalyzer
{
public function getDeclarations(Tokens $tokens)
{
$namespaces = [];
for ($index = 1, $count = \count($tokens); $index < $count; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_NAMESPACE)) {
continue;
}
$declarationEndIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
$namespace = trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1));
$declarationParts = explode('\\', $namespace);
$shortName = end($declarationParts);
if ($tokens[$declarationEndIndex]->equals('{')) {
$scopeEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $declarationEndIndex);
} else {
$scopeEndIndex = $tokens->getNextTokenOfKind($declarationEndIndex, [[T_NAMESPACE]]);
if (null === $scopeEndIndex) {
$scopeEndIndex = \count($tokens);
}
--$scopeEndIndex;
}
$namespaces[] = new NamespaceAnalysis(
$namespace,
$shortName,
$index,
$declarationEndIndex,
$index,
$scopeEndIndex
);
$index = $scopeEndIndex;
}
if (0 === \count($namespaces)) {
$namespaces[] = new NamespaceAnalysis('', '', 0, 0, 0, \count($tokens) - 1);
}
return $namespaces;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Tokens;
final class WhitespacesAnalyzer
{
public static 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);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class ClassyAnalyzer
{
public function isClassyInvocation(Tokens $tokens, $index)
{
$token = $tokens[$index];
if (!$token->isGivenKind(T_STRING)) {
throw new \LogicException(sprintf('No T_STRING at given index %d, got "%s".', $index, $tokens[$index]->getName()));
}
if (\in_array(strtolower($token->getContent()), ['bool', 'float', 'int', 'iterable', 'object', 'parent', 'self', 'string', 'void', 'null', 'false'], true)) {
return false;
}
$next = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$next];
if ($nextToken->isGivenKind(T_NS_SEPARATOR)) {
return false;
}
if ($nextToken->isGivenKind([T_DOUBLE_COLON, T_ELLIPSIS, CT::T_TYPE_ALTERNATION, T_VARIABLE])) {
return true;
}
$prev = $tokens->getPrevMeaningfulToken($index);
while ($tokens[$prev]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_NS_SEPARATOR, T_STRING])) {
$prev = $tokens->getPrevMeaningfulToken($prev);
}
$prevToken = $tokens[$prev];
if ($prevToken->isGivenKind([T_EXTENDS, T_INSTANCEOF, T_INSTEADOF, T_IMPLEMENTS, T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_COLON, CT::T_USE_TRAIT])) {
return true;
}
if ($nextToken->equals('&') && $tokens[$tokens->getNextMeaningfulToken($next)]->isGivenKind(T_VARIABLE)) {
$checkIndex = $tokens->getPrevTokenOfKind($prev + 1, [';', '{', '}', [T_FUNCTION], [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]]);
return $tokens[$checkIndex]->isGivenKind(T_FUNCTION);
}
if (!$prevToken->equals(',')) {
return false;
}
do {
$prev = $tokens->getPrevMeaningfulToken($prev);
} while ($tokens[$prev]->equalsAny([',', [T_NS_SEPARATOR], [T_STRING], [CT::T_NAMESPACE_OPERATOR]]));
return $tokens[$prev]->isGivenKind([T_IMPLEMENTS, CT::T_USE_TRAIT]);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class NamespaceUsesAnalyzer
{
public function getDeclarationsFromTokens(Tokens $tokens)
{
$tokenAnalyzer = new TokensAnalyzer($tokens);
$useIndexes = $tokenAnalyzer->getImportUseIndexes();
return $this->getDeclarations($tokens, $useIndexes);
}
private function getDeclarations(Tokens $tokens, array $useIndexes)
{
$uses = [];
foreach ($useIndexes as $index) {
$endIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]);
$analysis = $this->parseDeclaration($tokens, $index, $endIndex);
if ($analysis) {
$uses[] = $analysis;
}
}
return $uses;
}
private function parseDeclaration(Tokens $tokens, $startIndex, $endIndex)
{
$fullName = $shortName = '';
$aliased = false;
$type = NamespaceUseAnalysis::TYPE_CLASS;
for ($i = $startIndex; $i <= $endIndex; ++$i) {
$token = $tokens[$i];
if ($token->equals(',') || $token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) {
return null;
}
if ($token->isGivenKind(CT::T_FUNCTION_IMPORT)) {
$type = NamespaceUseAnalysis::TYPE_FUNCTION;
} elseif ($token->isGivenKind(CT::T_CONST_IMPORT)) {
$type = NamespaceUseAnalysis::TYPE_CONSTANT;
}
if ($token->isWhitespace() || $token->isComment() || $token->isGivenKind(T_USE)) {
continue;
}
if ($token->isGivenKind(T_STRING)) {
$shortName = $token->getContent();
if (!$aliased) {
$fullName .= $shortName;
}
} elseif ($token->isGivenKind(T_NS_SEPARATOR)) {
$fullName .= $token->getContent();
} elseif ($token->isGivenKind(T_AS)) {
$aliased = true;
}
}
return new NamespaceUseAnalysis(
trim($fullName),
$shortName,
$aliased,
$startIndex,
$endIndex,
$type
);
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis;
use PhpCsFixer\Tokenizer\Tokens;
final class SwitchAnalyzer
{
public function getSwitchAnalysis(Tokens $tokens, $switchIndex)
{
if (!$tokens[$switchIndex]->isGivenKind(T_SWITCH)) {
throw new \InvalidArgumentException(sprintf('Index %d is not "switch".', $switchIndex));
}
$casesStartIndex = $this->getCasesStart($tokens, $switchIndex);
$casesEndIndex = $this->getCasesEnd($tokens, $casesStartIndex);
$cases = [];
$index = $casesStartIndex;
while ($index < $casesEndIndex) {
$index = $this->getNextSameLevelToken($tokens, $index);
if (!$tokens[$index]->isGivenKind([T_CASE, T_DEFAULT])) {
continue;
}
$caseAnalysis = $this->getCaseAnalysis($tokens, $index);
$cases[] = $caseAnalysis;
}
return new SwitchAnalysis($casesStartIndex, $casesEndIndex, $cases);
}
private function getCasesStart(Tokens $tokens, $switchIndex)
{
$parenthesisStartIndex = $tokens->getNextMeaningfulToken($switchIndex);
$parenthesisEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $parenthesisStartIndex);
$casesStartIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex);
\assert(\is_int($casesStartIndex));
return $casesStartIndex;
}
private function getCasesEnd(Tokens $tokens, $casesStartIndex)
{
if ($tokens[$casesStartIndex]->equals('{')) {
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $casesStartIndex);
}
$index = $casesStartIndex;
while ($index < $tokens->count()) {
$index = $this->getNextSameLevelToken($tokens, $index);
if ($tokens[$index]->isGivenKind(T_ENDSWITCH)) {
break;
}
}
$afterEndswitchIndex = $tokens->getNextMeaningfulToken($index);
$afterEndswitchToken = $tokens[$afterEndswitchIndex];
return $afterEndswitchToken->equalsAny([';', [T_CLOSE_TAG]]) ? $afterEndswitchIndex : $index;
}
private function getCaseAnalysis(Tokens $tokens, $index)
{
while ($index < $tokens->count()) {
$index = $this->getNextSameLevelToken($tokens, $index);
if ($tokens[$index]->equalsAny([':', ';'])) {
break;
}
}
return new CaseAnalysis($index);
}
private function getNextSameLevelToken(Tokens $tokens, $index)
{
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(T_SWITCH)) {
return (new self())->getSwitchAnalysis($tokens, $index)->getCasesEnd();
}
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType && $blockType['isStart']) {
return $tokens->findBlockEnd($blockType['type'], $index) + 1;
}
return $index;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
interface StartEndTokenAwareAnalysis
{
public function getStartIndex();
public function getEndIndex();
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class NamespaceUseAnalysis implements StartEndTokenAwareAnalysis
{
const TYPE_CLASS = 1;
const TYPE_FUNCTION = 2;
const TYPE_CONSTANT = 3;
private $fullName;
private $shortName;
private $isAliased;
private $startIndex;
private $endIndex;
private $type;
public function __construct($fullName, $shortName, $isAliased, $startIndex, $endIndex, $type)
{
$this->fullName = $fullName;
$this->shortName = $shortName;
$this->isAliased = $isAliased;
$this->startIndex = $startIndex;
$this->endIndex = $endIndex;
$this->type = $type;
}
public function getFullName()
{
return $this->fullName;
}
public function getShortName()
{
return $this->shortName;
}
public function isAliased()
{
return $this->isAliased;
}
public function getStartIndex()
{
return $this->startIndex;
}
public function getEndIndex()
{
return $this->endIndex;
}
public function isClass()
{
return self::TYPE_CLASS === $this->type;
}
public function isFunction()
{
return self::TYPE_FUNCTION === $this->type;
}
public function isConstant()
{
return self::TYPE_CONSTANT === $this->type;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class SwitchAnalysis
{
private $casesStart;
private $casesEnd;
private $cases = [];
public function __construct($casesStart, $casesEnd, array $cases)
{
$this->casesStart = $casesStart;
$this->casesEnd = $casesEnd;
$this->cases = $cases;
}
public function getCasesStart()
{
return $this->casesStart;
}
public function getCasesEnd()
{
return $this->casesEnd;
}
public function getCases()
{
return $this->cases;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class ArgumentAnalysis
{
private $default;
private $name;
private $nameIndex;
private $typeAnalysis;
public function __construct($name, $nameIndex, $default, TypeAnalysis $typeAnalysis = null)
{
$this->name = $name;
$this->nameIndex = $nameIndex;
$this->default = $default ?: null;
$this->typeAnalysis = $typeAnalysis ?: null;
}
public function getDefault()
{
return $this->default;
}
public function hasDefault()
{
return null !== $this->default;
}
public function getName()
{
return $this->name;
}
public function getNameIndex()
{
return $this->nameIndex;
}
public function getTypeAnalysis()
{
return $this->typeAnalysis;
}
public function hasTypeAnalysis()
{
return null !== $this->typeAnalysis;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class NamespaceAnalysis implements StartEndTokenAwareAnalysis
{
private $fullName;
private $shortName;
private $startIndex;
private $endIndex;
private $scopeStartIndex;
private $scopeEndIndex;
public function __construct($fullName, $shortName, $startIndex, $endIndex, $scopeStartIndex, $scopeEndIndex)
{
$this->fullName = $fullName;
$this->shortName = $shortName;
$this->startIndex = $startIndex;
$this->endIndex = $endIndex;
$this->scopeStartIndex = $scopeStartIndex;
$this->scopeEndIndex = $scopeEndIndex;
}
public function getFullName()
{
return $this->fullName;
}
public function getShortName()
{
return $this->shortName;
}
public function getStartIndex()
{
return $this->startIndex;
}
public function getEndIndex()
{
return $this->endIndex;
}
public function getScopeStartIndex()
{
return $this->scopeStartIndex;
}
public function getScopeEndIndex()
{
return $this->scopeEndIndex;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class TypeAnalysis implements StartEndTokenAwareAnalysis
{
private static $reservedTypes = [
'array',
'bool',
'callable',
'int',
'iterable',
'float',
'mixed',
'numeric',
'object',
'resource',
'self',
'string',
'void',
];
private $name;
private $startIndex;
private $endIndex;
private $nullable;
public function __construct($name, $startIndex, $endIndex)
{
$this->name = $name;
$this->nullable = false;
if (0 === strpos($name, '?')) {
$this->name = substr($name, 1);
$this->nullable = true;
}
$this->startIndex = $startIndex;
$this->endIndex = $endIndex;
}
public function getName()
{
return $this->name;
}
public function getStartIndex()
{
return $this->startIndex;
}
public function getEndIndex()
{
return $this->endIndex;
}
public function isReservedType()
{
return \in_array($this->name, self::$reservedTypes, true);
}
public function isNullable()
{
return $this->nullable;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer\Analysis;
final class CaseAnalysis
{
private $colonIndex;
public function __construct($colonIndex)
{
$this->colonIndex = $colonIndex;
}
public function getColonIndex()
{
return $this->colonIndex;
}
}
<?php
namespace PhpCsFixer\Tokenizer\Analyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class FunctionsAnalyzer
{
private $functionsAnalysis = ['tokens' => '', 'imports' => [], 'declarations' => []];
public function isGlobalFunctionCall(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_STRING)) {
return false;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$nextIndex]->equals('(')) {
return false;
}
$previousIsNamespaceSeparator = false;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) {
$previousIsNamespaceSeparator = true;
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
}
if ($tokens[$prevIndex]->isGivenKind([T_DOUBLE_COLON, T_FUNCTION, CT::T_NAMESPACE_OPERATOR, T_NEW, T_OBJECT_OPERATOR, CT::T_RETURN_REF, T_STRING])) {
return false;
}
if ($previousIsNamespaceSeparator) {
return true;
}
if ($tokens->isChanged() || $tokens->getCodeHash() !== $this->functionsAnalysis['tokens']) {
$this->buildFunctionsAnalysis($tokens);
}
$namespaceAnalyzer = new NamespacesAnalyzer();
$declarations = $namespaceAnalyzer->getDeclarations($tokens);
$scopeStartIndex = 0;
$scopeEndIndex = \count($tokens) - 1;
$inGlobalNamespace = false;
foreach ($declarations as $declaration) {
$scopeStartIndex = $declaration->getScopeStartIndex();
$scopeEndIndex = $declaration->getScopeEndIndex();
if ($index >= $scopeStartIndex && $index <= $scopeEndIndex) {
$inGlobalNamespace = '' === $declaration->getFullName();
break;
}
}
$call = strtolower($tokens[$index]->getContent());
if (!$inGlobalNamespace) {
foreach ($this->functionsAnalysis['declarations'] as $functionNameIndex) {
if ($functionNameIndex < $scopeStartIndex || $functionNameIndex > $scopeEndIndex) {
continue;
}
if (strtolower($tokens[$functionNameIndex]->getContent()) === $call) {
return false;
}
}
}
foreach ($this->functionsAnalysis['imports'] as $functionUse) {
if ($functionUse->getStartIndex() < $scopeStartIndex || $functionUse->getEndIndex() > $scopeEndIndex) {
continue;
}
if ($call !== strtolower($functionUse->getShortName())) {
continue;
}
return $functionUse->getShortName() === ltrim($functionUse->getFullName(), '\\');
}
return true;
}
public function getFunctionArguments(Tokens $tokens, $methodIndex)
{
$argumentsStart = $tokens->getNextTokenOfKind($methodIndex, ['(']);
$argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart);
$argumentAnalyzer = new ArgumentsAnalyzer();
$arguments = [];
foreach ($argumentAnalyzer->getArguments($tokens, $argumentsStart, $argumentsEnd) as $start => $end) {
$argumentInfo = $argumentAnalyzer->getArgumentInfo($tokens, $start, $end);
$arguments[$argumentInfo->getName()] = $argumentInfo;
}
return $arguments;
}
public function getFunctionReturnType(Tokens $tokens, $methodIndex)
{
$argumentsStart = $tokens->getNextTokenOfKind($methodIndex, ['(']);
$argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart);
$typeColonIndex = $tokens->getNextMeaningfulToken($argumentsEnd);
if (!$tokens[$typeColonIndex]->isGivenKind(CT::T_TYPE_COLON)) {
return null;
}
$type = '';
$typeStartIndex = $tokens->getNextMeaningfulToken($typeColonIndex);
$typeEndIndex = $typeStartIndex;
$functionBodyStart = $tokens->getNextTokenOfKind($typeColonIndex, ['{', ';', [T_DOUBLE_ARROW]]);
for ($i = $typeStartIndex; $i < $functionBodyStart; ++$i) {
if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
continue;
}
$type .= $tokens[$i]->getContent();
$typeEndIndex = $i;
}
return new TypeAnalysis($type, $typeStartIndex, $typeEndIndex);
}
public function isTheSameClassCall(Tokens $tokens, $index)
{
if (!$tokens->offsetExists($index)) {
return false;
}
$operatorIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens->offsetExists($operatorIndex)) {
return false;
}
$referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex);
if (!$tokens->offsetExists($referenceIndex)) {
return false;
}
return $tokens[$operatorIndex]->equals([T_OBJECT_OPERATOR, '->']) && $tokens[$referenceIndex]->equals([T_VARIABLE, '$this'], false)
|| $tokens[$operatorIndex]->equals([T_DOUBLE_COLON, '::']) && $tokens[$referenceIndex]->equals([T_STRING, 'self'], false)
|| $tokens[$operatorIndex]->equals([T_DOUBLE_COLON, '::']) && $tokens[$referenceIndex]->equals([T_STATIC, 'static'], false);
}
private function buildFunctionsAnalysis(Tokens $tokens)
{
$this->functionsAnalysis = [
'tokens' => $tokens->getCodeHash(),
'imports' => [],
'declarations' => [],
];
if ($tokens->isTokenKindFound(T_FUNCTION)) {
$end = \count($tokens);
for ($i = 0; $i < $end; ++$i) {
if ($tokens[$i]->isGivenKind(Token::getClassyTokenKinds())) {
$i = $tokens->getNextTokenOfKind($i, ['(', '{']);
if ($tokens[$i]->equals('(')) {
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i);
$i = $tokens->getNextTokenOfKind($i, ['{']);
}
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
continue;
}
if (!$tokens[$i]->isGivenKind(T_FUNCTION)) {
continue;
}
$i = $tokens->getNextMeaningfulToken($i);
if ($tokens[$i]->isGivenKind(CT::T_RETURN_REF)) {
$i = $tokens->getNextMeaningfulToken($i);
}
if (!$tokens[$i]->isGivenKind(T_STRING)) {
continue;
}
$this->functionsAnalysis['declarations'][] = $i;
}
}
$namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
if ($tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) {
$declarations = $namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens);
foreach ($declarations as $declaration) {
if ($declaration->isFunction()) {
$this->functionsAnalysis['imports'][] = $declaration;
}
}
}
}
}
<?php
namespace PhpCsFixer\Tokenizer;
use PhpCsFixer\Utils;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
final class Transformers
{
private $items = [];
private function __construct()
{
$this->registerBuiltInTransformers();
usort($this->items, static function (TransformerInterface $a, TransformerInterface $b) {
return Utils::cmpInt($b->getPriority(), $a->getPriority());
});
}
public static function create()
{
static $instance = null;
if (!$instance) {
$instance = new self();
}
return $instance;
}
public function transform(Tokens $tokens)
{
foreach ($this->items as $transformer) {
foreach ($tokens as $index => $token) {
$transformer->process($tokens, $token, $index);
}
}
}
private function registerTransformer(TransformerInterface $transformer)
{
if (\PHP_VERSION_ID >= $transformer->getRequiredPhpVersionId()) {
$this->items[] = $transformer;
}
}
private function registerBuiltInTransformers()
{
static $registered = false;
if ($registered) {
return;
}
$registered = true;
foreach ($this->findBuiltInTransformers() as $transformer) {
$this->registerTransformer($transformer);
}
}
private function findBuiltInTransformers()
{
foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) {
$relativeNamespace = $file->getRelativePath();
$class = __NAMESPACE__.'\\Transformer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
yield new $class();
}
}
}
<?php
namespace PhpCsFixer\Tokenizer;
use PhpCsFixer\Preg;
use PhpCsFixer\Utils;
/**
@extends
*/
class Tokens extends \SplFixedArray
{
const BLOCK_TYPE_PARENTHESIS_BRACE = 1;
const BLOCK_TYPE_CURLY_BRACE = 2;
const BLOCK_TYPE_INDEX_SQUARE_BRACE = 3;
const BLOCK_TYPE_ARRAY_SQUARE_BRACE = 4;
const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5;
const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6;
const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = 7;
const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8;
const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = 9;
const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = 10;
const BLOCK_TYPE_ATTRIBUTE = 11;
private static $cache = [];
private $blockEndCache = [];
private $codeHash;
private $changed = false;
private $foundTokenKinds = [];
private static $isLegacyMode = false;
public function __clone()
{
foreach ($this as $key => $val) {
$this[$key] = clone $val;
}
}
public static function isLegacyMode()
{
return self::$isLegacyMode;
}
public static function setLegacyMode($isLegacy)
{
if (getenv('PHP_CS_FIXER_FUTURE_MODE') && $isLegacy) {
throw new \RuntimeException('Cannot enable `legacy mode` when using `future mode`. This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set.');
}
self::$isLegacyMode = $isLegacy;
}
public static function clearCache($key = null)
{
if (null === $key) {
self::$cache = [];
return;
}
if (self::hasCache($key)) {
unset(self::$cache[$key]);
}
}
public static function detectBlockType(Token $token)
{
foreach (self::getBlockEdgeDefinitions() as $type => $definition) {
if ($token->equals($definition['start'])) {
return ['type' => $type, 'isStart' => true];
}
if ($token->equals($definition['end'])) {
return ['type' => $type, 'isStart' => false];
}
}
return null;
}
public static function fromArray($array, $saveIndexes = null)
{
$tokens = new self(\count($array));
if (null === $saveIndexes || $saveIndexes) {
foreach ($array as $key => $val) {
$tokens[$key] = $val;
}
} else {
$index = 0;
foreach ($array as $val) {
$tokens[$index++] = $val;
}
}
$tokens->generateCode();
$tokens->clearChanged();
return $tokens;
}
public static function fromCode($code)
{
$codeHash = self::calculateCodeHash($code);
if (self::hasCache($codeHash)) {
$tokens = self::getCache($codeHash);
$tokens->generateCode();
if ($codeHash === $tokens->codeHash) {
$tokens->clearEmptyTokens();
$tokens->clearChanged();
return $tokens;
}
}
$tokens = new self();
$tokens->setCode($code);
$tokens->clearChanged();
return $tokens;
}
public static function getBlockEdgeDefinitions()
{
$definitions = [
self::BLOCK_TYPE_CURLY_BRACE => [
'start' => '{',
'end' => '}',
],
self::BLOCK_TYPE_PARENTHESIS_BRACE => [
'start' => '(',
'end' => ')',
],
self::BLOCK_TYPE_INDEX_SQUARE_BRACE => [
'start' => '[',
'end' => ']',
],
self::BLOCK_TYPE_ARRAY_SQUARE_BRACE => [
'start' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, '['],
'end' => [CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']'],
],
self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => [
'start' => [CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'],
'end' => [CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}'],
],
self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => [
'start' => [CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'],
'end' => [CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}'],
],
self::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE => [
'start' => [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{'],
'end' => [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}'],
],
self::BLOCK_TYPE_GROUP_IMPORT_BRACE => [
'start' => [CT::T_GROUP_IMPORT_BRACE_OPEN, '{'],
'end' => [CT::T_GROUP_IMPORT_BRACE_CLOSE, '}'],
],
self::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE => [
'start' => [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '['],
'end' => [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']'],
],
self::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION => [
'start' => [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('],
'end' => [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')'],
],
];
if (\defined('T_ATTRIBUTE')) {
$definitions[self::BLOCK_TYPE_ATTRIBUTE] = [
'start' => [T_ATTRIBUTE, '#['],
'end' => [CT::T_ATTRIBUTE_CLOSE, ']'],
];
}
return $definitions;
}
public function setSize($size)
{
if ($this->getSize() !== $size) {
$this->changed = true;
parent::setSize($size);
}
}
public function offsetUnset($index)
{
$this->changed = true;
$this->unregisterFoundToken($this[$index]);
parent::offsetUnset($index);
}
public function offsetSet($index, $newval)
{
$this->blockEndCache = [];
if (!isset($this[$index]) || !$this[$index]->equals($newval)) {
$this->changed = true;
if (isset($this[$index])) {
$this->unregisterFoundToken($this[$index]);
}
$this->registerFoundToken($newval);
}
parent::offsetSet($index, $newval);
}
public function clearChanged()
{
$this->changed = false;
if (self::isLegacyMode()) {
foreach ($this as $token) {
$token->clearChanged();
}
}
}
public function clearEmptyTokens()
{
$limit = $this->count();
$index = 0;
for (; $index < $limit; ++$index) {
if ($this->isEmptyAt($index)) {
break;
}
}
if ($limit === $index) {
return;
}
for ($count = $index; $index < $limit; ++$index) {
if (!$this->isEmptyAt($index)) {
$this[$count++] = $this[$index];
}
}
$this->setSize($count);
}
public function ensureWhitespaceAtIndex($index, $indexOffset, $whitespace)
{
$removeLastCommentLine = static function (self $tokens, $index, $indexOffset, $whitespace) {
$token = $tokens[$index];
if (1 === $indexOffset && $token->isGivenKind(T_OPEN_TAG)) {
if (0 === strpos($whitespace, "\r\n")) {
$tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent())."\r\n"]);
return \strlen($whitespace) > 2
? substr($whitespace, 2)
: ''
;
}
$tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]);
return \strlen($whitespace) > 1
? substr($whitespace, 1)
: ''
;
}
return $whitespace;
};
if ($this[$index]->isWhitespace()) {
$whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace);
if ('' === $whitespace) {
$this->clearAt($index);
} else {
$this[$index] = new Token([T_WHITESPACE, $whitespace]);
}
return false;
}
$whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace);
if ('' === $whitespace) {
return false;
}
$this->insertAt(
$index + $indexOffset,
[new Token([T_WHITESPACE, $whitespace])]
);
return true;
}
public function findBlockEnd($type, $searchIndex, $findEnd = true)
{
if (3 === \func_num_args()) {
if ($findEnd) {
@trigger_error('Argument #3 of Tokens::findBlockEnd is deprecated and will be removed in 3.0, you can safely drop the argument.', E_USER_DEPRECATED);
} else {
@trigger_error('Argument #3 of Tokens::findBlockEnd is deprecated and will be removed in 3.0, use Tokens::findBlockStart instead.', E_USER_DEPRECATED);
}
}
return $this->findOppositeBlockEdge($type, $searchIndex, $findEnd);
}
public function findBlockStart($type, $searchIndex)
{
return $this->findOppositeBlockEdge($type, $searchIndex, false);
}
public function findGivenKind($possibleKind, $start = 0, $end = null)
{
if (null === $end) {
$end = $this->count();
}
$elements = [];
$possibleKinds = (array) $possibleKind;
foreach ($possibleKinds as $kind) {
$elements[$kind] = [];
}
if (!self::isLegacyMode()) {
$possibleKinds = array_filter($possibleKinds, function ($kind) {
return $this->isTokenKindFound($kind);
});
}
if (\count($possibleKinds)) {
for ($i = $start; $i < $end; ++$i) {
$token = $this[$i];
if ($token->isGivenKind($possibleKinds)) {
$elements[$token->getId()][$i] = $token;
}
}
}
return \is_array($possibleKind) ? $elements : $elements[$possibleKind];
}
public function generateCode()
{
$code = $this->generatePartialCode(0, \count($this) - 1);
$this->changeCodeHash(self::calculateCodeHash($code));
return $code;
}
public function generatePartialCode($start, $end)
{
$code = '';
for ($i = $start; $i <= $end; ++$i) {
$code .= $this[$i]->getContent();
}
return $code;
}
public function getCodeHash()
{
return $this->codeHash;
}
public function getNextNonWhitespace($index, $whitespaces = null)
{
return $this->getNonWhitespaceSibling($index, 1, $whitespaces);
}
public function getNextTokenOfKind($index, array $tokens = [], $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive);
}
public function getNonWhitespaceSibling($index, $direction, $whitespaces = null)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if (!$this[$index]->isWhitespace($whitespaces)) {
return $index;
}
}
}
public function getPrevNonWhitespace($index, $whitespaces = null)
{
return $this->getNonWhitespaceSibling($index, -1, $whitespaces);
}
public function getPrevTokenOfKind($index, array $tokens = [], $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive);
}
public function getTokenOfKindSibling($index, $direction, array $tokens = [], $caseSensitive = true)
{
if (!self::isLegacyMode()) {
$tokens = array_filter($tokens, function ($token) {
return $this->isTokenKindFound($this->extractTokenKind($token));
});
}
if (!\count($tokens)) {
return null;
}
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if ($this[$index]->equalsAny($tokens, $caseSensitive)) {
return $index;
}
}
}
public function getTokenNotOfKindSibling($index, $direction, array $tokens = [])
{
return $this->getTokenNotOfKind(
$index,
$direction,
function ($a) use ($tokens) {
return $this[$a]->equalsAny($tokens);
}
);
}
public function getTokenNotOfKindsSibling($index, $direction, array $kinds = [])
{
return $this->getTokenNotOfKind(
$index,
$direction,
function ($index) use ($kinds) {
return $this[$index]->isGivenKind($kinds);
}
);
}
public function getMeaningfulTokenSibling($index, $direction)
{
return $this->getTokenNotOfKindsSibling(
$index,
$direction,
[T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]
);
}
public function getNonEmptySibling($index, $direction)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if (!$this->isEmptyAt($index)) {
return $index;
}
}
}
public function getNextMeaningfulToken($index)
{
return $this->getMeaningfulTokenSibling($index, 1);
}
public function getPrevMeaningfulToken($index)
{
return $this->getMeaningfulTokenSibling($index, -1);
}
public function findSequence(array $sequence, $start = 0, $end = null, $caseSensitive = true)
{
$sequenceCount = \count($sequence);
if (0 === $sequenceCount) {
throw new \InvalidArgumentException('Invalid sequence.');
}
$end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1);
if ($start + $sequenceCount - 1 > $end) {
return null;
}
$nonMeaningFullKind = [T_COMMENT, T_DOC_COMMENT, T_WHITESPACE];
foreach ($sequence as $key => $token) {
if (!$token instanceof Token) {
if (\is_array($token) && !isset($token[1])) {
$token[1] = 'DUMMY';
}
$token = new Token($token);
}
if ($token->isGivenKind($nonMeaningFullKind)) {
throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: "%s".', $key));
}
if ('' === $token->getContent()) {
throw new \InvalidArgumentException(sprintf('Non-meaningful (empty) token at position: "%s".', $key));
}
}
if (!self::isLegacyMode()) {
foreach ($sequence as $token) {
if (!$this->isTokenKindFound($this->extractTokenKind($token))) {
return null;
}
}
}
$key = key($sequence);
$firstCs = Token::isKeyCaseSensitive($caseSensitive, $key);
$firstToken = $sequence[$key];
unset($sequence[$key]);
$index = $start - 1;
while (null !== $index && $index <= $end) {
$index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs);
if (null === $index || $index > $end) {
return null;
}
$result = [$index => $this[$index]];
$currIdx = $index;
foreach ($sequence as $key => $token) {
$currIdx = $this->getNextMeaningfulToken($currIdx);
if (null === $currIdx || $currIdx > $end) {
return null;
}
if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) {
continue 2;
}
$result[$currIdx] = $this[$currIdx];
}
if (\count($sequence) < \count($result)) {
return $result;
}
}
return null;
}
public function insertAt($index, $items)
{
$items = \is_array($items) || $items instanceof self ? $items : [$items];
$this->insertSlices([$index => $items]);
}
public function insertSlices(array $slices)
{
$itemsCount = 0;
foreach ($slices as $slice) {
$slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice];
$itemsCount += \count($slice);
}
if (0 === $itemsCount) {
return;
}
$oldSize = \count($this);
$this->changed = true;
$this->blockEndCache = [];
$this->setSize($oldSize + $itemsCount);
krsort($slices);
$insertBound = $oldSize - 1;
foreach ($slices as $index => $slice) {
$slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice];
$sliceCount = \count($slice);
for ($i = $insertBound; $i >= $index; --$i) {
$oldItem = parent::offsetExists($i) ? parent::offsetGet($i) : new Token('');
parent::offsetSet($i + $itemsCount, $oldItem);
}
$insertBound = $index - $sliceCount;
$itemsCount -= $sliceCount;
foreach ($slice as $indexItem => $item) {
if ('' === $item->getContent()) {
throw new \InvalidArgumentException('Must not add empty token to collection.');
}
$this->registerFoundToken($item);
$newOffset = $index + $itemsCount + $indexItem;
parent::offsetSet($newOffset, $item);
}
}
}
public function isChanged()
{
if ($this->changed) {
return true;
}
if (self::isLegacyMode()) {
foreach ($this as $token) {
if ($token->isChanged()) {
return true;
}
}
}
return false;
}
public function isEmptyAt($index)
{
$token = $this[$index];
return null === $token->getId() && '' === $token->getContent();
}
public function clearAt($index)
{
$this[$index] = new Token('');
}
public function overrideAt($index, $token)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0, use offsetSet instead.', E_USER_DEPRECATED);
self::$isLegacyMode = true;
$this[$index]->override($token);
$this->registerFoundToken($token);
}
public function overrideRange($indexStart, $indexEnd, $items)
{
$indexToChange = $indexEnd - $indexStart + 1;
$itemsCount = \count($items);
if ($itemsCount > $indexToChange) {
$placeholders = [];
while ($itemsCount > $indexToChange) {
$placeholders[] = new Token('__PLACEHOLDER__');
++$indexToChange;
}
$this->insertAt($indexEnd + 1, $placeholders);
}
foreach ($items as $itemIndex => $item) {
$this[$indexStart + $itemIndex] = $item;
}
if ($itemsCount < $indexToChange) {
$this->clearRange($indexStart + $itemsCount, $indexEnd);
}
}
public function removeLeadingWhitespace($index, $whitespaces = null)
{
$this->removeWhitespaceSafely($index, -1, $whitespaces);
}
public function removeTrailingWhitespace($index, $whitespaces = null)
{
$this->removeWhitespaceSafely($index, 1, $whitespaces);
}
public function setCode($code)
{
if ($code === $this->generateCode()) {
return;
}
$this->setSize(0);
$tokens = \defined('TOKEN_PARSE')
? token_get_all($code, TOKEN_PARSE)
: token_get_all($code);
$this->setSize(\count($tokens));
foreach ($tokens as $index => $token) {
$this[$index] = new Token($token);
}
$transformers = Transformers::create();
$transformers->transform($this);
$this->foundTokenKinds = [];
foreach ($this as $token) {
$this->registerFoundToken($token);
}
if (\PHP_VERSION_ID < 80000) {
$this->rewind();
}
$this->changeCodeHash(self::calculateCodeHash($code));
$this->changed = true;
}
public function toJson()
{
static $options = null;
if (null === $options) {
$options = Utils::calculateBitmask(['JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK']);
}
$output = new \SplFixedArray(\count($this));
foreach ($this as $index => $token) {
$output[$index] = $token->toArray();
}
if (\PHP_VERSION_ID < 80000) {
$this->rewind();
}
return json_encode($output, $options);
}
public function isAllTokenKindsFound(array $tokenKinds)
{
foreach ($tokenKinds as $tokenKind) {
if (empty($this->foundTokenKinds[$tokenKind])) {
return false;
}
}
return true;
}
public function isAnyTokenKindsFound(array $tokenKinds)
{
foreach ($tokenKinds as $tokenKind) {
if (!empty($this->foundTokenKinds[$tokenKind])) {
return true;
}
}
return false;
}
public function isTokenKindFound($tokenKind)
{
return !empty($this->foundTokenKinds[$tokenKind]);
}
public function countTokenKind($tokenKind)
{
if (self::isLegacyMode()) {
throw new \RuntimeException(sprintf('"%s" is not available in legacy mode.', __METHOD__));
}
return isset($this->foundTokenKinds[$tokenKind]) ? $this->foundTokenKinds[$tokenKind] : 0;
}
public function clearRange($indexStart, $indexEnd)
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$this->clearAt($i);
}
}
public function isMonolithicPhp()
{
$size = $this->count();
if (0 === $size) {
return false;
}
if (self::isLegacyMode()) {
if ($this[0]->isGivenKind(T_INLINE_HTML) || $this[$size - 1]->isGivenKind(T_INLINE_HTML)) {
return false;
}
for ($index = 1; $index < $size; ++$index) {
if ($this[$index]->isGivenKind([T_INLINE_HTML, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO])) {
return false;
}
}
return true;
}
if ($this->isTokenKindFound(T_INLINE_HTML)) {
return false;
}
return 1 >= ($this->countTokenKind(T_OPEN_TAG) + $this->countTokenKind(T_OPEN_TAG_WITH_ECHO));
}
public function isPartialCodeMultiline($start, $end)
{
for ($i = $start; $i <= $end; ++$i) {
if (false !== strpos($this[$i]->getContent(), "\n")) {
return true;
}
}
return false;
}
public function hasAlternativeSyntax()
{
return $this->isAnyTokenKindsFound([
T_ENDDECLARE,
T_ENDFOR,
T_ENDFOREACH,
T_ENDIF,
T_ENDSWITCH,
T_ENDWHILE,
]);
}
public function clearTokenAndMergeSurroundingWhitespace($index)
{
$count = \count($this);
$this->clearAt($index);
if ($index === $count - 1) {
return;
}
$nextIndex = $this->getNonEmptySibling($index, 1);
if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) {
return;
}
$prevIndex = $this->getNonEmptySibling($index, -1);
if ($this[$prevIndex]->isWhitespace()) {
$this[$prevIndex] = new Token([T_WHITESPACE, $this[$prevIndex]->getContent().$this[$nextIndex]->getContent()]);
} elseif ($this->isEmptyAt($prevIndex + 1)) {
$this[$prevIndex + 1] = new Token([T_WHITESPACE, $this[$nextIndex]->getContent()]);
}
$this->clearAt($nextIndex);
}
public function current()
{
$this->warnPhp8SplFixerArrayChange(__METHOD__);
return parent::current();
}
public function key()
{
$this->warnPhp8SplFixerArrayChange(__METHOD__);
return parent::key();
}
public function next()
{
$this->warnPhp8SplFixerArrayChange(__METHOD__);
parent::next();
}
public function rewind()
{
$this->warnPhp8SplFixerArrayChange(__METHOD__);
parent::rewind();
}
public function valid()
{
$this->warnPhp8SplFixerArrayChange(__METHOD__);
return parent::valid();
}
private function warnPhp8SplFixerArrayChange($method)
{
if (80000 <= \PHP_VERSION_ID) {
throw new \BadMethodCallException(sprintf('"%s" has been removed on PHP8, use ::getIterator() in place.', $method));
}
}
private function removeWhitespaceSafely($index, $direction, $whitespaces = null)
{
$whitespaceIndex = $this->getNonEmptySibling($index, $direction);
if (isset($this[$whitespaceIndex]) && $this[$whitespaceIndex]->isWhitespace()) {
$newContent = '';
$tokenToCheck = $this[$whitespaceIndex];
if (isset($this[$whitespaceIndex - 1]) && $this[$whitespaceIndex - 1]->isComment() && '/*' !== substr($this[$whitespaceIndex - 1]->getContent(), 0, 2)) {
list($emptyString, $newContent, $whitespacesToCheck) = Preg::split('/^(\R)/', $this[$whitespaceIndex]->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE);
if ('' === $whitespacesToCheck) {
return;
}
$tokenToCheck = new Token([T_WHITESPACE, $whitespacesToCheck]);
}
if (!$tokenToCheck->isWhitespace($whitespaces)) {
return;
}
if ('' === $newContent) {
$this->clearAt($whitespaceIndex);
} else {
$this[$whitespaceIndex] = new Token([T_WHITESPACE, $newContent]);
}
}
}
private function findOppositeBlockEdge($type, $searchIndex, $findEnd)
{
$blockEdgeDefinitions = self::getBlockEdgeDefinitions();
if (!isset($blockEdgeDefinitions[$type])) {
throw new \InvalidArgumentException(sprintf('Invalid param type: "%s".', $type));
}
if (!self::isLegacyMode() && isset($this->blockEndCache[$searchIndex])) {
return $this->blockEndCache[$searchIndex];
}
$startEdge = $blockEdgeDefinitions[$type]['start'];
$endEdge = $blockEdgeDefinitions[$type]['end'];
$startIndex = $searchIndex;
$endIndex = $this->count() - 1;
$indexOffset = 1;
if (!$findEnd) {
list($startEdge, $endEdge) = [$endEdge, $startEdge];
$indexOffset = -1;
$endIndex = 0;
}
if (!$this[$startIndex]->equals($startEdge)) {
throw new \InvalidArgumentException(sprintf('Invalid param $startIndex - not a proper block "%s".', $findEnd ? 'start' : 'end'));
}
$blockLevel = 0;
for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) {
$token = $this[$index];
if ($token->equals($startEdge)) {
++$blockLevel;
continue;
}
if ($token->equals($endEdge)) {
--$blockLevel;
if (0 === $blockLevel) {
break;
}
continue;
}
}
if (!$this[$index]->equals($endEdge)) {
throw new \UnexpectedValueException(sprintf('Missing block "%s".', $findEnd ? 'end' : 'start'));
}
$this->blockEndCache[$startIndex] = $index;
$this->blockEndCache[$index] = $startIndex;
return $index;
}
private static function calculateCodeHash($code)
{
return CodeHasher::calculateCodeHash($code);
}
private static function getCache($key)
{
if (!self::hasCache($key)) {
throw new \OutOfBoundsException(sprintf('Unknown cache key: "%s".', $key));
}
return self::$cache[$key];
}
private static function hasCache($key)
{
return isset(self::$cache[$key]);
}
private static function setCache($key, self $value)
{
self::$cache[$key] = $value;
}
private function changeCodeHash($codeHash)
{
if (null !== $this->codeHash) {
self::clearCache($this->codeHash);
}
$this->codeHash = $codeHash;
self::setCache($this->codeHash, $this);
}
private function registerFoundToken($token)
{
$tokenKind = $token instanceof Token
? ($token->isArray() ? $token->getId() : $token->getContent())
: (\is_array($token) ? $token[0] : $token)
;
if (!isset($this->foundTokenKinds[$tokenKind])) {
$this->foundTokenKinds[$tokenKind] = 0;
}
++$this->foundTokenKinds[$tokenKind];
}
private function unregisterFoundToken($token)
{
$tokenKind = $token instanceof Token
? ($token->isArray() ? $token->getId() : $token->getContent())
: (\is_array($token) ? $token[0] : $token)
;
if (!isset($this->foundTokenKinds[$tokenKind])) {
return;
}
--$this->foundTokenKinds[$tokenKind];
}
private function extractTokenKind($token)
{
return $token instanceof Token
? ($token->isArray() ? $token->getId() : $token->getContent())
: (\is_array($token) ? $token[0] : $token)
;
}
private function getTokenNotOfKind($index, $direction, $filter)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if ($this->isEmptyAt($index) || $filter($index)) {
continue;
}
return $index;
}
}
}
<?php
namespace PhpCsFixer\Tokenizer;
use PhpCsFixer\Utils;
abstract class AbstractTransformer implements TransformerInterface
{
public function getName()
{
$nameParts = explode('\\', static::class);
$name = substr(end($nameParts), 0, -\strlen('Transformer'));
return Utils::camelCaseToUnderscore($name);
}
public function getPriority()
{
return 0;
}
public function getCustomTokens()
{
@trigger_error(sprintf('%s is deprecated and will be removed in 3.0.', __METHOD__), E_USER_DEPRECATED);
return $this->getDeprecatedCustomTokens();
}
abstract protected function getDeprecatedCustomTokens();
}
<?php
namespace PhpCsFixer\Tokenizer;
final class CT
{
const T_ARRAY_INDEX_CURLY_BRACE_CLOSE = 10001;
const T_ARRAY_INDEX_CURLY_BRACE_OPEN = 10002;
const T_ARRAY_SQUARE_BRACE_CLOSE = 10003;
const T_ARRAY_SQUARE_BRACE_OPEN = 10004;
const T_ARRAY_TYPEHINT = 10005;
const T_BRACE_CLASS_INSTANTIATION_CLOSE = 10006;
const T_BRACE_CLASS_INSTANTIATION_OPEN = 10007;
const T_CLASS_CONSTANT = 10008;
const T_CONST_IMPORT = 10009;
const T_CURLY_CLOSE = 10010;
const T_DESTRUCTURING_SQUARE_BRACE_CLOSE = 10011;
const T_DESTRUCTURING_SQUARE_BRACE_OPEN = 10012;
const T_DOLLAR_CLOSE_CURLY_BRACES = 10013;
const T_DYNAMIC_PROP_BRACE_CLOSE = 10014;
const T_DYNAMIC_PROP_BRACE_OPEN = 10015;
const T_DYNAMIC_VAR_BRACE_CLOSE = 10016;
const T_DYNAMIC_VAR_BRACE_OPEN = 10017;
const T_FUNCTION_IMPORT = 10018;
const T_GROUP_IMPORT_BRACE_CLOSE = 10019;
const T_GROUP_IMPORT_BRACE_OPEN = 10020;
const T_NAMESPACE_OPERATOR = 10021;
const T_NULLABLE_TYPE = 10022;
const T_RETURN_REF = 10023;
const T_TYPE_ALTERNATION = 10024;
const T_TYPE_COLON = 10025;
const T_USE_LAMBDA = 10026;
const T_USE_TRAIT = 10027;
const T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC = 10028;
const T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED = 10029;
const T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE = 10030;
const T_ATTRIBUTE_CLOSE = 10031;
const T_NAMED_ARGUMENT_NAME = 10032;
const T_NAMED_ARGUMENT_COLON = 10033;
private function __construct()
{
}
public static function getName($value)
{
if (!self::has($value)) {
throw new \InvalidArgumentException(sprintf('No custom token was found for "%s".', $value));
}
$tokens = self::getMapById();
return 'CT::'.$tokens[$value];
}
public static function has($value)
{
$tokens = self::getMapById();
return isset($tokens[$value]);
}
private static function getMapById()
{
static $constants;
if (null === $constants) {
$reflection = new \ReflectionClass(__CLASS__);
$constants = array_flip($reflection->getConstants());
}
return $constants;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException;
use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException;
use PhpCsFixer\Console\Application;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DefinedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\ExceptionInterface;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
abstract class AbstractFixer implements FixerInterface, DefinedFixerInterface
{
protected $configuration;
protected $whitespacesConfig;
private $configurationDefinition;
public function __construct()
{
if ($this instanceof ConfigurableFixerInterface) {
try {
$this->configure([]);
} catch (RequiredFixerConfigurationException $e) {
}
}
if ($this instanceof WhitespacesAwareFixerInterface) {
$this->whitespacesConfig = $this->getDefaultWhitespacesFixerConfig();
}
}
final public function fix(\SplFileInfo $file, Tokens $tokens)
{
if ($this instanceof ConfigurableFixerInterface && null === $this->configuration) {
throw new RequiredFixerConfigurationException($this->getName(), 'Configuration is required.');
}
if (0 < $tokens->count() && $this->isCandidate($tokens) && $this->supports($file)) {
$this->applyFix($file, $tokens);
}
}
public function isRisky()
{
return false;
}
public function getName()
{
$nameParts = explode('\\', static::class);
$name = substr(end($nameParts), 0, -\strlen('Fixer'));
return Utils::camelCaseToUnderscore($name);
}
public function getPriority()
{
return 0;
}
public function supports(\SplFileInfo $file)
{
return true;
}
public function configure(array $configuration = null)
{
if (!$this instanceof ConfigurationDefinitionFixerInterface) {
throw new \LogicException('Cannot configure using Abstract parent, child not implementing "PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface".');
}
if (null === $configuration) {
$message = 'Passing NULL to set default configuration is deprecated and will not be supported in 3.0, use an empty array 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);
$configuration = [];
}
foreach ($this->getConfigurationDefinition()->getOptions() as $option) {
if (!$option instanceof DeprecatedFixerOption) {
continue;
}
$name = $option->getName();
if (\array_key_exists($name, $configuration)) {
$message = sprintf(
'Option "%s" for rule "%s" is deprecated and will be removed in version %d.0. %s',
$name,
$this->getName(),
Application::getMajorVersion() + 1,
str_replace('`', '"', $option->getDeprecationMessage())
);
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);
}
}
try {
$this->configuration = $this->getConfigurationDefinition()->resolve($configuration);
} catch (MissingOptionsException $exception) {
throw new RequiredFixerConfigurationException(
$this->getName(),
sprintf('Missing required configuration: %s', $exception->getMessage()),
$exception
);
} catch (InvalidOptionsForEnvException $exception) {
throw new InvalidForEnvFixerConfigurationException(
$this->getName(),
sprintf('Invalid configuration for env: %s', $exception->getMessage()),
$exception
);
} catch (ExceptionInterface $exception) {
throw new InvalidFixerConfigurationException(
$this->getName(),
sprintf('Invalid configuration: %s', $exception->getMessage()),
$exception
);
}
}
public function getConfigurationDefinition()
{
if (!$this instanceof ConfigurationDefinitionFixerInterface) {
throw new \LogicException('Cannot get configuration definition using Abstract parent, child not implementing "PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface".');
}
if (null === $this->configurationDefinition) {
$this->configurationDefinition = $this->createConfigurationDefinition();
}
return $this->configurationDefinition;
}
public function setWhitespacesConfig(WhitespacesFixerConfig $config)
{
if (!$this instanceof WhitespacesAwareFixerInterface) {
throw new \LogicException('Cannot run method for class not implementing "PhpCsFixer\Fixer\WhitespacesAwareFixerInterface".');
}
$this->whitespacesConfig = $config;
}
abstract protected function applyFix(\SplFileInfo $file, Tokens $tokens);
protected function createConfigurationDefinition()
{
if (!$this instanceof ConfigurationDefinitionFixerInterface) {
throw new \LogicException('Cannot create configuration definition using Abstract parent, child not implementing "PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface".');
}
throw new \LogicException('Not implemented.');
}
private function getDefaultWhitespacesFixerConfig()
{
static $defaultWhitespacesFixerConfig = null;
if (null === $defaultWhitespacesFixerConfig) {
$defaultWhitespacesFixerConfig = new WhitespacesFixerConfig(' ', "\n");
}
return $defaultWhitespacesFixerConfig;
}
}
<?php
namespace PhpCsFixer;
use PhpCsFixer\Tokenizer\Tokens;
abstract class AbstractPhpdocToTypeDeclarationFixer extends AbstractFixer
{
private static $syntaxValidationCache = [];
final protected function isValidSyntax($code)
{
if (!isset(self::$syntaxValidationCache[$code])) {
try {
Tokens::fromCode($code);
self::$syntaxValidationCache[$code] = true;
} catch (\ParseError $e) {
self::$syntaxValidationCache[$code] = false;
}
}
return self::$syntaxValidationCache[$code];
}
}
<?php
namespace PhpCsFixer;
final class FileReader
{
private static $instance;
private $stdinContent;
public static function createSingleton()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function read($filePath)
{
if ('php://stdin' === $filePath) {
if (null === $this->stdinContent) {
$this->stdinContent = $this->readRaw($filePath);
}
return $this->stdinContent;
}
return $this->readRaw($filePath);
}
private function readRaw($realPath)
{
$content = @file_get_contents($realPath);
if (false === $content) {
$error = error_get_last();
throw new \RuntimeException(sprintf(
'Failed to read content from "%s".%s',
$realPath,
$error ? ' '.$error['message'] : ''
));
}
return $content;
}
}
<?php
namespace PhpCsFixer\RuleSet;
class RuleSet implements RuleSetInterface
{
private $rules;
public function __construct(array $set = [])
{
foreach ($set as $key => $value) {
if (\is_int($key)) {
throw new \InvalidArgumentException(sprintf('Missing value for "%s" rule/set.', $value));
}
}
$this->resolveSet($set);
}
public function hasRule($rule)
{
return \array_key_exists($rule, $this->rules);
}
public function getRuleConfiguration($rule)
{
if (!$this->hasRule($rule)) {
throw new \InvalidArgumentException(sprintf('Rule "%s" is not in the set.', $rule));
}
if (true === $this->rules[$rule]) {
return null;
}
return $this->rules[$rule];
}
public function getRules()
{
return $this->rules;
}
public static function create(array $set = [])
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0, use the constructor.', E_USER_DEPRECATED);
return new self($set);
}
public function getSetDefinitionNames()
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0, use PhpCsFixer\RuleSet\RuleSets::getSetDefinitionNames.', E_USER_DEPRECATED);
return RuleSets::getSetDefinitionNames();
}
private function resolveSet(array $rules)
{
$resolvedRules = [];
foreach ($rules as $name => $value) {
if ('@' === $name[0]) {
if (!\is_bool($value)) {
throw new \UnexpectedValueException(sprintf('Nested rule set "%s" configuration must be a boolean.', $name));
}
$set = $this->resolveSubset($name, $value);
$resolvedRules = array_merge($resolvedRules, $set);
} else {
$resolvedRules[$name] = $value;
}
}
$resolvedRules = array_filter($resolvedRules);
$this->rules = $resolvedRules;
return $this;
}
private function resolveSubset($setName, $setValue)
{
$rules = RuleSets::getSetDefinition($setName)->getRules();
foreach ($rules as $name => $value) {
if ('@' === $name[0]) {
$set = $this->resolveSubset($name, $setValue);
unset($rules[$name]);
$rules = array_merge($rules, $set);
} elseif (!$setValue) {
$rules[$name] = false;
} else {
$rules[$name] = $value;
}
}
return $rules;
}
}
<?php
namespace PhpCsFixer\RuleSet;
interface RuleSetDescriptionInterface
{
public function __construct();
public function getDescription();
public function getName();
public function getRules();
public function isRisky();
}
<?php
namespace PhpCsFixer\RuleSet;
/**
@PSR2
@PSR1
*/
interface RuleSetInterface
{
public function __construct(array $set = []);
public function getRuleConfiguration($rule);
public function getRules();
public function hasRule($rule);
public static function create(array $set = []);
public function getSetDefinitionNames();
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP70MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP56Migration' => true,
'ternary_to_null_coalescing' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit35MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit32Migration:risky' => true,
'php_unit_dedicate_assert' => [
'target' => '3.5',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 3.5 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit84MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit60Migration:risky' => true,
'@PHPUnit75Migration:risky' => true,
'php_unit_expectation' => [
'target' => '8.4',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 7.5 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit54MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit52Migration:risky' => true,
'php_unit_mock' => [
'target' => '5.4',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.4 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit52MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit50Migration:risky' => true,
'php_unit_expectation' => [
'target' => '5.2',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.2 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP54MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'array_syntax' => ['syntax' => 'short'],
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 5.4 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP74MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP73Migration' => true,
'normalize_index_brace' => true,
'short_scalar_cast' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.4 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit75MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit60Migration:risky' => true,
'php_unit_dedicate_assert_internal_type' => [
'target' => '7.5',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 7.5 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP80MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP74Migration:risky' => true,
'no_alias_functions' => [
'sets' => [
'@all',
],
],
'no_php4_constructor' => true,
'no_unneeded_final_method' => true,
'no_unreachable_default_argument_value' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 8.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PSR12RiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'no_trailing_whitespace_in_string' => true,
'no_unreachable_default_argument_value' => true,
];
}
public function getDescription()
{
return 'Rules that follow `PSR-12 <https://www.php-fig.org/psr/psr-12/>`_ standard.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class SymfonySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PSR12' => true,
'array_syntax' => [
'syntax' => 'short',
],
'backtick_to_shell_exec' => true,
'binary_operator_spaces' => true,
'blank_line_before_statement' => [
'statements' => [
'return',
],
],
'braces' => [
'allow_single_line_anonymous_class_with_empty_body' => true,
'allow_single_line_closure' => true,
],
'cast_spaces' => true,
'class_attributes_separation' => [
'elements' => [
'method' => 'one',
],
],
'class_definition' => [
'single_line' => true,
],
'clean_namespace' => true,
'concat_space' => true,
'echo_tag_syntax' => true,
'fully_qualified_strict_types' => true,
'function_typehint_space' => true,
'general_phpdoc_tag_rename' => [
'replacements' => [
'inheritDocs' => 'inheritDoc',
],
],
'include' => true,
'increment_style' => true,
'lambda_not_used_import' => true,
'linebreak_after_opening_tag' => true,
'magic_constant_casing' => true,
'magic_method_casing' => true,
'method_argument_space' => true,
'native_function_casing' => true,
'native_function_type_declaration_casing' => true,
'no_alias_language_construct_call' => true,
'no_alternative_syntax' => true,
'no_binary_string' => true,
'no_blank_lines_after_phpdoc' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => [
'tokens' => [
'case',
'continue',
'curly_brace_block',
'default',
'extra',
'parenthesis_brace_block',
'square_brace_block',
'switch',
'throw',
'use',
'use_trait',
],
],
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_short_bool_cast' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_around_offset' => true,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
'allow_unused_params' => true,
],
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_unneeded_control_parentheses' => [
'statements' => [
'break',
'clone',
'continue',
'echo_print',
'return',
'switch_case',
'yield',
'yield_from',
],
],
'no_unneeded_curly_braces' => ['namespaces' => true],
'no_unset_cast' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'normalize_index_brace' => true,
'object_operator_without_whitespace' => true,
'ordered_imports' => true,
'php_unit_fqcn_annotation' => true,
'php_unit_method_casing' => true,
'phpdoc_align' => [
'tags' => [
'method',
'param',
'property',
'return',
'throws',
'type',
'var',
],
],
'phpdoc_annotation_without_dot' => true,
'phpdoc_indent' => true,
'phpdoc_inline_tag_normalizer' => true,
'phpdoc_no_access' => true,
'phpdoc_no_alias_tag' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_return_self_reference' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_tag_type' => [
'tags' => [
'inheritDoc' => 'inline',
],
],
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => true,
'phpdoc_types_order' => [
'null_adjustment' => 'always_last',
'sort_algorithm' => 'none',
],
'phpdoc_var_without_name' => true,
'protected_to_private' => true,
'semicolon_after_instruction' => true,
'single_class_element_per_statement' => true,
'single_line_comment_style' => [
'comment_types' => [
'hash',
],
],
'single_line_throw' => true,
'single_quote' => true,
'single_space_after_construct' => true,
'space_after_semicolon' => [
'remove_in_empty_for_expressions' => true,
],
'standardize_increment' => true,
'standardize_not_equals' => true,
'switch_continue_to_break' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'visibility_required' => true,
'whitespace_after_comma_in_array' => true,
'yoda_style' => true,
];
}
public function getDescription()
{
return 'Rules that follow the official `Symfony Coding Standards <https://symfony.com/doc/current/contributing/code/standards.html>`_.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit48MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit43Migration:risky' => true,
'php_unit_namespaced' => [
'target' => '4.8',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 4.8 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit57MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit56Migration:risky' => true,
'php_unit_namespaced' => [
'target' => '5.7',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.7 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP56MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP54Migration' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 5.6 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit30MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'php_unit_dedicate_assert' => [
'target' => '3.0',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 3.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP71MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP70Migration:risky' => true,
'void_return' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.1 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PSR1Set extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'encoding' => true,
'full_opening_tag' => true,
];
}
public function getDescription()
{
return 'Rules that follow `PSR-1 <https://www.php-fig.org/psr/psr-1/>`_ standard.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PhpCsFixerSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@Symfony' => true,
'align_multiline_comment' => true,
'array_indentation' => true,
'blank_line_before_statement' => [
'statements' => [
'break',
'case',
'continue',
'declare',
'default',
'exit',
'goto',
'include',
'include_once',
'require',
'require_once',
'return',
'switch',
'throw',
'try',
],
],
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'escape_implicit_backslashes' => true,
'explicit_indirect_variable' => true,
'explicit_string_variable' => true,
'heredoc_to_nowdoc' => true,
'method_argument_space' => [
'on_multiline' => 'ensure_fully_multiline',
],
'method_chaining_indentation' => true,
'multiline_comment_opening_closing' => true,
'multiline_whitespace_before_semicolons' => [
'strategy' => 'new_line_for_chained_calls',
],
'no_extra_blank_lines' => [
'tokens' => [
'break',
'case',
'continue',
'curly_brace_block',
'default',
'extra',
'parenthesis_brace_block',
'return',
'square_brace_block',
'switch',
'throw',
'use',
'use_trait',
],
],
'no_null_property_initialization' => true,
'no_superfluous_elseif' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'operator_linebreak' => [
'only_booleans' => true,
],
'ordered_class_elements' => true,
'php_unit_internal_class' => true,
'php_unit_test_class_requires_covers' => true,
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_no_empty_return' => true,
'phpdoc_order' => true,
'phpdoc_order_by_value' => true,
'phpdoc_types_order' => true,
'phpdoc_var_annotation_correct_order' => true,
'return_assignment' => true,
'simple_to_complex_string_variable' => true,
'single_line_comment_style' => true,
'single_line_throw' => false,
];
}
public function getDescription()
{
return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP74MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP71Migration:risky' => true,
'implode_call' => true,
'no_alias_functions' => true,
'use_arrow_functions' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.1 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit43MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit35Migration:risky' => true,
'php_unit_no_expectation_annotation' => [
'target' => '4.3',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 4.3 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit56MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit55Migration:risky' => true,
'php_unit_dedicate_assert' => [
'target' => '5.6',
],
'php_unit_expectation' => [
'target' => '5.6',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.6 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit32MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit30Migration:risky' => true,
'php_unit_no_expectation_annotation' => [
'target' => '3.2',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 3.2 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit55MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit54Migration:risky' => true,
'php_unit_mock' => [
'target' => '5.5',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.5 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit60MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit57Migration:risky' => true,
'php_unit_namespaced' => [
'target' => '6.0',
],
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 6.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP71MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP70Migration' => true,
'list_syntax' => ['syntax' => 'short'],
'visibility_required' => [
'elements' => [
'const',
'method',
'property',
],
],
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.1 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class DoctrineAnnotationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'doctrine_annotation_array_assignment' => [
'operator' => ':',
],
'doctrine_annotation_braces' => true,
'doctrine_annotation_indentation' => true,
'doctrine_annotation_spaces' => [
'before_array_assignments_colon' => false,
],
];
}
public function getDescription()
{
return 'Rules covering Doctrine annotations with configuration based on examples found in `Doctrine Annotation documentation <http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html>`_ and `Symfony documentation <http://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/annotations/routing.html>`_.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP70MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP56Migration:risky' => true,
'combine_nested_dirname' => true,
'declare_strict_types' => true,
'non_printable_character' => [
'use_escape_sequences_in_strings' => true,
],
'random_api_migration' => [
'replacements' => [
'mt_rand' => 'random_int',
'rand' => 'random_int',
],
],
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP56MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'pow_to_exponentiation' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 5.6 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PSR2Set extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PSR1' => true,
'blank_line_after_namespace' => true,
'braces' => true,
'class_definition' => true,
'constant_case' => true,
'elseif' => true,
'function_declaration' => true,
'indentation_type' => true,
'line_ending' => true,
'lowercase_keywords' => true,
'method_argument_space' => [
'on_multiline' => 'ensure_fully_multiline',
],
'no_break_comment' => true,
'no_closing_tag' => true,
'no_spaces_after_function_name' => true,
'no_spaces_inside_parenthesis' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'single_blank_line_at_eof' => true,
'single_class_element_per_statement' => [
'elements' => [
'property',
],
],
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'visibility_required' => true,
];
}
public function getDescription()
{
return 'Rules that follow `PSR-2 <https://www.php-fig.org/psr/psr-2/>`_ standard.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP73MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP71Migration' => true,
'heredoc_indentation' => true,
'method_argument_space' => ['after_heredoc' => true],
'no_whitespace_before_comma_in_array' => ['after_heredoc' => true],
'trailing_comma_in_multiline_array' => ['after_heredoc' => true],
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 7.3 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class SymfonyRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
$rules = [
'@PHP56Migration:risky' => true,
'@PSR12:risky' => true,
'array_push' => true,
'combine_nested_dirname' => true,
'dir_constant' => true,
'ereg_to_preg' => true,
'error_suppression' => true,
'fopen_flag_order' => true,
'fopen_flags' => [
'b_mode' => false,
],
'function_to_constant' => [
'functions' => [
'get_called_class',
'get_class',
'get_class_this',
'php_sapi_name',
'phpversion',
'pi',
],
],
'implode_call' => true,
'is_null' => true,
'logical_operators' => true,
'modernize_types_casting' => true,
'native_constant_invocation' => true,
'native_function_invocation' => [
'include' => [
'@compiler_optimized',
],
'scope' => 'namespaced',
'strict' => true,
],
'no_alias_functions' => true,
'no_homoglyph_names' => true,
'no_php4_constructor' => true,
'no_unneeded_final_method' => true,
'no_unreachable_default_argument_value' => false,
'no_useless_sprintf' => true,
'non_printable_character' => true,
'ordered_traits' => true,
'php_unit_construct' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_test_annotation' => true,
'psr_autoloading' => true,
'self_accessor' => true,
'set_type_to_cast' => true,
'string_line_ending' => true,
'ternary_to_elvis_operator' => true,
];
$rules['non_printable_character'] = \PHP_VERSION_ID < 70000
? true
: ['use_escape_sequences_in_strings' => true]
;
ksort($rules);
return $rules;
}
public function getDescription()
{
return 'Rules that follow the official `Symfony Coding Standards <https://symfony.com/doc/current/contributing/code/standards.html>`_.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PhpCsFixerRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@Symfony:risky' => true,
'comment_to_phpdoc' => true,
'final_internal_class' => true,
'native_constant_invocation' => [
'fix_built_in' => false,
'include' => [
'DIRECTORY_SEPARATOR',
'PHP_INT_SIZE',
'PHP_SAPI',
'PHP_VERSION_ID',
],
'scope' => 'namespaced',
'strict' => true,
],
'no_alias_functions' => [
'sets' => [
'@all',
],
],
'no_unreachable_default_argument_value' => true,
'no_unset_on_property' => true,
'php_unit_strict' => true,
'php_unit_test_case_static_method_calls' => true,
'strict_comparison' => true,
'strict_param' => true,
];
}
public function getDescription()
{
return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHPUnit50MigrationRiskySet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHPUnit48Migration:risky' => true,
'php_unit_dedicate_assert' => true,
];
}
public function getDescription()
{
return 'Rules to improve tests code for PHPUnit 5.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PSR12Set extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PSR2' => true,
'blank_line_after_opening_tag' => true,
'braces' => [
'allow_single_line_anonymous_class_with_empty_body' => true,
],
'compact_nullable_typehint' => true,
'declare_equal_normalize' => true,
'lowercase_cast' => true,
'lowercase_static_reference' => true,
'new_with_braces' => true,
'no_blank_lines_after_class_opening' => true,
'no_leading_import_slash' => true,
'no_whitespace_in_blank_line' => true,
'ordered_class_elements' => [
'order' => [
'use_trait',
],
],
'ordered_imports' => [
'imports_order' => [
'class',
'function',
'const',
],
'sort_algorithm' => 'none',
],
'return_type_declaration' => true,
'short_scalar_cast' => true,
'single_blank_line_before_namespace' => true,
'single_trait_insert_per_statement' => true,
'ternary_operator_spaces' => true,
'visibility_required' => [
'elements' => [
'const',
'method',
'property',
],
],
];
}
public function getDescription()
{
return 'Rules that follow `PSR-12 <https://www.php-fig.org/psr/psr-12/>`_ standard.';
}
}
<?php
namespace PhpCsFixer\RuleSet\Sets;
use PhpCsFixer\RuleSet\AbstractRuleSetDescription;
final class PHP80MigrationSet extends AbstractRuleSetDescription
{
public function getRules()
{
return [
'@PHP74Migration' => true,
'clean_namespace' => true,
'no_unset_cast' => true,
];
}
public function getDescription()
{
return 'Rules to improve code for PHP 8.0 compatibility.';
}
}
<?php
namespace PhpCsFixer\RuleSet;
use Symfony\Component\Finder\Finder;
final class RuleSets
{
private static $setDefinitions;
public static function getSetDefinitions()
{
if (null === self::$setDefinitions) {
self::$setDefinitions = [];
foreach (Finder::create()->files()->in(__DIR__.'/Sets') as $file) {
$class = 'PhpCsFixer\RuleSet\Sets\\'.$file->getBasename('.php');
$set = new $class();
self::$setDefinitions[$set->getName()] = $set;
}
ksort(self::$setDefinitions);
}
return self::$setDefinitions;
}
public static function getSetDefinitionNames()
{
return array_keys(self::getSetDefinitions());
}
public static function getSetDefinition($name)
{
$definitions = self::getSetDefinitions();
if (!isset($definitions[$name])) {
throw new \InvalidArgumentException(sprintf('Set "%s" does not exist.', $name));
}
return $definitions[$name];
}
}
<?php
namespace PhpCsFixer\RuleSet;
abstract class AbstractRuleSetDescription implements RuleSetDescriptionInterface
{
public function __construct()
{
}
public function getName()
{
$name = substr(static::class, 1 + strrpos(static::class, '\\'), -3);
return '@'.str_replace('Risky', ':risky', $name);
}
public function isRisky()
{
return false !== strpos(static::class, 'Risky');
}
}
<?php
namespace PhpCsFixer\Cache;
interface DirectoryInterface
{
public function getRelativePathTo($file);
}
<?php
namespace PhpCsFixer\Cache;
use Symfony\Component\Filesystem\Exception\IOException;
final class FileHandler implements FileHandlerInterface
{
private $file;
public function __construct($file)
{
$this->file = $file;
}
public function getFile()
{
return $this->file;
}
public function read()
{
if (!file_exists($this->file)) {
return null;
}
$content = file_get_contents($this->file);
try {
$cache = Cache::fromJson($content);
} catch (\InvalidArgumentException $exception) {
return null;
}
return $cache;
}
public function write(CacheInterface $cache)
{
$content = $cache->toJson();
if (file_exists($this->file)) {
if (is_dir($this->file)) {
throw new IOException(
sprintf('Cannot write cache file "%s" as the location exists as directory.', realpath($this->file)),
0,
null,
$this->file
);
}
if (!is_writable($this->file)) {
throw new IOException(
sprintf('Cannot write to file "%s" as it is not writable.', realpath($this->file)),
0,
null,
$this->file
);
}
} else {
$dir = \dirname($this->file);
if (!is_dir($dir)) {
throw new IOException(
sprintf('Directory of cache file "%s" does not exists.', $this->file),
0,
null,
$this->file
);
}
@touch($this->file);
@chmod($this->file, 0666);
}
$bytesWritten = @file_put_contents($this->file, $content);
if (false === $bytesWritten) {
$error = error_get_last();
throw new IOException(
sprintf('Failed to write file "%s", "%s".', $this->file, isset($error['message']) ? $error['message'] : 'no reason available'),
0,
null,
$this->file
);
}
}
}
<?php
namespace PhpCsFixer\Cache;
interface CacheInterface
{
public function getSignature();
public function has($file);
public function get($file);
public function set($file, $hash);
public function clear($file);
public function toJson();
}
<?php
namespace PhpCsFixer\Cache;
final class Directory implements DirectoryInterface
{
private $directoryName;
public function __construct($directoryName)
{
$this->directoryName = $directoryName;
}
public function getRelativePathTo($file)
{
$file = $this->normalizePath($file);
if (
'' === $this->directoryName
|| 0 !== stripos($file, $this->directoryName.\DIRECTORY_SEPARATOR)
) {
return $file;
}
return substr($file, \strlen($this->directoryName) + 1);
}
private function normalizePath($path)
{
return str_replace(['\\', '/'], \DIRECTORY_SEPARATOR, $path);
}
}
<?php
namespace PhpCsFixer\Cache;
interface FileHandlerInterface
{
public function getFile();
public function read();
public function write(CacheInterface $cache);
}
<?php
namespace PhpCsFixer\Cache;
final class Cache implements CacheInterface
{
private $signature;
private $hashes = [];
public function __construct(SignatureInterface $signature)
{
$this->signature = $signature;
}
public function getSignature()
{
return $this->signature;
}
public function has($file)
{
return \array_key_exists($file, $this->hashes);
}
public function get($file)
{
if (!$this->has($file)) {
return null;
}
return $this->hashes[$file];
}
public function set($file, $hash)
{
$this->hashes[$file] = $hash;
}
public function clear($file)
{
unset($this->hashes[$file]);
}
public function toJson()
{
$json = json_encode([
'php' => $this->getSignature()->getPhpVersion(),
'version' => $this->getSignature()->getFixerVersion(),
'indent' => $this->getSignature()->getIndent(),
'lineEnding' => $this->getSignature()->getLineEnding(),
'rules' => $this->getSignature()->getRules(),
'hashes' => $this->hashes,
]);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \UnexpectedValueException(sprintf(
'Can not encode cache signature to JSON, error: "%s". If you have non-UTF8 chars in your signature, like in license for `header_comment`, consider enabling `ext-mbstring` or install `symfony/polyfill-mbstring`.',
json_last_error_msg()
));
}
return $json;
}
public static function fromJson($json)
{
$data = json_decode($json, true);
if (null === $data && JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(sprintf(
'Value needs to be a valid JSON string, got "%s", error: "%s".',
$json,
json_last_error_msg()
));
}
$requiredKeys = [
'php',
'version',
'indent',
'lineEnding',
'rules',
'hashes',
];
$missingKeys = array_diff_key(array_flip($requiredKeys), $data);
if (\count($missingKeys)) {
throw new \InvalidArgumentException(sprintf(
'JSON data is missing keys "%s"',
implode('", "', $missingKeys)
));
}
$signature = new Signature(
$data['php'],
$data['version'],
$data['indent'],
$data['lineEnding'],
$data['rules']
);
$cache = new self($signature);
$cache->hashes = $data['hashes'];
return $cache;
}
}
<?php
namespace PhpCsFixer\Cache;
final class Signature implements SignatureInterface
{
private $phpVersion;
private $fixerVersion;
private $indent;
private $lineEnding;
private $rules;
public function __construct($phpVersion, $fixerVersion, $indent, $lineEnding, array $rules)
{
$this->phpVersion = $phpVersion;
$this->fixerVersion = $fixerVersion;
$this->indent = $indent;
$this->lineEnding = $lineEnding;
$this->rules = self::utf8Encode($rules);
}
public function getPhpVersion()
{
return $this->phpVersion;
}
public function getFixerVersion()
{
return $this->fixerVersion;
}
public function getIndent()
{
return $this->indent;
}
public function getLineEnding()
{
return $this->lineEnding;
}
public function getRules()
{
return $this->rules;
}
public function equals(SignatureInterface $signature)
{
return $this->phpVersion === $signature->getPhpVersion()
&& $this->fixerVersion === $signature->getFixerVersion()
&& $this->indent === $signature->getIndent()
&& $this->lineEnding === $signature->getLineEnding()
&& $this->rules === $signature->getRules();
}
private static function utf8Encode(array $data)
{
if (!\function_exists('mb_detect_encoding')) {
return $data;
}
array_walk_recursive($data, static function (&$item) {
if (\is_string($item) && !mb_detect_encoding($item, 'utf-8', true)) {
$item = utf8_encode($item);
}
});
return $data;
}
}
<?php
namespace PhpCsFixer\Cache;
interface SignatureInterface
{
public function getPhpVersion();
public function getFixerVersion();
public function getIndent();
public function getLineEnding();
public function getRules();
public function equals(self $signature);
}
<?php
namespace PhpCsFixer\Cache;
final class FileCacheManager implements CacheManagerInterface
{
private $handler;
private $signature;
private $cache;
private $isDryRun;
private $cacheDirectory;
public function __construct(
FileHandlerInterface $handler,
SignatureInterface $signature,
$isDryRun = false,
DirectoryInterface $cacheDirectory = null
) {
$this->handler = $handler;
$this->signature = $signature;
$this->isDryRun = $isDryRun;
$this->cacheDirectory = $cacheDirectory ?: new Directory('');
$this->readCache();
}
public function __destruct()
{
$this->writeCache();
}
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function needFixing($file, $fileContent)
{
$file = $this->cacheDirectory->getRelativePathTo($file);
return !$this->cache->has($file) || $this->cache->get($file) !== $this->calcHash($fileContent);
}
public function setFile($file, $fileContent)
{
$file = $this->cacheDirectory->getRelativePathTo($file);
$hash = $this->calcHash($fileContent);
if ($this->isDryRun && $this->cache->has($file) && $this->cache->get($file) !== $hash) {
$this->cache->clear($file);
return;
}
$this->cache->set($file, $hash);
}
private function readCache()
{
$cache = $this->handler->read();
if (!$cache || !$this->signature->equals($cache->getSignature())) {
$cache = new Cache($this->signature);
}
$this->cache = $cache;
}
private function writeCache()
{
$this->handler->write($this->cache);
}
private function calcHash($content)
{
return crc32($content);
}
}
<?php
namespace PhpCsFixer\Cache;
interface CacheManagerInterface
{
public function needFixing($file, $fileContent);
public function setFile($file, $fileContent);
}
<?php
namespace PhpCsFixer\Cache;
final class NullCacheManager implements CacheManagerInterface
{
public function needFixing($file, $fileContent)
{
return true;
}
public function setFile($file, $fileContent)
{
}
}
#!/bin/sh
set -eu
IFS='
'
CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}")
if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php_cs(\\.dist)?|composer\\.lock)$"; then EXTRA_ARGS=$(printf -- '--path-mode=intersection\n--\n%s' "${CHANGED_FILES}"); else EXTRA_ARGS=''; fi
vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v --dry-run --stop-on-violation --using-cache=no ${EXTRA_ARGS}
<?php
namespace Symfony\Component\Filesystem;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\Filesystem\Exception\IOException;
class Filesystem
{
private static $lastError;
public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
{
$originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
if ($originIsLocal && !is_file($originFile)) {
throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
}
$this->mkdir(\dirname($targetFile));
$doCopy = true;
if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) {
$doCopy = filemtime($originFile) > filemtime($targetFile);
}
if ($doCopy) {
if (false === $source = @fopen($originFile, 'r')) {
throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
}
if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(['ftp' => ['overwrite' => true]]))) {
throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
}
$bytesCopied = stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
unset($source, $target);
if (!is_file($targetFile)) {
throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
}
if ($originIsLocal) {
@chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
}
}
}
}
public function mkdir($dirs, $mode = 0777)
{
foreach ($this->toIterable($dirs) as $dir) {
if (is_dir($dir)) {
continue;
}
if (!self::box('mkdir', $dir, $mode, true)) {
if (!is_dir($dir)) {
if (self::$lastError) {
throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir);
}
throw new IOException(sprintf('Failed to create "%s".', $dir), 0, null, $dir);
}
}
}
}
public function exists($files)
{
$maxPathLength = \PHP_MAXPATHLEN - 2;
foreach ($this->toIterable($files) as $file) {
if (\strlen($file) > $maxPathLength) {
throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
}
if (!file_exists($file)) {
return false;
}
}
return true;
}
public function touch($files, $time = null, $atime = null)
{
foreach ($this->toIterable($files) as $file) {
$touch = $time ? @touch($file, $time, $atime) : @touch($file);
if (true !== $touch) {
throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
}
}
}
public function remove($files)
{
if ($files instanceof \Traversable) {
$files = iterator_to_array($files, false);
} elseif (!\is_array($files)) {
$files = [$files];
}
$files = array_reverse($files);
foreach ($files as $file) {
if (is_link($file)) {
if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) {
throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError);
}
} elseif (is_dir($file)) {
$this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
if (!self::box('rmdir', $file) && file_exists($file)) {
throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError);
}
} elseif (!self::box('unlink', $file) && (false !== strpos(self::$lastError, 'Permission denied') || file_exists($file))) {
throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError);
}
}
}
public function chmod($files, $mode, $umask = 0000, $recursive = false)
{
foreach ($this->toIterable($files) as $file) {
if ((\PHP_VERSION_ID < 80000 || \is_int($mode)) && true !== @chmod($file, $mode & ~$umask)) {
throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
}
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
}
}
}
public function chown($files, $user, $recursive = false)
{
foreach ($this->toIterable($files) as $file) {
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chown(new \FilesystemIterator($file), $user, true);
}
if (is_link($file) && \function_exists('lchown')) {
if (true !== @lchown($file, $user)) {
throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @chown($file, $user)) {
throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
}
}
}
}
public function chgrp($files, $group, $recursive = false)
{
foreach ($this->toIterable($files) as $file) {
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chgrp(new \FilesystemIterator($file), $group, true);
}
if (is_link($file) && \function_exists('lchgrp')) {
if (true !== @lchgrp($file, $group) || (\defined('HHVM_VERSION') && !posix_getgrnam($group))) {
throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @chgrp($file, $group)) {
throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
}
}
}
}
public function rename($origin, $target, $overwrite = false)
{
if (!$overwrite && $this->isReadable($target)) {
throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
}
if (true !== @rename($origin, $target)) {
if (is_dir($origin)) {
$this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]);
$this->remove($origin);
return;
}
throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
}
}
private function isReadable($filename)
{
$maxPathLength = \PHP_MAXPATHLEN - 2;
if (\strlen($filename) > $maxPathLength) {
throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
}
return is_readable($filename);
}
public function symlink($originDir, $targetDir, $copyOnWindows = false)
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$originDir = strtr($originDir, '/', '\\');
$targetDir = strtr($targetDir, '/', '\\');
if ($copyOnWindows) {
$this->mirror($originDir, $targetDir);
return;
}
}
$this->mkdir(\dirname($targetDir));
if (is_link($targetDir)) {
if (readlink($targetDir) === $originDir) {
return;
}
$this->remove($targetDir);
}
if (!self::box('symlink', $originDir, $targetDir)) {
$this->linkException($originDir, $targetDir, 'symbolic');
}
}
public function hardlink($originFile, $targetFiles)
{
if (!$this->exists($originFile)) {
throw new FileNotFoundException(null, 0, null, $originFile);
}
if (!is_file($originFile)) {
throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile));
}
foreach ($this->toIterable($targetFiles) as $targetFile) {
if (is_file($targetFile)) {
if (fileinode($originFile) === fileinode($targetFile)) {
continue;
}
$this->remove($targetFile);
}
if (!self::box('link', $originFile, $targetFile)) {
$this->linkException($originFile, $targetFile, 'hard');
}
}
}
private function linkException($origin, $target, $linkType)
{
if (self::$lastError) {
if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) {
throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target);
}
}
throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target);
}
public function readlink($path, $canonicalize = false)
{
if (!$canonicalize && !is_link($path)) {
return null;
}
if ($canonicalize) {
if (!$this->exists($path)) {
return null;
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$path = readlink($path);
}
return realpath($path);
}
if ('\\' === \DIRECTORY_SEPARATOR) {
return realpath($path);
}
return readlink($path);
}
public function makePathRelative($endPath, $startPath)
{
if (!$this->isAbsolutePath($endPath) || !$this->isAbsolutePath($startPath)) {
@trigger_error(sprintf('Support for passing relative paths to %s() is deprecated since Symfony 3.4 and will be removed in 4.0.', __METHOD__), \E_USER_DEPRECATED);
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$endPath = str_replace('\\', '/', $endPath);
$startPath = str_replace('\\', '/', $startPath);
}
$splitDriveLetter = function ($path) {
return (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0]))
? [substr($path, 2), strtoupper($path[0])]
: [$path, null];
};
$splitPath = function ($path, $absolute) {
$result = [];
foreach (explode('/', trim($path, '/')) as $segment) {
if ('..' === $segment && ($absolute || \count($result))) {
array_pop($result);
} elseif ('.' !== $segment && '' !== $segment) {
$result[] = $segment;
}
}
return $result;
};
list($endPath, $endDriveLetter) = $splitDriveLetter($endPath);
list($startPath, $startDriveLetter) = $splitDriveLetter($startPath);
$startPathArr = $splitPath($startPath, static::isAbsolutePath($startPath));
$endPathArr = $splitPath($endPath, static::isAbsolutePath($endPath));
if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) {
return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : '');
}
$index = 0;
while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
++$index;
}
if (1 === \count($startPathArr) && '' === $startPathArr[0]) {
$depth = 0;
} else {
$depth = \count($startPathArr) - $index;
}
$traverser = str_repeat('../', $depth);
$endPathRemainder = implode('/', \array_slice($endPathArr, $index));
$relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
return '' === $relativePath ? './' : $relativePath;
}
public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = [])
{
$targetDir = rtrim($targetDir, '/\\');
$originDir = rtrim($originDir, '/\\');
$originDirLen = \strlen($originDir);
if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
$deleteIterator = $iterator;
if (null === $deleteIterator) {
$flags = \FilesystemIterator::SKIP_DOTS;
$deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
}
$targetDirLen = \strlen($targetDir);
foreach ($deleteIterator as $file) {
$origin = $originDir.substr($file->getPathname(), $targetDirLen);
if (!$this->exists($origin)) {
$this->remove($file);
}
}
}
$copyOnWindows = false;
if (isset($options['copy_on_windows'])) {
$copyOnWindows = $options['copy_on_windows'];
}
if (null === $iterator) {
$flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
}
if ($this->exists($originDir)) {
$this->mkdir($targetDir);
}
foreach ($iterator as $file) {
$target = $targetDir.substr($file->getPathname(), $originDirLen);
if ($copyOnWindows) {
if (is_file($file)) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} elseif (is_dir($file)) {
$this->mkdir($target);
} else {
throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
}
} else {
if (is_link($file)) {
$this->symlink($file->getLinkTarget(), $target);
} elseif (is_dir($file)) {
$this->mkdir($target);
} elseif (is_file($file)) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} else {
throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
}
}
}
}
public function isAbsolutePath($file)
{
return '' !== (string) $file && (strspn($file, '/\\', 0, 1)
|| (\strlen($file) > 3 && ctype_alpha($file[0])
&& ':' === $file[1]
&& strspn($file, '/\\', 2, 1)
)
|| null !== parse_url($file, \PHP_URL_SCHEME)
);
}
public function tempnam($dir, $prefix)
{
list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
$tmpFile = @tempnam($hierarchy, $prefix);
if (false !== $tmpFile) {
if (null !== $scheme && 'gs' !== $scheme) {
return $scheme.'://'.$tmpFile;
}
return $tmpFile;
}
throw new IOException('A temporary file could not be created.');
}
for ($i = 0; $i < 10; ++$i) {
$tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
$handle = @fopen($tmpFile, 'x+');
if (false === $handle) {
continue;
}
@fclose($handle);
return $tmpFile;
}
throw new IOException('A temporary file could not be created.');
}
public function dumpFile($filename, $content)
{
$dir = \dirname($filename);
if (!is_dir($dir)) {
$this->mkdir($dir);
}
if (!is_writable($dir)) {
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
}
$tmpFile = $this->tempnam($dir, basename($filename));
if (false === @file_put_contents($tmpFile, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}
@chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
$this->rename($tmpFile, $filename, true);
}
public function appendToFile($filename, $content)
{
$dir = \dirname($filename);
if (!is_dir($dir)) {
$this->mkdir($dir);
}
if (!is_writable($dir)) {
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
}
if (false === @file_put_contents($filename, $content, \FILE_APPEND)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}
}
private function toIterable($files)
{
return \is_array($files) || $files instanceof \Traversable ? $files : [$files];
}
private function getSchemeAndHierarchy($filename)
{
$components = explode('://', $filename, 2);
return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]];
}
private static function box($func)
{
self::$lastError = null;
set_error_handler(__CLASS__.'::handleError');
try {
$result = \call_user_func_array($func, \array_slice(\func_get_args(), 1));
restore_error_handler();
return $result;
} catch (\Throwable $e) {
} catch (\Exception $e) {
}
restore_error_handler();
throw $e;
}
public static function handleError($type, $msg)
{
self::$lastError = $msg;
}
}
<?php
namespace Symfony\Component\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\SemaphoreStore;
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Use %s or %s instead.', LockHandler::class, SemaphoreStore::class, FlockStore::class), \E_USER_DEPRECATED);
/**
@gmail
@tchwork
*/
class LockHandler
{
private $file;
private $handle;
public function __construct($name, $lockPath = null)
{
$lockPath = $lockPath ?: sys_get_temp_dir();
if (!is_dir($lockPath)) {
$fs = new Filesystem();
$fs->mkdir($lockPath);
}
if (!is_writable($lockPath)) {
throw new IOException(sprintf('The directory "%s" is not writable.', $lockPath), 0, null, $lockPath);
}
$this->file = sprintf('%s/sf.%s.%s.lock', $lockPath, preg_replace('/[^a-z0-9\._-]+/i', '-', $name), hash('sha256', $name));
}
public function lock($blocking = false)
{
if ($this->handle) {
return true;
}
$error = null;
set_error_handler(function ($errno, $msg) use (&$error) {
$error = $msg;
});
if (!$this->handle = fopen($this->file, 'r+') ?: fopen($this->file, 'r')) {
if ($this->handle = fopen($this->file, 'x')) {
chmod($this->file, 0666);
} elseif (!$this->handle = fopen($this->file, 'r+') ?: fopen($this->file, 'r')) {
usleep(100);
$this->handle = fopen($this->file, 'r+') ?: fopen($this->file, 'r');
}
}
restore_error_handler();
if (!$this->handle) {
throw new IOException($error, 0, null, $this->file);
}
if (!flock($this->handle, \LOCK_EX | ($blocking ? 0 : \LOCK_NB))) {
fclose($this->handle);
$this->handle = null;
return false;
}
return true;
}
public function release()
{
if ($this->handle) {
flock($this->handle, \LOCK_UN | \LOCK_NB);
fclose($this->handle);
$this->handle = null;
}
}
}
<?php
namespace Symfony\Component\Filesystem\Exception;
interface IOExceptionInterface extends ExceptionInterface
{
public function getPath();
}
<?php
namespace Symfony\Component\Filesystem\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Filesystem\Exception;
/**
@googlemail
@symfony
*/
class IOException extends \RuntimeException implements IOExceptionInterface
{
private $path;
public function __construct($message, $code = 0, \Exception $previous = null, $path = null)
{
$this->path = $path;
parent::__construct($message, $code, $previous);
}
public function getPath()
{
return $this->path;
}
}
<?php
namespace Symfony\Component\Filesystem\Exception;
/**
@googlemail
*/
class FileNotFoundException extends IOException
{
public function __construct($message = null, $code = 0, \Exception $previous = null, $path = null)
{
if (null === $message) {
if (null === $path) {
$message = 'File could not be found.';
} else {
$message = sprintf('File "%s" could not be found.', $path);
}
}
parent::__construct($message, $code, $previous, $path);
}
}
<?php
namespace Symfony\Component\Finder;
/**
@unixbeard
@symfony
@unixbeard
*/
class Glob
{
public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true, $delimiter = '#')
{
$firstByte = true;
$escaping = false;
$inCurlies = 0;
$regex = '';
$sizeGlob = \strlen($glob);
for ($i = 0; $i < $sizeGlob; ++$i) {
$car = $glob[$i];
if ($firstByte && $strictLeadingDot && '.' !== $car) {
$regex .= '(?=[^\.])';
}
$firstByte = '/' === $car;
if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) {
$car = '[^/]++/';
if (!isset($glob[$i + 3])) {
$car .= '?';
}
if ($strictLeadingDot) {
$car = '(?=[^\.])'.$car;
}
$car = '/(?:'.$car.')*';
$i += 2 + isset($glob[$i + 3]);
if ('/' === $delimiter) {
$car = str_replace('/', '\\/', $car);
}
}
if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
$regex .= "\\$car";
} elseif ('*' === $car) {
$regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
} elseif ('?' === $car) {
$regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
} elseif ('{' === $car) {
$regex .= $escaping ? '\\{' : '(';
if (!$escaping) {
++$inCurlies;
}
} elseif ('}' === $car && $inCurlies) {
$regex .= $escaping ? '}' : ')';
if (!$escaping) {
--$inCurlies;
}
} elseif (',' === $car && $inCurlies) {
$regex .= $escaping ? ',' : '|';
} elseif ('\\' === $car) {
if ($escaping) {
$regex .= '\\\\';
$escaping = false;
} else {
$escaping = true;
}
continue;
} else {
$regex .= $car;
}
$escaping = false;
}
return $delimiter.'^'.$regex.'$'.$delimiter;
}
}
<?php
namespace Symfony\Component\Finder;
class SplFileInfo extends \SplFileInfo
{
private $relativePath;
private $relativePathname;
public function __construct($file, $relativePath, $relativePathname)
{
parent::__construct($file);
$this->relativePath = $relativePath;
$this->relativePathname = $relativePathname;
}
public function getRelativePath()
{
return $this->relativePath;
}
public function getRelativePathname()
{
return $this->relativePathname;
}
public function getContents()
{
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$content = file_get_contents($this->getPathname());
restore_error_handler();
if (false === $content) {
throw new \RuntimeException($error);
}
return $content;
}
}
<?php
namespace Symfony\Component\Finder\Comparator;
/**
@unixbeard
@symfony
@unixbeard
*/
class NumberComparator extends Comparator
{
public function __construct($test)
{
if (!preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test));
}
$target = $matches[2];
if (!is_numeric($target)) {
throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target));
}
if (isset($matches[3])) {
switch (strtolower($matches[3])) {
case 'k':
$target *= 1000;
break;
case 'ki':
$target *= 1024;
break;
case 'm':
$target *= 1000000;
break;
case 'mi':
$target *= 1024 * 1024;
break;
case 'g':
$target *= 1000000000;
break;
case 'gi':
$target *= 1024 * 1024 * 1024;
break;
}
}
$this->setTarget($target);
$this->setOperator(isset($matches[1]) ? $matches[1] : '==');
}
}
<?php
namespace Symfony\Component\Finder\Comparator;
class DateComparator extends Comparator
{
public function __construct($test)
{
if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test));
}
try {
$date = new \DateTime($matches[2]);
$target = $date->format('U');
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
}
$operator = isset($matches[1]) ? $matches[1] : '==';
if ('since' === $operator || 'after' === $operator) {
$operator = '>';
}
if ('until' === $operator || 'before' === $operator) {
$operator = '<';
}
$this->setOperator($operator);
$this->setTarget($target);
}
}
<?php
namespace Symfony\Component\Finder\Comparator;
class Comparator
{
private $target;
private $operator = '==';
public function getTarget()
{
return $this->target;
}
public function setTarget($target)
{
$this->target = $target;
}
public function getOperator()
{
return $this->operator;
}
public function setOperator($operator)
{
if (!$operator) {
$operator = '==';
}
if (!\in_array($operator, ['>', '<', '>=', '<=', '==', '!='])) {
throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator));
}
$this->operator = $operator;
}
public function test($test)
{
switch ($this->operator) {
case '>':
return $test > $this->target;
case '>=':
return $test >= $this->target;
case '<':
return $test < $this->target;
case '<=':
return $test <= $this->target;
case '!=':
return $test != $this->target;
}
return $test == $this->target;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Comparator\NumberComparator;
class SizeRangeFilterIterator extends FilterIterator
{
private $comparators = [];
public function __construct(\Iterator $iterator, array $comparators)
{
$this->comparators = $comparators;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (!$fileinfo->isFile()) {
return true;
}
$filesize = $fileinfo->getSize();
foreach ($this->comparators as $compare) {
if (!$compare->test($filesize)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
abstract class FilterIterator extends \FilterIterator
{
public function rewind()
{
if (\PHP_VERSION_ID > 50607 || (\PHP_VERSION_ID > 50523 && \PHP_VERSION_ID < 50600)) {
parent::rewind();
return;
}
$iterator = $this;
while ($iterator instanceof \OuterIterator) {
$innerIterator = $iterator->getInnerIterator();
if ($innerIterator instanceof RecursiveDirectoryIterator) {
if ($innerIterator->isRewindable()) {
$innerIterator->next();
$innerIterator->rewind();
}
} elseif ($innerIterator instanceof \FilesystemIterator) {
$innerIterator->next();
$innerIterator->rewind();
}
$iterator = $innerIterator;
}
parent::rewind();
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
abstract class MultiplePcreFilterIterator extends FilterIterator
{
protected $matchRegexps = [];
protected $noMatchRegexps = [];
public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
{
foreach ($matchPatterns as $pattern) {
$this->matchRegexps[] = $this->toRegex($pattern);
}
foreach ($noMatchPatterns as $pattern) {
$this->noMatchRegexps[] = $this->toRegex($pattern);
}
parent::__construct($iterator);
}
protected function isAccepted($string)
{
foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $string)) {
return false;
}
}
if ($this->matchRegexps) {
foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $string)) {
return true;
}
}
return false;
}
return true;
}
protected function isRegex($str)
{
if (preg_match('/^(.{3,}?)[imsxuADU]*$/', $str, $m)) {
$start = substr($m[1], 0, 1);
$end = substr($m[1], -1);
if ($start === $end) {
return !preg_match('/[*?[:alnum:] \\\\]/', $start);
}
foreach ([['{', '}'], ['(', ')'], ['[', ']'], ['<', '>']] as $delimiters) {
if ($start === $delimiters[0] && $end === $delimiters[1]) {
return true;
}
}
}
return false;
}
abstract protected function toRegex($str);
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Glob;
class FilenameFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
return $this->isAccepted($this->current()->getFilename());
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : Glob::toRegex($str);
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class DepthRangeFilterIterator extends FilterIterator
{
private $minDepth = 0;
public function __construct(\RecursiveIteratorIterator $iterator, $minDepth = 0, $maxDepth = \PHP_INT_MAX)
{
$this->minDepth = $minDepth;
$iterator->setMaxDepth(\PHP_INT_MAX === $maxDepth ? -1 : $maxDepth);
parent::__construct($iterator);
}
public function accept()
{
return $this->getInnerIterator()->getDepth() >= $this->minDepth;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator
{
private $iterator;
private $isRecursive;
private $excludedDirs = [];
private $excludedPattern;
public function __construct(\Iterator $iterator, array $directories)
{
$this->iterator = $iterator;
$this->isRecursive = $iterator instanceof \RecursiveIterator;
$patterns = [];
foreach ($directories as $directory) {
$directory = rtrim($directory, '/');
if (!$this->isRecursive || false !== strpos($directory, '/')) {
$patterns[] = preg_quote($directory, '#');
} else {
$this->excludedDirs[$directory] = true;
}
}
if ($patterns) {
$this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#';
}
parent::__construct($iterator);
}
public function accept()
{
if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) {
return false;
}
if ($this->excludedPattern) {
$path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
$path = str_replace('\\', '/', $path);
return !preg_match($this->excludedPattern, $path);
}
return true;
}
public function hasChildren()
{
return $this->isRecursive && $this->iterator->hasChildren();
}
public function getChildren()
{
$children = new self($this->iterator->getChildren(), []);
$children->excludedDirs = $this->excludedDirs;
$children->excludedPattern = $this->excludedPattern;
return $children;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Finder\SplFileInfo;
class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
{
private $ignoreUnreadableDirs;
private $rewindable;
private $rootPath;
private $subPath;
private $directorySeparator = '/';
public function __construct($path, $flags, $ignoreUnreadableDirs = false)
{
if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) {
throw new \RuntimeException('This iterator only support returning current as fileinfo.');
}
parent::__construct($path, $flags);
$this->ignoreUnreadableDirs = $ignoreUnreadableDirs;
$this->rootPath = $path;
if ('/' !== \DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) {
$this->directorySeparator = \DIRECTORY_SEPARATOR;
}
}
public function current()
{
if (null === $subPathname = $this->subPath) {
$subPathname = $this->subPath = (string) $this->getSubPath();
}
if ('' !== $subPathname) {
$subPathname .= $this->directorySeparator;
}
$subPathname .= $this->getFilename();
if ('/' !== $basePath = $this->rootPath) {
$basePath .= $this->directorySeparator;
}
return new SplFileInfo($basePath.$subPathname, $this->subPath, $subPathname);
}
public function getChildren()
{
try {
$children = parent::getChildren();
if ($children instanceof self) {
$children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
$children->rewindable = &$this->rewindable;
$children->rootPath = $this->rootPath;
}
return $children;
} catch (\UnexpectedValueException $e) {
if ($this->ignoreUnreadableDirs) {
return new \RecursiveArrayIterator([]);
} else {
throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e);
}
}
}
public function rewind()
{
if (false === $this->isRewindable()) {
return;
}
if (\PHP_VERSION_ID < 50523 || \PHP_VERSION_ID >= 50600 && \PHP_VERSION_ID < 50607) {
parent::next();
}
parent::rewind();
}
public function isRewindable()
{
if (null !== $this->rewindable) {
return $this->rewindable;
}
if ('' === $this->getPath()) {
return $this->rewindable = false;
}
if (false !== $stream = @opendir($this->getPath())) {
$infos = stream_get_meta_data($stream);
closedir($stream);
if ($infos['seekable']) {
return $this->rewindable = true;
}
}
return $this->rewindable = false;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class FileTypeFilterIterator extends FilterIterator
{
const ONLY_FILES = 1;
const ONLY_DIRECTORIES = 2;
private $mode;
public function __construct(\Iterator $iterator, $mode)
{
$this->mode = $mode;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) {
return false;
} elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
return false;
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Comparator\DateComparator;
class DateRangeFilterIterator extends FilterIterator
{
private $comparators = [];
public function __construct(\Iterator $iterator, array $comparators)
{
$this->comparators = $comparators;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (!file_exists($fileinfo->getPathname())) {
return false;
}
$filedate = $fileinfo->getMTime();
foreach ($this->comparators as $compare) {
if (!$compare->test($filedate)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class CustomFilterIterator extends FilterIterator
{
private $filters = [];
public function __construct(\Iterator $iterator, array $filters)
{
foreach ($filters as $filter) {
if (!\is_callable($filter)) {
throw new \InvalidArgumentException('Invalid PHP callback.');
}
}
$this->filters = $filters;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
foreach ($this->filters as $filter) {
if (false === \call_user_func($filter, $fileinfo)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
/**
@gajdaw
*/
class PathFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
$filename = $this->current()->getRelativePathname();
if ('\\' === \DIRECTORY_SEPARATOR) {
$filename = str_replace('\\', '/', $filename);
}
return $this->isAccepted($filename);
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
/**
@gajdaw
*/
class FilecontentFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
if (!$this->matchRegexps && !$this->noMatchRegexps) {
return true;
}
$fileinfo = $this->current();
if ($fileinfo->isDir() || !$fileinfo->isReadable()) {
return false;
}
$content = $fileinfo->getContents();
if (!$content) {
return false;
}
return $this->isAccepted($content);
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class SortableIterator implements \IteratorAggregate
{
const SORT_BY_NAME = 1;
const SORT_BY_TYPE = 2;
const SORT_BY_ACCESSED_TIME = 3;
const SORT_BY_CHANGED_TIME = 4;
const SORT_BY_MODIFIED_TIME = 5;
private $iterator;
private $sort;
public function __construct(\Traversable $iterator, $sort)
{
$this->iterator = $iterator;
if (self::SORT_BY_NAME === $sort) {
$this->sort = static function ($a, $b) {
return strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname());
};
} elseif (self::SORT_BY_TYPE === $sort) {
$this->sort = static function ($a, $b) {
if ($a->isDir() && $b->isFile()) {
return -1;
} elseif ($a->isFile() && $b->isDir()) {
return 1;
}
return strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname());
};
} elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
$this->sort = static function ($a, $b) {
return $a->getATime() - $b->getATime();
};
} elseif (self::SORT_BY_CHANGED_TIME === $sort) {
$this->sort = static function ($a, $b) {
return $a->getCTime() - $b->getCTime();
};
} elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
$this->sort = static function ($a, $b) {
return $a->getMTime() - $b->getMTime();
};
} elseif (\is_callable($sort)) {
$this->sort = $sort;
} else {
throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
}
}
public function getIterator()
{
$array = iterator_to_array($this->iterator, true);
uasort($array, $this->sort);
return new \ArrayIterator($array);
}
}
<?php
namespace Symfony\Component\Finder;
use Symfony\Component\Finder\Comparator\DateComparator;
use Symfony\Component\Finder\Comparator\NumberComparator;
use Symfony\Component\Finder\Iterator\CustomFilterIterator;
use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
use Symfony\Component\Finder\Iterator\SortableIterator;
class Finder implements \IteratorAggregate, \Countable
{
const IGNORE_VCS_FILES = 1;
const IGNORE_DOT_FILES = 2;
private $mode = 0;
private $names = [];
private $notNames = [];
private $exclude = [];
private $filters = [];
private $depths = [];
private $sizes = [];
private $followLinks = false;
private $sort = false;
private $ignore = 0;
private $dirs = [];
private $dates = [];
private $iterators = [];
private $contains = [];
private $notContains = [];
private $paths = [];
private $notPaths = [];
private $ignoreUnreadableDirs = false;
private static $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'];
public function __construct()
{
$this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
}
public static function create()
{
return new static();
}
public function directories()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
return $this;
}
public function files()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
return $this;
}
public function depth($level)
{
$this->depths[] = new Comparator\NumberComparator($level);
return $this;
}
public function date($date)
{
$this->dates[] = new Comparator\DateComparator($date);
return $this;
}
public function name($pattern)
{
$this->names[] = $pattern;
return $this;
}
public function notName($pattern)
{
$this->notNames[] = $pattern;
return $this;
}
public function contains($pattern)
{
$this->contains[] = $pattern;
return $this;
}
public function notContains($pattern)
{
$this->notContains[] = $pattern;
return $this;
}
public function path($pattern)
{
$this->paths[] = $pattern;
return $this;
}
public function notPath($pattern)
{
$this->notPaths[] = $pattern;
return $this;
}
public function size($size)
{
$this->sizes[] = new Comparator\NumberComparator($size);
return $this;
}
public function exclude($dirs)
{
$this->exclude = array_merge($this->exclude, (array) $dirs);
return $this;
}
public function ignoreDotFiles($ignoreDotFiles)
{
if ($ignoreDotFiles) {
$this->ignore |= static::IGNORE_DOT_FILES;
} else {
$this->ignore &= ~static::IGNORE_DOT_FILES;
}
return $this;
}
public function ignoreVCS($ignoreVCS)
{
if ($ignoreVCS) {
$this->ignore |= static::IGNORE_VCS_FILES;
} else {
$this->ignore &= ~static::IGNORE_VCS_FILES;
}
return $this;
}
public static function addVCSPattern($pattern)
{
foreach ((array) $pattern as $p) {
self::$vcsPatterns[] = $p;
}
self::$vcsPatterns = array_unique(self::$vcsPatterns);
}
public function sort(\Closure $closure)
{
$this->sort = $closure;
return $this;
}
public function sortByName()
{
$this->sort = Iterator\SortableIterator::SORT_BY_NAME;
return $this;
}
public function sortByType()
{
$this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
return $this;
}
public function sortByAccessedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
return $this;
}
public function sortByChangedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
return $this;
}
public function sortByModifiedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
return $this;
}
public function filter(\Closure $closure)
{
$this->filters[] = $closure;
return $this;
}
public function followLinks()
{
$this->followLinks = true;
return $this;
}
public function ignoreUnreadableDirs($ignore = true)
{
$this->ignoreUnreadableDirs = (bool) $ignore;
return $this;
}
public function in($dirs)
{
$resolvedDirs = [];
foreach ((array) $dirs as $dir) {
if (is_dir($dir)) {
$resolvedDirs[] = $this->normalizeDir($dir);
} elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) {
sort($glob);
$resolvedDirs = array_merge($resolvedDirs, array_map([$this, 'normalizeDir'], $glob));
} else {
throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
}
}
$this->dirs = array_merge($this->dirs, $resolvedDirs);
return $this;
}
public function getIterator()
{
if (0 === \count($this->dirs) && 0 === \count($this->iterators)) {
throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
}
if (1 === \count($this->dirs) && 0 === \count($this->iterators)) {
return $this->searchInDirectory($this->dirs[0]);
}
$iterator = new \AppendIterator();
foreach ($this->dirs as $dir) {
$iterator->append($this->searchInDirectory($dir));
}
foreach ($this->iterators as $it) {
$iterator->append($it);
}
return $iterator;
}
public function append($iterator)
{
if ($iterator instanceof \IteratorAggregate) {
$this->iterators[] = $iterator->getIterator();
} elseif ($iterator instanceof \Iterator) {
$this->iterators[] = $iterator;
} elseif ($iterator instanceof \Traversable || \is_array($iterator)) {
$it = new \ArrayIterator();
foreach ($iterator as $file) {
$it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
}
$this->iterators[] = $it;
} else {
throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
}
return $this;
}
public function hasResults()
{
foreach ($this->getIterator() as $_) {
return true;
}
return false;
}
public function count()
{
return iterator_count($this->getIterator());
}
private function searchInDirectory($dir)
{
$exclude = $this->exclude;
$notPaths = $this->notPaths;
if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
$exclude = array_merge($exclude, self::$vcsPatterns);
}
if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
$notPaths[] = '#(^|/)\..+(/|$)#';
}
$minDepth = 0;
$maxDepth = \PHP_INT_MAX;
foreach ($this->depths as $comparator) {
switch ($comparator->getOperator()) {
case '>':
$minDepth = $comparator->getTarget() + 1;
break;
case '>=':
$minDepth = $comparator->getTarget();
break;
case '<':
$maxDepth = $comparator->getTarget() - 1;
break;
case '<=':
$maxDepth = $comparator->getTarget();
break;
default:
$minDepth = $maxDepth = $comparator->getTarget();
}
}
$flags = \RecursiveDirectoryIterator::SKIP_DOTS;
if ($this->followLinks) {
$flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
}
$iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
if ($exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude);
}
$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) {
$iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
}
if ($this->mode) {
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
}
if ($this->names || $this->notNames) {
$iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
}
if ($this->contains || $this->notContains) {
$iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
}
if ($this->sizes) {
$iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
}
if ($this->dates) {
$iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
}
if ($this->filters) {
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
}
if ($this->paths || $notPaths) {
$iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths);
}
if ($this->sort) {
$iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
$iterator = $iteratorAggregate->getIterator();
}
return $iterator;
}
private function normalizeDir($dir)
{
if ('/' === $dir) {
return $dir;
}
$dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR);
if (preg_match('#^(ssh2\.)?s?ftp://#', $dir)) {
$dir .= '/';
}
return $dir;
}
}
<?php
namespace Symfony\Component\Finder\Exception;
class AccessDeniedException extends \UnexpectedValueException
{
}
<?php
namespace Symfony\Component\Finder\Exception;
interface ExceptionInterface
{
public function getAdapter();
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\RuntimeException;
class InputStream implements \IteratorAggregate
{
private $onEmpty = null;
private $input = [];
private $open = true;
public function onEmpty(callable $onEmpty = null)
{
$this->onEmpty = $onEmpty;
}
public function write($input)
{
if (null === $input) {
return;
}
if ($this->isClosed()) {
throw new RuntimeException(sprintf('"%s" is closed.', static::class));
}
$this->input[] = ProcessUtils::validateInput(__METHOD__, $input);
}
public function close()
{
$this->open = false;
}
public function isClosed()
{
return !$this->open;
}
public function getIterator()
{
$this->open = true;
while ($this->open || $this->input) {
if (!$this->input) {
yield '';
continue;
}
$current = array_shift($this->input);
if ($current instanceof \Iterator) {
foreach ($current as $cur) {
yield $cur;
}
} else {
yield $current;
}
if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
$this->write($onEmpty($this));
}
}
}
}
<?php
namespace Symfony\Component\Process\Pipes;
interface PipesInterface
{
const CHUNK_SIZE = 16384;
public function getDescriptors();
public function getFiles();
public function readAndWrite($blocking, $close = false);
public function areOpen();
public function haveReadSupport();
public function close();
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Process;
class WindowsPipes extends AbstractPipes
{
private $files = [];
private $fileHandles = [];
private $lockHandles = [];
private $readBytes = [
Process::STDOUT => 0,
Process::STDERR => 0,
];
private $haveReadSupport;
public function __construct($input, $haveReadSupport)
{
$this->haveReadSupport = (bool) $haveReadSupport;
if ($this->haveReadSupport) {
$pipes = [
Process::STDOUT => Process::OUT,
Process::STDERR => Process::ERR,
];
$tmpDir = sys_get_temp_dir();
$lastError = 'unknown reason';
set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; });
for ($i = 0;; ++$i) {
foreach ($pipes as $pipe => $name) {
$file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name);
if (!$h = fopen($file.'.lock', 'w')) {
if (file_exists($file.'.lock')) {
continue 2;
}
restore_error_handler();
throw new RuntimeException('A temporary file could not be opened to write the process output: '.$lastError);
}
if (!flock($h, \LOCK_EX | \LOCK_NB)) {
continue 2;
}
if (isset($this->lockHandles[$pipe])) {
flock($this->lockHandles[$pipe], \LOCK_UN);
fclose($this->lockHandles[$pipe]);
}
$this->lockHandles[$pipe] = $h;
if (!fclose(fopen($file, 'w')) || !$h = fopen($file, 'r')) {
flock($this->lockHandles[$pipe], \LOCK_UN);
fclose($this->lockHandles[$pipe]);
unset($this->lockHandles[$pipe]);
continue 2;
}
$this->fileHandles[$pipe] = $h;
$this->files[$pipe] = $file;
}
break;
}
restore_error_handler();
}
parent::__construct($input);
}
public function __destruct()
{
$this->close();
}
public function getDescriptors()
{
if (!$this->haveReadSupport) {
$nullstream = fopen('NUL', 'c');
return [
['pipe', 'r'],
$nullstream,
$nullstream,
];
}
return [
['pipe', 'r'],
['file', 'NUL', 'w'],
['file', 'NUL', 'w'],
];
}
public function getFiles()
{
return $this->files;
}
public function readAndWrite($blocking, $close = false)
{
$this->unblock();
$w = $this->write();
$read = $r = $e = [];
if ($blocking) {
if ($w) {
@stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6);
} elseif ($this->fileHandles) {
usleep(Process::TIMEOUT_PRECISION * 1E6);
}
}
foreach ($this->fileHandles as $type => $fileHandle) {
$data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]);
if (isset($data[0])) {
$this->readBytes[$type] += \strlen($data);
$read[$type] = $data;
}
if ($close) {
ftruncate($fileHandle, 0);
fclose($fileHandle);
flock($this->lockHandles[$type], \LOCK_UN);
fclose($this->lockHandles[$type]);
unset($this->fileHandles[$type], $this->lockHandles[$type]);
}
}
return $read;
}
public function haveReadSupport()
{
return $this->haveReadSupport;
}
public function areOpen()
{
return $this->pipes && $this->fileHandles;
}
public function close()
{
parent::close();
foreach ($this->fileHandles as $type => $handle) {
ftruncate($handle, 0);
fclose($handle);
flock($this->lockHandles[$type], \LOCK_UN);
fclose($this->lockHandles[$type]);
}
$this->fileHandles = $this->lockHandles = [];
}
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Exception\InvalidArgumentException;
abstract class AbstractPipes implements PipesInterface
{
public $pipes = [];
private $inputBuffer = '';
private $input;
private $blocked = true;
private $lastError;
public function __construct($input)
{
if (\is_resource($input) || $input instanceof \Iterator) {
$this->input = $input;
} elseif (\is_string($input)) {
$this->inputBuffer = $input;
} else {
$this->inputBuffer = (string) $input;
}
}
public function close()
{
foreach ($this->pipes as $pipe) {
fclose($pipe);
}
$this->pipes = [];
}
protected function hasSystemCallBeenInterrupted()
{
$lastError = $this->lastError;
$this->lastError = null;
return null !== $lastError && false !== stripos($lastError, 'interrupted system call');
}
protected function unblock()
{
if (!$this->blocked) {
return;
}
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
if (\is_resource($this->input)) {
stream_set_blocking($this->input, 0);
}
$this->blocked = false;
}
protected function write()
{
if (!isset($this->pipes[0])) {
return null;
}
$input = $this->input;
if ($input instanceof \Iterator) {
if (!$input->valid()) {
$input = null;
} elseif (\is_resource($input = $input->current())) {
stream_set_blocking($input, 0);
} elseif (!isset($this->inputBuffer[0])) {
if (!\is_string($input)) {
if (!is_scalar($input)) {
throw new InvalidArgumentException(sprintf('"%s" yielded a value of type "%s", but only scalars and stream resources are supported.', \get_class($this->input), \gettype($input)));
}
$input = (string) $input;
}
$this->inputBuffer = $input;
$this->input->next();
$input = null;
} else {
$input = null;
}
}
$r = $e = [];
$w = [$this->pipes[0]];
if (false === @stream_select($r, $w, $e, 0, 0)) {
return null;
}
foreach ($w as $stdin) {
if (isset($this->inputBuffer[0])) {
$written = fwrite($stdin, $this->inputBuffer);
$this->inputBuffer = substr($this->inputBuffer, $written);
if (isset($this->inputBuffer[0])) {
return [$this->pipes[0]];
}
}
if ($input) {
for (;;) {
$data = fread($input, self::CHUNK_SIZE);
if (!isset($data[0])) {
break;
}
$written = fwrite($stdin, $data);
$data = substr($data, $written);
if (isset($data[0])) {
$this->inputBuffer = $data;
return [$this->pipes[0]];
}
}
if (feof($input)) {
if ($this->input instanceof \Iterator) {
$this->input->next();
} else {
$this->input = null;
}
}
}
}
if (!isset($this->inputBuffer[0]) && !($this->input instanceof \Iterator ? $this->input->valid() : $this->input)) {
$this->input = null;
fclose($this->pipes[0]);
unset($this->pipes[0]);
} elseif (!$w) {
return [$this->pipes[0]];
}
return null;
}
public function handleError($type, $msg)
{
$this->lastError = $msg;
}
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Process;
class UnixPipes extends AbstractPipes
{
private $ttyMode;
private $ptyMode;
private $haveReadSupport;
public function __construct($ttyMode, $ptyMode, $input, $haveReadSupport)
{
$this->ttyMode = (bool) $ttyMode;
$this->ptyMode = (bool) $ptyMode;
$this->haveReadSupport = (bool) $haveReadSupport;
parent::__construct($input);
}
public function __destruct()
{
$this->close();
}
public function getDescriptors()
{
if (!$this->haveReadSupport) {
$nullstream = fopen('/dev/null', 'c');
return [
['pipe', 'r'],
$nullstream,
$nullstream,
];
}
if ($this->ttyMode) {
return [
['file', '/dev/tty', 'r'],
['file', '/dev/tty', 'w'],
['file', '/dev/tty', 'w'],
];
}
if ($this->ptyMode && Process::isPtySupported()) {
return [
['pty'],
['pty'],
['pty'],
];
}
return [
['pipe', 'r'],
['pipe', 'w'],
['pipe', 'w'],
];
}
public function getFiles()
{
return [];
}
public function readAndWrite($blocking, $close = false)
{
$this->unblock();
$w = $this->write();
$read = $e = [];
$r = $this->pipes;
unset($r[0]);
set_error_handler([$this, 'handleError']);
if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
restore_error_handler();
if (!$this->hasSystemCallBeenInterrupted()) {
$this->pipes = [];
}
return $read;
}
restore_error_handler();
foreach ($r as $pipe) {
$read[$type = array_search($pipe, $this->pipes, true)] = '';
do {
$data = @fread($pipe, self::CHUNK_SIZE);
$read[$type] .= $data;
} while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1])));
if (!isset($read[$type][0])) {
unset($read[$type]);
}
if ($close && feof($pipe)) {
fclose($pipe);
unset($this->pipes[$type]);
}
}
return $read;
}
public function haveReadSupport()
{
return $this->haveReadSupport;
}
public function areOpen()
{
return (bool) $this->pipes;
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\RuntimeException;
class PhpProcess extends Process
{
public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = null)
{
$executableFinder = new PhpExecutableFinder();
if (false === $php = $executableFinder->find(false)) {
$php = null;
} else {
$php = array_merge([$php], $executableFinder->findArguments());
}
if ('phpdbg' === \PHP_SAPI) {
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
$php[] = $file;
$script = null;
}
if (null !== $options) {
@trigger_error(sprintf('The $options parameter of the %s constructor is deprecated since Symfony 3.3 and will be removed in 4.0.', __CLASS__), \E_USER_DEPRECATED);
}
parent::__construct($php, $cwd, $env, $script, $timeout, $options);
}
public function setPhpBinary($php)
{
$this->setCommandLine($php);
}
public function start(callable $callback = null)
{
if (null === $this->getCommandLine()) {
throw new RuntimeException('Unable to find the PHP executable.');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
parent::start($callback, $env);
}
}
<?php
namespace Symfony\Component\Process\Exception;
use Symfony\Component\Process\Process;
class ProcessTimedOutException extends RuntimeException
{
const TYPE_GENERAL = 1;
const TYPE_IDLE = 2;
private $process;
private $timeoutType;
public function __construct(Process $process, $timeoutType)
{
$this->process = $process;
$this->timeoutType = $timeoutType;
parent::__construct(sprintf(
'The process "%s" exceeded the timeout of %s seconds.',
$process->getCommandLine(),
$this->getExceededTimeout()
));
}
public function getProcess()
{
return $this->process;
}
public function isGeneralTimeout()
{
return self::TYPE_GENERAL === $this->timeoutType;
}
public function isIdleTimeout()
{
return self::TYPE_IDLE === $this->timeoutType;
}
public function getExceededTimeout()
{
switch ($this->timeoutType) {
case self::TYPE_GENERAL:
return $this->process->getTimeout();
case self::TYPE_IDLE:
return $this->process->getIdleTimeout();
default:
throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
}
}
}
<?php
namespace Symfony\Component\Process\Exception;
use Symfony\Component\Process\Process;
class ProcessFailedException extends RuntimeException
{
private $process;
public function __construct(Process $process)
{
if ($process->isSuccessful()) {
throw new InvalidArgumentException('Expected a failed process, but the given process was successful.');
}
$error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s",
$process->getCommandLine(),
$process->getExitCode(),
$process->getExitCodeText(),
$process->getWorkingDirectory()
);
if (!$process->isOutputDisabled()) {
$error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s",
$process->getOutput(),
$process->getErrorOutput()
);
}
parent::__construct($error);
$this->process = $process;
}
public function getProcess()
{
return $this->process;
}
}
<?php
namespace Symfony\Component\Process\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
class LogicException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\InvalidArgumentException;
class ProcessUtils
{
private function __construct()
{
}
public static function escapeArgument($argument)
{
@trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use a command line array or give env vars to the Process::start/run() method instead.', \E_USER_DEPRECATED);
if ('\\' === \DIRECTORY_SEPARATOR) {
if ('' === $argument) {
return escapeshellarg($argument);
}
$escapedArgument = '';
$quote = false;
foreach (preg_split('/(")/', $argument, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE) as $part) {
if ('"' === $part) {
$escapedArgument .= '\\"';
} elseif (self::isSurroundedBy($part, '%')) {
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else {
if ('\\' === substr($part, -1)) {
$part .= '\\';
}
$quote = true;
$escapedArgument .= $part;
}
}
if ($quote) {
$escapedArgument = '"'.$escapedArgument.'"';
}
return $escapedArgument;
}
return "'".str_replace("'", "'\\''", $argument)."'";
}
public static function validateInput($caller, $input)
{
if (null !== $input) {
if (\is_resource($input)) {
return $input;
}
if (\is_string($input)) {
return $input;
}
if (is_scalar($input)) {
return (string) $input;
}
if ($input instanceof Process) {
return $input->getIterator($input::ITER_SKIP_ERR);
}
if ($input instanceof \Iterator) {
return $input;
}
if ($input instanceof \Traversable) {
return new \IteratorIterator($input);
}
throw new InvalidArgumentException(sprintf('"%s" only accepts strings, Traversable objects or stream resources.', $caller));
}
return $input;
}
private static function isSurroundedBy($arg, $char)
{
return 2 < \strlen($arg) && $char === $arg[0] && $char === $arg[\strlen($arg) - 1];
}
}
<?php
namespace Symfony\Component\Process;
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Use the Process class instead.', ProcessBuilder::class), \E_USER_DEPRECATED);
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
class ProcessBuilder
{
private $arguments;
private $cwd;
private $env = [];
private $input;
private $timeout = 60;
private $options;
private $inheritEnv = true;
private $prefix = [];
private $outputDisabled = false;
public function __construct(array $arguments = [])
{
$this->arguments = $arguments;
}
public static function create(array $arguments = [])
{
return new static($arguments);
}
public function add($argument)
{
$this->arguments[] = $argument;
return $this;
}
public function setPrefix($prefix)
{
$this->prefix = \is_array($prefix) ? $prefix : [$prefix];
return $this;
}
public function setArguments(array $arguments)
{
$this->arguments = $arguments;
return $this;
}
public function setWorkingDirectory($cwd)
{
$this->cwd = $cwd;
return $this;
}
public function inheritEnvironmentVariables($inheritEnv = true)
{
$this->inheritEnv = $inheritEnv;
return $this;
}
public function setEnv($name, $value)
{
$this->env[$name] = $value;
return $this;
}
public function addEnvironmentVariables(array $variables)
{
$this->env = array_replace($this->env, $variables);
return $this;
}
public function setInput($input)
{
$this->input = ProcessUtils::validateInput(__METHOD__, $input);
return $this;
}
public function setTimeout($timeout)
{
if (null === $timeout) {
$this->timeout = null;
return $this;
}
$timeout = (float) $timeout;
if ($timeout < 0) {
throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
$this->timeout = $timeout;
return $this;
}
public function setOption($name, $value)
{
$this->options[$name] = $value;
return $this;
}
public function disableOutput()
{
$this->outputDisabled = true;
return $this;
}
public function enableOutput()
{
$this->outputDisabled = false;
return $this;
}
public function getProcess()
{
if (0 === \count($this->prefix) && 0 === \count($this->arguments)) {
throw new LogicException('You must add() command arguments before calling getProcess().');
}
$arguments = array_merge($this->prefix, $this->arguments);
$process = new Process($arguments, $this->cwd, $this->env, $this->input, $this->timeout, $this->options);
$process->setCommandLine($process->getCommandLine());
if ($this->inheritEnv) {
$process->inheritEnvironmentVariables();
}
if ($this->outputDisabled) {
$process->disableOutput();
}
return $process;
}
}
<?php
namespace Symfony\Component\Process;
/**
@gmail
*/
class PhpExecutableFinder
{
private $executableFinder;
public function __construct()
{
$this->executableFinder = new ExecutableFinder();
}
public function find($includeArgs = true)
{
$args = $this->findArguments();
$args = $includeArgs && $args ? ' '.implode(' ', $args) : '';
if (\defined('HHVM_VERSION')) {
return (getenv('PHP_BINARY') ?: \PHP_BINARY).$args;
}
if (\PHP_BINARY && \in_array(\PHP_SAPI, ['cli', 'cli-server', 'phpdbg'], true)) {
return \PHP_BINARY.$args;
}
if ($php = getenv('PHP_PATH')) {
if (!@is_executable($php)) {
return false;
}
return $php;
}
if ($php = getenv('PHP_PEAR_PHP_BIN')) {
if (@is_executable($php)) {
return $php;
}
}
if (@is_executable($php = \PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php'))) {
return $php;
}
$dirs = [\PHP_BINDIR];
if ('\\' === \DIRECTORY_SEPARATOR) {
$dirs[] = 'C:\xampp\php\\';
}
return $this->executableFinder->find('php', false, $dirs);
}
public function findArguments()
{
$arguments = [];
if (\defined('HHVM_VERSION')) {
$arguments[] = '--php';
} elseif ('phpdbg' === \PHP_SAPI) {
$arguments[] = '-qrr';
}
return $arguments;
}
}
<?php
namespace Symfony\Component\Process;
/**
@gmail
*/
class ExecutableFinder
{
private $suffixes = ['.exe', '.bat', '.cmd', '.com'];
public function setSuffixes(array $suffixes)
{
$this->suffixes = $suffixes;
}
public function addSuffix($suffix)
{
$this->suffixes[] = $suffix;
}
public function find($name, $default = null, array $extraDirs = [])
{
if (ini_get('open_basedir')) {
$searchPath = array_merge(explode(\PATH_SEPARATOR, ini_get('open_basedir')), $extraDirs);
$dirs = [];
foreach ($searchPath as $path) {
if (@is_dir($path)) {
$dirs[] = $path;
} else {
if (basename($path) == $name && @is_executable($path)) {
return $path;
}
}
}
} else {
$dirs = array_merge(
explode(\PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')),
$extraDirs
);
}
$suffixes = [''];
if ('\\' === \DIRECTORY_SEPARATOR) {
$pathExt = getenv('PATHEXT');
$suffixes = array_merge($pathExt ? explode(\PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes);
}
foreach ($suffixes as $suffix) {
foreach ($dirs as $dir) {
if (@is_file($file = $dir.\DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === \DIRECTORY_SEPARATOR || @is_executable($file))) {
return $file;
}
}
}
return $default;
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Pipes\PipesInterface;
use Symfony\Component\Process\Pipes\UnixPipes;
use Symfony\Component\Process\Pipes\WindowsPipes;
/**
@gmail
*/
class Process implements \IteratorAggregate
{
const ERR = 'err';
const OUT = 'out';
const STATUS_READY = 'ready';
const STATUS_STARTED = 'started';
const STATUS_TERMINATED = 'terminated';
const STDIN = 0;
const STDOUT = 1;
const STDERR = 2;
const TIMEOUT_PRECISION = 0.2;
const ITER_NON_BLOCKING = 1;
const ITER_KEEP_OUTPUT = 2;
const ITER_SKIP_OUT = 4;
const ITER_SKIP_ERR = 8;
private $callback;
private $hasCallback = false;
private $commandline;
private $cwd;
private $env;
private $input;
private $starttime;
private $lastOutputTime;
private $timeout;
private $idleTimeout;
private $options = ['suppress_errors' => true];
private $exitcode;
private $fallbackStatus = [];
private $processInformation;
private $outputDisabled = false;
private $stdout;
private $stderr;
private $enhanceWindowsCompatibility = true;
private $enhanceSigchildCompatibility;
private $process;
private $status = self::STATUS_READY;
private $incrementalOutputOffset = 0;
private $incrementalErrorOutputOffset = 0;
private $tty = false;
private $pty;
private $inheritEnv = false;
private $useFileHandles = false;
private $processPipes;
private $latestSignal;
private static $sigchild;
public static $exitCodes = [
0 => 'OK',
1 => 'General error',
2 => 'Misuse of shell builtins',
126 => 'Invoked command cannot execute',
127 => 'Command not found',
128 => 'Invalid exit argument',
129 => 'Hangup',
130 => 'Interrupt',
131 => 'Quit and dump core',
132 => 'Illegal instruction',
133 => 'Trace/breakpoint trap',
134 => 'Process aborted',
135 => 'Bus error: "access to undefined portion of memory object"',
136 => 'Floating point exception: "erroneous arithmetic operation"',
137 => 'Kill (terminate immediately)',
138 => 'User-defined 1',
139 => 'Segmentation violation',
140 => 'User-defined 2',
141 => 'Write to pipe with no one reading',
142 => 'Signal raised by alarm',
143 => 'Termination (request to terminate)',
145 => 'Child process terminated, stopped (or continued*)',
146 => 'Continue if stopped',
147 => 'Stop executing temporarily',
148 => 'Terminal stop signal',
149 => 'Background process attempting to read from tty ("in")',
150 => 'Background process attempting to write to tty ("out")',
151 => 'Urgent data available on socket',
152 => 'CPU time limit exceeded',
153 => 'File size limit exceeded',
154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
155 => 'Profiling timer expired',
157 => 'Pollable event',
159 => 'Bad syscall',
];
public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = null)
{
if (!\function_exists('proc_open')) {
throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
}
$this->commandline = $commandline;
$this->cwd = $cwd;
if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
$this->cwd = getcwd();
}
if (null !== $env) {
$this->setEnv($env);
}
$this->setInput($input);
$this->setTimeout($timeout);
$this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
$this->pty = false;
$this->enhanceSigchildCompatibility = '\\' !== \DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
if (null !== $options) {
@trigger_error(sprintf('The $options parameter of the %s constructor is deprecated since Symfony 3.3 and will be removed in 4.0.', __CLASS__), \E_USER_DEPRECATED);
$this->options = array_replace($this->options, $options);
}
}
public function __destruct()
{
$this->stop(0);
}
public function __clone()
{
$this->resetProcessData();
}
public function run($callback = null)
{
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
$this->start($callback, $env);
return $this->wait();
}
public function mustRun(callable $callback = null)
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
if (0 !== $this->run($callback, $env)) {
throw new ProcessFailedException($this);
}
return $this;
}
public function start(callable $callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running.');
}
if (2 <= \func_num_args()) {
$env = func_get_arg(1);
} else {
if (__CLASS__ !== static::class) {
$r = new \ReflectionMethod($this, __FUNCTION__);
if (__CLASS__ !== $r->getDeclaringClass()->getName() && (2 > $r->getNumberOfParameters() || 'env' !== $r->getParameters()[1]->name)) {
@trigger_error(sprintf('The %s::start() method expects a second "$env" argument since Symfony 3.3. It will be made mandatory in 4.0.', static::class), \E_USER_DEPRECATED);
}
}
$env = null;
}
$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$this->hasCallback = null !== $callback;
$descriptors = $this->getDescriptors();
$inheritEnv = $this->inheritEnv;
if (\is_array($commandline = $this->commandline)) {
$commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline));
if ('\\' !== \DIRECTORY_SEPARATOR) {
$commandline = 'exec '.$commandline;
}
}
if (null === $env) {
$env = $this->env;
} else {
if ($this->env) {
$env += $this->env;
}
$inheritEnv = true;
}
if (null !== $env && $inheritEnv) {
$env += $this->getDefaultEnv();
} elseif (null !== $env) {
@trigger_error('Not inheriting environment variables is deprecated since Symfony 3.3 and will always happen in 4.0. Set "Process::inheritEnvironmentVariables()" to true instead.', \E_USER_DEPRECATED);
} else {
$env = $this->getDefaultEnv();
}
if ('\\' === \DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
$this->options['bypass_shell'] = true;
$commandline = $this->prepareWindowsCommandLine($commandline, $env);
} elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$descriptors[3] = ['pipe', 'w'];
$commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
$commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
$ptsWorkaround = fopen(__FILE__, 'r');
}
if (\defined('HHVM_VERSION')) {
$envPairs = $env;
} else {
$envPairs = [];
foreach ($env as $k => $v) {
if (false !== $v) {
$envPairs[] = $k.'='.$v;
}
}
}
if (!is_dir($this->cwd)) {
@trigger_error('The provided cwd does not exist. Command is currently ran against getcwd(). This behavior is deprecated since Symfony 3.4 and will be removed in 4.0.', \E_USER_DEPRECATED);
}
$this->process = @proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options);
if (!\is_resource($this->process)) {
throw new RuntimeException('Unable to launch a new process.');
}
$this->status = self::STATUS_STARTED;
if (isset($descriptors[3])) {
$this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
}
if ($this->tty) {
return;
}
$this->updateStatus(false);
$this->checkTimeout();
}
public function restart(callable $callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running.');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
$process = clone $this;
$process->start($callback, $env);
return $process;
}
public function wait(callable $callback = null)
{
$this->requireProcessIsStarted(__FUNCTION__);
$this->updateStatus(false);
if (null !== $callback) {
if (!$this->processPipes->haveReadSupport()) {
$this->stop(0);
throw new \LogicException('Pass the callback to the Process::start method or enableOutput to use a callback with Process::wait.');
}
$this->callback = $this->buildCallback($callback);
}
do {
$this->checkTimeout();
$running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
} while ($running);
while ($this->isRunning()) {
$this->checkTimeout();
usleep(1000);
}
if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
}
return $this->exitcode;
}
public function getPid()
{
return $this->isRunning() ? $this->processInformation['pid'] : null;
}
public function signal($signal)
{
$this->doSignal($signal, true);
return $this;
}
public function disableOutput()
{
if ($this->isRunning()) {
throw new RuntimeException('Disabling output while the process is running is not possible.');
}
if (null !== $this->idleTimeout) {
throw new LogicException('Output can not be disabled while an idle timeout is set.');
}
$this->outputDisabled = true;
return $this;
}
public function enableOutput()
{
if ($this->isRunning()) {
throw new RuntimeException('Enabling output while the process is running is not possible.');
}
$this->outputDisabled = false;
return $this;
}
public function isOutputDisabled()
{
return $this->outputDisabled;
}
public function getOutput()
{
$this->readPipesForOutput(__FUNCTION__);
if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
return '';
}
return $ret;
}
public function getIncrementalOutput()
{
$this->readPipesForOutput(__FUNCTION__);
$latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
$this->incrementalOutputOffset = ftell($this->stdout);
if (false === $latest) {
return '';
}
return $latest;
}
public function getIterator($flags = 0)
{
$this->readPipesForOutput(__FUNCTION__, false);
$clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
$blocking = !(self::ITER_NON_BLOCKING & $flags);
$yieldOut = !(self::ITER_SKIP_OUT & $flags);
$yieldErr = !(self::ITER_SKIP_ERR & $flags);
while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
if ($yieldOut) {
$out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
if (isset($out[0])) {
if ($clearOutput) {
$this->clearOutput();
} else {
$this->incrementalOutputOffset = ftell($this->stdout);
}
yield self::OUT => $out;
}
}
if ($yieldErr) {
$err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
if (isset($err[0])) {
if ($clearOutput) {
$this->clearErrorOutput();
} else {
$this->incrementalErrorOutputOffset = ftell($this->stderr);
}
yield self::ERR => $err;
}
}
if (!$blocking && !isset($out[0]) && !isset($err[0])) {
yield self::OUT => '';
}
$this->checkTimeout();
$this->readPipesForOutput(__FUNCTION__, $blocking);
}
}
public function clearOutput()
{
ftruncate($this->stdout, 0);
fseek($this->stdout, 0);
$this->incrementalOutputOffset = 0;
return $this;
}
public function getErrorOutput()
{
$this->readPipesForOutput(__FUNCTION__);
if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
return '';
}
return $ret;
}
public function getIncrementalErrorOutput()
{
$this->readPipesForOutput(__FUNCTION__);
$latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
$this->incrementalErrorOutputOffset = ftell($this->stderr);
if (false === $latest) {
return '';
}
return $latest;
}
public function clearErrorOutput()
{
ftruncate($this->stderr, 0);
fseek($this->stderr, 0);
$this->incrementalErrorOutputOffset = 0;
return $this;
}
public function getExitCode()
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$this->updateStatus(false);
return $this->exitcode;
}
public function getExitCodeText()
{
if (null === $exitcode = $this->getExitCode()) {
return null;
}
return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
}
public function isSuccessful()
{
return 0 === $this->getExitCode();
}
public function hasBeenSignaled()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
return $this->processInformation['signaled'];
}
public function getTermSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
return $this->processInformation['termsig'];
}
public function hasBeenStopped()
{
$this->requireProcessIsTerminated(__FUNCTION__);
return $this->processInformation['stopped'];
}
public function getStopSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
return $this->processInformation['stopsig'];
}
public function isRunning()
{
if (self::STATUS_STARTED !== $this->status) {
return false;
}
$this->updateStatus(false);
return $this->processInformation['running'];
}
public function isStarted()
{
return self::STATUS_READY != $this->status;
}
public function isTerminated()
{
$this->updateStatus(false);
return self::STATUS_TERMINATED == $this->status;
}
public function getStatus()
{
$this->updateStatus(false);
return $this->status;
}
public function stop($timeout = 10, $signal = null)
{
$timeoutMicro = microtime(true) + $timeout;
if ($this->isRunning()) {
$this->doSignal(15, false);
do {
usleep(1000);
} while ($this->isRunning() && microtime(true) < $timeoutMicro);
if ($this->isRunning()) {
$this->doSignal($signal ?: 9, false);
}
}
if ($this->isRunning()) {
if (isset($this->fallbackStatus['pid'])) {
unset($this->fallbackStatus['pid']);
return $this->stop(0, $signal);
}
$this->close();
}
return $this->exitcode;
}
public function addOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stdout, 0, \SEEK_END);
fwrite($this->stdout, $line);
fseek($this->stdout, $this->incrementalOutputOffset);
}
public function addErrorOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stderr, 0, \SEEK_END);
fwrite($this->stderr, $line);
fseek($this->stderr, $this->incrementalErrorOutputOffset);
}
public function getCommandLine()
{
return \is_array($this->commandline) ? implode(' ', array_map([$this, 'escapeArgument'], $this->commandline)) : $this->commandline;
}
public function setCommandLine($commandline)
{
$this->commandline = $commandline;
return $this;
}
public function getTimeout()
{
return $this->timeout;
}
public function getIdleTimeout()
{
return $this->idleTimeout;
}
public function setTimeout($timeout)
{
$this->timeout = $this->validateTimeout($timeout);
return $this;
}
public function setIdleTimeout($timeout)
{
if (null !== $timeout && $this->outputDisabled) {
throw new LogicException('Idle timeout can not be set while the output is disabled.');
}
$this->idleTimeout = $this->validateTimeout($timeout);
return $this;
}
public function setTty($tty)
{
if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
throw new RuntimeException('TTY mode is not supported on Windows platform.');
}
if ($tty) {
static $isTtySupported;
if (null === $isTtySupported) {
$isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
}
if (!$isTtySupported) {
throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
}
}
$this->tty = (bool) $tty;
return $this;
}
public function isTty()
{
return $this->tty;
}
public function setPty($bool)
{
$this->pty = (bool) $bool;
return $this;
}
public function isPty()
{
return $this->pty;
}
public function getWorkingDirectory()
{
if (null === $this->cwd) {
return getcwd() ?: null;
}
return $this->cwd;
}
public function setWorkingDirectory($cwd)
{
$this->cwd = $cwd;
return $this;
}
public function getEnv()
{
return $this->env;
}
public function setEnv(array $env)
{
$env = array_filter($env, function ($value) {
return !\is_array($value);
});
$this->env = $env;
return $this;
}
public function getInput()
{
return $this->input;
}
public function setInput($input)
{
if ($this->isRunning()) {
throw new LogicException('Input can not be set while the process is running.');
}
$this->input = ProcessUtils::validateInput(__METHOD__, $input);
return $this;
}
public function getOptions()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0.', __METHOD__), \E_USER_DEPRECATED);
return $this->options;
}
public function setOptions(array $options)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0.', __METHOD__), \E_USER_DEPRECATED);
$this->options = $options;
return $this;
}
public function getEnhanceWindowsCompatibility()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Enhanced Windows compatibility will always be enabled.', __METHOD__), \E_USER_DEPRECATED);
return $this->enhanceWindowsCompatibility;
}
public function setEnhanceWindowsCompatibility($enhance)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Enhanced Windows compatibility will always be enabled.', __METHOD__), \E_USER_DEPRECATED);
$this->enhanceWindowsCompatibility = (bool) $enhance;
return $this;
}
public function getEnhanceSigchildCompatibility()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Sigchild compatibility will always be enabled.', __METHOD__), \E_USER_DEPRECATED);
return $this->enhanceSigchildCompatibility;
}
public function setEnhanceSigchildCompatibility($enhance)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Sigchild compatibility will always be enabled.', __METHOD__), \E_USER_DEPRECATED);
$this->enhanceSigchildCompatibility = (bool) $enhance;
return $this;
}
public function inheritEnvironmentVariables($inheritEnv = true)
{
if (!$inheritEnv) {
@trigger_error('Not inheriting environment variables is deprecated since Symfony 3.3 and will always happen in 4.0. Set "Process::inheritEnvironmentVariables()" to true instead.', \E_USER_DEPRECATED);
}
$this->inheritEnv = (bool) $inheritEnv;
return $this;
}
public function areEnvironmentVariablesInherited()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Environment variables will always be inherited.', __METHOD__), \E_USER_DEPRECATED);
return $this->inheritEnv;
}
public function checkTimeout()
{
if (self::STATUS_STARTED !== $this->status) {
return;
}
if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
$this->stop(0);
throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
}
if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
$this->stop(0);
throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
}
}
public static function isPtySupported()
{
static $result;
if (null !== $result) {
return $result;
}
if ('\\' === \DIRECTORY_SEPARATOR) {
return $result = false;
}
return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
}
private function getDescriptors()
{
if ($this->input instanceof \Iterator) {
$this->input->rewind();
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
} else {
$this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
}
return $this->processPipes->getDescriptors();
}
protected function buildCallback(callable $callback = null)
{
if ($this->outputDisabled) {
return function ($type, $data) use ($callback) {
if (null !== $callback) {
\call_user_func($callback, $type, $data);
}
};
}
$out = self::OUT;
return function ($type, $data) use ($callback, $out) {
if ($out == $type) {
$this->addOutput($data);
} else {
$this->addErrorOutput($data);
}
if (null !== $callback) {
\call_user_func($callback, $type, $data);
}
};
}
protected function updateStatus($blocking)
{
if (self::STATUS_STARTED !== $this->status) {
return;
}
$this->processInformation = proc_get_status($this->process);
$running = $this->processInformation['running'];
$this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$this->processInformation = $this->fallbackStatus + $this->processInformation;
}
if (!$running) {
$this->close();
}
}
protected function isSigchildEnabled()
{
if (null !== self::$sigchild) {
return self::$sigchild;
}
if (!\function_exists('phpinfo') || \defined('HHVM_VERSION')) {
return self::$sigchild = false;
}
ob_start();
phpinfo(\INFO_GENERAL);
return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
}
private function readPipesForOutput($caller, $blocking = false)
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
}
$this->requireProcessIsStarted($caller);
$this->updateStatus($blocking);
}
private function validateTimeout($timeout)
{
$timeout = (float) $timeout;
if (0.0 === $timeout) {
$timeout = null;
} elseif ($timeout < 0) {
throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
return $timeout;
}
private function readPipes($blocking, $close)
{
$result = $this->processPipes->readAndWrite($blocking, $close);
$callback = $this->callback;
foreach ($result as $type => $data) {
if (3 !== $type) {
$callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
} elseif (!isset($this->fallbackStatus['signaled'])) {
$this->fallbackStatus['exitcode'] = (int) $data;
}
}
}
private function close()
{
$this->processPipes->close();
if (\is_resource($this->process)) {
proc_close($this->process);
}
$this->exitcode = $this->processInformation['exitcode'];
$this->status = self::STATUS_TERMINATED;
if (-1 === $this->exitcode) {
if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
$this->exitcode = 128 + $this->processInformation['termsig'];
} elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$this->processInformation['signaled'] = true;
$this->processInformation['termsig'] = -1;
}
}
$this->callback = null;
return $this->exitcode;
}
private function resetProcessData()
{
$this->starttime = null;
$this->callback = null;
$this->exitcode = null;
$this->fallbackStatus = [];
$this->processInformation = null;
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;
$this->incrementalOutputOffset = 0;
$this->incrementalErrorOutputOffset = 0;
}
private function doSignal($signal, $throwException)
{
if (null === $pid = $this->getPid()) {
if ($throwException) {
throw new LogicException('Can not send signal on a non running process.');
}
return false;
}
if ('\\' === \DIRECTORY_SEPARATOR) {
exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
if ($exitCode && $this->isRunning()) {
if ($throwException) {
throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
}
return false;
}
} else {
if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
$ok = @proc_terminate($this->process, $signal);
} elseif (\function_exists('posix_kill')) {
$ok = @posix_kill($pid, $signal);
} elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
$ok = false === fgets($pipes[2]);
}
if (!$ok) {
if ($throwException) {
throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
}
return false;
}
}
$this->latestSignal = (int) $signal;
$this->fallbackStatus['signaled'] = true;
$this->fallbackStatus['exitcode'] = -1;
$this->fallbackStatus['termsig'] = $this->latestSignal;
return true;
}
private function prepareWindowsCommandLine($cmd, array &$env)
{
$uid = uniqid('', true);
$varCount = 0;
$varCache = [];
$cmd = preg_replace_callback(
'/"(?:(
[^"%!^]*+
(?:
(?: !LF! | "(?:\^[%!^])?+" )
[^"%!^]*+
)++
) | [^"]*+ )"/x',
function ($m) use (&$env, &$varCache, &$varCount, $uid) {
if (!isset($m[1])) {
return $m[0];
}
if (isset($varCache[$m[0]])) {
return $varCache[$m[0]];
}
if (false !== strpos($value = $m[1], "\0")) {
$value = str_replace("\0", '?', $value);
}
if (false === strpbrk($value, "\"%!\n")) {
return '"'.$value.'"';
}
$value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value);
$value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
$var = $uid.++$varCount;
$env[$var] = $value;
return $varCache[$m[0]] = '!'.$var.'!';
},
$cmd
);
$cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
foreach ($this->processPipes->getFiles() as $offset => $filename) {
$cmd .= ' '.$offset.'>"'.$filename.'"';
}
return $cmd;
}
private function requireProcessIsStarted($functionName)
{
if (!$this->isStarted()) {
throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName));
}
}
private function requireProcessIsTerminated($functionName)
{
if (!$this->isTerminated()) {
throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName));
}
}
private function escapeArgument($argument)
{
if ('\\' !== \DIRECTORY_SEPARATOR) {
return "'".str_replace("'", "'\\''", $argument)."'";
}
if ('' === $argument = (string) $argument) {
return '""';
}
if (false !== strpos($argument, "\0")) {
$argument = str_replace("\0", '?', $argument);
}
if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
return $argument;
}
$argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
}
private function getDefaultEnv()
{
$env = [];
foreach ($_SERVER as $k => $v) {
if (\is_string($v) && false !== $v = getenv($k)) {
$env[$k] = $v;
}
}
foreach ($_ENV as $k => $v) {
if (\is_string($v)) {
$env[$k] = $v;
}
}
return $env;
}
}
<?php
use Symfony\Polyfill\Php70 as p;
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('PHP_INT_MIN')) {
define('PHP_INT_MIN', ~PHP_INT_MAX);
}
if (!function_exists('intdiv')) {
function intdiv($num1, $num2) { return p\Php70::intdiv($num1, $num2); }
}
if (!function_exists('preg_replace_callback_array')) {
function preg_replace_callback_array(array $pattern, $subject, $limit = -1, &$count = 0, $flags = null) { return p\Php70::preg_replace_callback_array($pattern, $subject, $limit, $count); }
}
if (!function_exists('error_clear_last')) {
function error_clear_last() { return p\Php70::error_clear_last(); }
}
<?php
namespace Symfony\Polyfill\Php70;
final class Php70
{
public static function intdiv($dividend, $divisor)
{
$dividend = self::intArg($dividend, __FUNCTION__, 1);
$divisor = self::intArg($divisor, __FUNCTION__, 2);
if (0 === $divisor) {
throw new \DivisionByZeroError('Division by zero');
}
if (-1 === $divisor && ~PHP_INT_MAX === $dividend) {
throw new \ArithmeticError('Division of PHP_INT_MIN by -1 is not an integer');
}
return ($dividend - ($dividend % $divisor)) / $divisor;
}
public static function preg_replace_callback_array(array $patterns, $subject, $limit = -1, &$count = 0)
{
$count = 0;
$result = (string) $subject;
if (0 === $limit = self::intArg($limit, __FUNCTION__, 3)) {
return $result;
}
foreach ($patterns as $pattern => $callback) {
$result = preg_replace_callback($pattern, $callback, $result, $limit, $c);
$count += $c;
}
return $result;
}
public static function error_clear_last()
{
static $handler;
if (!$handler) {
$handler = function () { return false; };
}
set_error_handler($handler);
@trigger_error('');
restore_error_handler();
}
private static function intArg($value, $caller, $pos)
{
if (\is_int($value)) {
return $value;
}
if (!\is_numeric($value) || PHP_INT_MAX <= ($value += 0) || ~PHP_INT_MAX >= $value) {
throw new \TypeError(sprintf('%s() expects parameter %d to be integer, %s given', $caller, $pos, \gettype($value)));
}
return (int) $value;
}
}
<?php
class DivisionByZeroError extends Error
{
}
<?php
class ArithmeticError extends Error
{
}
<?php
class ParseError extends Error
{
}
<?php
class AssertionError extends Error
{
}
<?php
interface SessionUpdateTimestampHandlerInterface
{
public function validateId($key);
public function updateTimestamp($key, $val);
}
<?php
class TypeError extends Error
{
}
<?php
class Error extends Exception
{
}
<?php
namespace Symfony\Component\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\DebugFormatterHelper;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputAwareInterface;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class Application
{
private $commands = [];
private $wantHelps = false;
private $runningCommand;
private $name;
private $version;
private $commandLoader;
private $catchExceptions = true;
private $autoExit = true;
private $definition;
private $helperSet;
private $dispatcher;
private $terminal;
private $defaultCommand;
private $singleCommand = false;
private $initialized;
public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
{
$this->name = $name;
$this->version = $version;
$this->terminal = new Terminal();
$this->defaultCommand = 'list';
}
public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function setCommandLoader(CommandLoaderInterface $commandLoader)
{
$this->commandLoader = $commandLoader;
}
public function run(InputInterface $input = null, OutputInterface $output = null)
{
putenv('LINES='.$this->terminal->getHeight());
putenv('COLUMNS='.$this->terminal->getWidth());
if (null === $input) {
$input = new ArgvInput();
}
if (null === $output) {
$output = new ConsoleOutput();
}
$renderException = function ($e) use ($output) {
if (!$e instanceof \Exception) {
$e = class_exists(FatalThrowableError::class) ? new FatalThrowableError($e) : new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
}
if ($output instanceof ConsoleOutputInterface) {
$this->renderException($e, $output->getErrorOutput());
} else {
$this->renderException($e, $output);
}
};
if ($phpHandler = set_exception_handler($renderException)) {
restore_exception_handler();
if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) {
$debugHandler = true;
} elseif ($debugHandler = $phpHandler[0]->setExceptionHandler($renderException)) {
$phpHandler[0]->setExceptionHandler($debugHandler);
}
}
if (null !== $this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
@trigger_error(sprintf('The "ConsoleEvents::EXCEPTION" event is deprecated since Symfony 3.3 and will be removed in 4.0. Listen to the "ConsoleEvents::ERROR" event instead.'), \E_USER_DEPRECATED);
}
$this->configureIO($input, $output);
try {
$exitCode = $this->doRun($input, $output);
} catch (\Exception $e) {
if (!$this->catchExceptions) {
throw $e;
}
$renderException($e);
$exitCode = $e->getCode();
if (is_numeric($exitCode)) {
$exitCode = (int) $exitCode;
if (0 === $exitCode) {
$exitCode = 1;
}
} else {
$exitCode = 1;
}
} finally {
if (!$phpHandler) {
if (set_exception_handler($renderException) === $renderException) {
restore_exception_handler();
}
restore_exception_handler();
} elseif (!$debugHandler) {
$finalHandler = $phpHandler[0]->setExceptionHandler(null);
if ($finalHandler !== $renderException) {
$phpHandler[0]->setExceptionHandler($finalHandler);
}
}
}
if ($this->autoExit) {
if ($exitCode > 255) {
$exitCode = 255;
}
exit($exitCode);
}
return $exitCode;
}
public function doRun(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(['--version', '-V'], true)) {
$output->writeln($this->getLongVersion());
return 0;
}
try {
$input->bind($this->getDefinition());
} catch (ExceptionInterface $e) {
}
$name = $this->getCommandName($input);
if (true === $input->hasParameterOption(['--help', '-h'], true)) {
if (!$name) {
$name = 'help';
$input = new ArrayInput(['command_name' => $this->defaultCommand]);
} else {
$this->wantHelps = true;
}
}
if (!$name) {
$name = $this->defaultCommand;
$definition = $this->getDefinition();
$definition->setArguments(array_merge(
$definition->getArguments(),
[
'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
]
));
}
try {
$e = $this->runningCommand = null;
$command = $this->find($name);
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
if (null !== $e) {
if (null !== $this->dispatcher) {
$event = new ConsoleErrorEvent($input, $output, $e);
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
$e = $event->getError();
if (0 === $event->getExitCode()) {
return 0;
}
}
throw $e;
}
$this->runningCommand = $command;
$exitCode = $this->doRunCommand($command, $input, $output);
$this->runningCommand = null;
return $exitCode;
}
public function setHelperSet(HelperSet $helperSet)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
if (!$this->helperSet) {
$this->helperSet = $this->getDefaultHelperSet();
}
return $this->helperSet;
}
public function setDefinition(InputDefinition $definition)
{
$this->definition = $definition;
}
public function getDefinition()
{
if (!$this->definition) {
$this->definition = $this->getDefaultInputDefinition();
}
if ($this->singleCommand) {
$inputDefinition = $this->definition;
$inputDefinition->setArguments();
return $inputDefinition;
}
return $this->definition;
}
public function getHelp()
{
return $this->getLongVersion();
}
public function areExceptionsCaught()
{
return $this->catchExceptions;
}
public function setCatchExceptions($boolean)
{
$this->catchExceptions = (bool) $boolean;
}
public function isAutoExitEnabled()
{
return $this->autoExit;
}
public function setAutoExit($boolean)
{
$this->autoExit = (bool) $boolean;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getVersion()
{
return $this->version;
}
public function setVersion($version)
{
$this->version = $version;
}
public function getLongVersion()
{
if ('UNKNOWN' !== $this->getName()) {
if ('UNKNOWN' !== $this->getVersion()) {
return sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion());
}
return $this->getName();
}
return 'Console Tool';
}
public function register($name)
{
return $this->add(new Command($name));
}
public function addCommands(array $commands)
{
foreach ($commands as $command) {
$this->add($command);
}
}
public function add(Command $command)
{
$this->init();
$command->setApplication($this);
if (!$command->isEnabled()) {
$command->setApplication(null);
return null;
}
$command->getDefinition();
if (!$command->getName()) {
throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command)));
}
$this->commands[$command->getName()] = $command;
foreach ($command->getAliases() as $alias) {
$this->commands[$alias] = $command;
}
return $command;
}
public function get($name)
{
$this->init();
if (!$this->has($name)) {
throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
}
if (!isset($this->commands[$name])) {
throw new CommandNotFoundException(sprintf('The "%s" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".', $name));
}
$command = $this->commands[$name];
if ($this->wantHelps) {
$this->wantHelps = false;
$helpCommand = $this->get('help');
$helpCommand->setCommand($command);
return $helpCommand;
}
return $command;
}
public function has($name)
{
$this->init();
return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name)));
}
public function getNamespaces()
{
$namespaces = [];
foreach ($this->all() as $command) {
if ($command->isHidden()) {
continue;
}
$namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
foreach ($command->getAliases() as $alias) {
$namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
}
}
return array_values(array_unique(array_filter($namespaces)));
}
public function findNamespace($namespace)
{
$allNamespaces = $this->getNamespaces();
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
$namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
if (empty($namespaces)) {
$message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
if (1 == \count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
$message .= implode("\n ", $alternatives);
}
throw new CommandNotFoundException($message, $alternatives);
}
$exact = \in_array($namespace, $namespaces, true);
if (\count($namespaces) > 1 && !$exact) {
throw new CommandNotFoundException(sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
}
return $exact ? $namespace : reset($namespaces);
}
public function find($name)
{
$this->init();
$aliases = [];
foreach ($this->commands as $command) {
foreach ($command->getAliases() as $alias) {
if (!$this->has($alias)) {
$this->commands[$alias] = $command;
}
}
}
if ($this->has($name)) {
return $this->get($name);
}
$allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
$commands = preg_grep('{^'.$expr.'}', $allCommands);
if (empty($commands)) {
$commands = preg_grep('{^'.$expr.'}i', $allCommands);
}
if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
if (false !== $pos = strrpos($name, ':')) {
$this->findNamespace(substr($name, 0, $pos));
}
$message = sprintf('Command "%s" is not defined.', $name);
if ($alternatives = $this->findAlternatives($name, $allCommands)) {
$alternatives = array_filter($alternatives, function ($name) {
return !$this->get($name)->isHidden();
});
if (1 == \count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
$message .= implode("\n ", $alternatives);
}
throw new CommandNotFoundException($message, array_values($alternatives));
}
if (\count($commands) > 1) {
$commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
$commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) {
if (!$commandList[$nameOrAlias] instanceof Command) {
$commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
}
$commandName = $commandList[$nameOrAlias]->getName();
$aliases[$nameOrAlias] = $commandName;
return $commandName === $nameOrAlias || !\in_array($commandName, $commands);
}));
}
$exact = \in_array($name, $commands, true) || isset($aliases[$name]);
if (\count($commands) > 1 && !$exact) {
$usableWidth = $this->terminal->getWidth() - 10;
$abbrevs = array_values($commands);
$maxLen = 0;
foreach ($abbrevs as $abbrev) {
$maxLen = max(Helper::strlen($abbrev), $maxLen);
}
$abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) {
if ($commandList[$cmd]->isHidden()) {
return false;
}
$abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
}, array_values($commands));
$suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs));
throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands));
}
return $this->get($exact ? $name : reset($commands));
}
public function all($namespace = null)
{
$this->init();
if (null === $namespace) {
if (!$this->commandLoader) {
return $this->commands;
}
$commands = $this->commands;
foreach ($this->commandLoader->getNames() as $name) {
if (!isset($commands[$name]) && $this->has($name)) {
$commands[$name] = $this->get($name);
}
}
return $commands;
}
$commands = [];
foreach ($this->commands as $name => $command) {
if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
$commands[$name] = $command;
}
}
if ($this->commandLoader) {
foreach ($this->commandLoader->getNames() as $name) {
if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
$commands[$name] = $this->get($name);
}
}
}
return $commands;
}
public static function getAbbreviations($names)
{
$abbrevs = [];
foreach ($names as $name) {
for ($len = \strlen($name); $len > 0; --$len) {
$abbrev = substr($name, 0, $len);
$abbrevs[$abbrev][] = $name;
}
}
return $abbrevs;
}
public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$this->doRenderException($e, $output);
if (null !== $this->runningCommand) {
$output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
}
protected function doRenderException(\Exception $e, OutputInterface $output)
{
do {
$message = trim($e->getMessage());
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
$len = Helper::strlen($title);
} else {
$len = 0;
}
$width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX;
if (\defined('HHVM_VERSION') && $width > 1 << 31) {
$width = 1 << 31;
}
$lines = [];
foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
$lineLength = Helper::strlen($line) + 4;
$lines[] = [$line, $lineLength];
$len = max($lineLength, $len);
}
}
$messages = [];
if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$messages[] = sprintf('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
}
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
}
foreach ($lines as $line) {
$messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
}
$messages[] = $emptyLine;
$messages[] = '';
$output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
$trace = $e->getTrace();
array_unshift($trace, [
'function' => '',
'file' => $e->getFile() ?: 'n/a',
'line' => $e->getLine() ?: 'n/a',
'args' => [],
]);
for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = isset($trace[$i]['function']) ? $trace[$i]['function'] : '';
$file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
$output->writeln(sprintf(' %s%s at <info>%s:%s</info>', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET);
}
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} while ($e = $e->getPrevious());
}
protected function getTerminalWidth()
{
@trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->terminal->getWidth();
}
protected function getTerminalHeight()
{
@trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->terminal->getHeight();
}
public function getTerminalDimensions()
{
@trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), \E_USER_DEPRECATED);
return [$this->terminal->getWidth(), $this->terminal->getHeight()];
}
public function setTerminalDimensions($width, $height)
{
@trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Set the COLUMNS and LINES env vars instead.', __METHOD__), \E_USER_DEPRECATED);
putenv('COLUMNS='.$width);
putenv('LINES='.$height);
return $this;
}
protected function configureIO(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(['--ansi'], true)) {
$output->setDecorated(true);
} elseif (true === $input->hasParameterOption(['--no-ansi'], true)) {
$output->setDecorated(false);
}
if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) {
$input->setInteractive(false);
} elseif (\function_exists('posix_isatty')) {
$inputStream = null;
if ($input instanceof StreamableInputInterface) {
$inputStream = $input->getStream();
}
if (!$inputStream && $this->getHelperSet()->has('question')) {
$inputStream = $this->getHelperSet()->get('question')->getInputStream(false);
}
if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
$input->setInteractive(false);
}
}
switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) {
case -1: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break;
case 1: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break;
case 2: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break;
case 3: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break;
default: $shellVerbosity = 0; break;
}
if (true === $input->hasParameterOption(['--quiet', '-q'], true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
$shellVerbosity = -1;
} else {
if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
$shellVerbosity = 3;
} elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
$shellVerbosity = 2;
} elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
$shellVerbosity = 1;
}
}
if (-1 === $shellVerbosity) {
$input->setInteractive(false);
}
putenv('SHELL_VERBOSITY='.$shellVerbosity);
$_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
$_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
}
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
{
foreach ($command->getHelperSet() as $helper) {
if ($helper instanceof InputAwareInterface) {
$helper->setInput($input);
}
}
if (null === $this->dispatcher) {
return $command->run($input, $output);
}
try {
$command->mergeApplicationDefinition();
$input->bind($command->getDefinition());
} catch (ExceptionInterface $e) {
}
$event = new ConsoleCommandEvent($command, $input, $output);
$e = null;
try {
$this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
if ($event->commandShouldRun()) {
$exitCode = $command->run($input, $output);
} else {
$exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
}
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
if (null !== $e) {
if ($this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
$x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
$event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
$this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
if ($x !== $event->getException()) {
$e = $event->getException();
}
}
$event = new ConsoleErrorEvent($input, $output, $e, $command);
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
$e = $event->getError();
if (0 === $exitCode = $event->getExitCode()) {
$e = null;
}
}
$event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
if (null !== $e) {
throw $e;
}
return $event->getExitCode();
}
protected function getCommandName(InputInterface $input)
{
return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
}
protected function getDefaultInputDefinition()
{
return new InputDefinition([
new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
]);
}
protected function getDefaultCommands()
{
return [new HelpCommand(), new ListCommand()];
}
protected function getDefaultHelperSet()
{
return new HelperSet([
new FormatterHelper(),
new DebugFormatterHelper(),
new ProcessHelper(),
new QuestionHelper(),
]);
}
private function getAbbreviationSuggestions($abbrevs)
{
return ' '.implode("\n ", $abbrevs);
}
public function extractNamespace($name, $limit = null)
{
$parts = explode(':', $name, -1);
return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
}
private function findAlternatives($name, $collection)
{
$threshold = 1e3;
$alternatives = [];
$collectionParts = [];
foreach ($collection as $item) {
$collectionParts[$item] = explode(':', $item);
}
foreach (explode(':', $name) as $i => $subname) {
foreach ($collectionParts as $collectionName => $parts) {
$exists = isset($alternatives[$collectionName]);
if (!isset($parts[$i]) && $exists) {
$alternatives[$collectionName] += $threshold;
continue;
} elseif (!isset($parts[$i])) {
continue;
}
$lev = levenshtein($subname, $parts[$i]);
if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
$alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
$alternatives[$collectionName] += $threshold;
}
}
}
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
$alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);
return array_keys($alternatives);
}
public function setDefaultCommand($commandName, $isSingleCommand = false)
{
$this->defaultCommand = $commandName;
if ($isSingleCommand) {
$this->find($commandName);
$this->singleCommand = true;
}
return $this;
}
public function isSingleCommand()
{
return $this->singleCommand;
}
private function splitStringByWidth($string, $width)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return str_split($string, $width);
}
$utf8String = mb_convert_encoding($string, 'utf8', $encoding);
$lines = [];
$line = '';
foreach (preg_split('//u', $utf8String) as $char) {
if (mb_strwidth($line.$char, 'utf8') <= $width) {
$line .= $char;
continue;
}
$lines[] = str_pad($line, $width);
$line = $char;
}
$lines[] = \count($lines) ? str_pad($line, $width) : $line;
mb_convert_variables($encoding, 'utf8', $lines);
return $lines;
}
private function extractAllNamespaces($name)
{
$parts = explode(':', $name, -1);
$namespaces = [];
foreach ($parts as $part) {
if (\count($namespaces)) {
$namespaces[] = end($namespaces).':'.$part;
} else {
$namespaces[] = $part;
}
}
return $namespaces;
}
private function init()
{
if ($this->initialized) {
return;
}
$this->initialized = true;
foreach ($this->getDefaultCommands() as $command) {
$this->add($command);
}
}
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatterStyleStack
{
private $styles;
private $emptyStyle;
public function __construct(OutputFormatterStyleInterface $emptyStyle = null)
{
$this->emptyStyle = $emptyStyle ?: new OutputFormatterStyle();
$this->reset();
}
public function reset()
{
$this->styles = [];
}
public function push(OutputFormatterStyleInterface $style)
{
$this->styles[] = $style;
}
public function pop(OutputFormatterStyleInterface $style = null)
{
if (empty($this->styles)) {
return $this->emptyStyle;
}
if (null === $style) {
return array_pop($this->styles);
}
foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
if ($style->apply('') === $stackedStyle->apply('')) {
$this->styles = \array_slice($this->styles, 0, $index);
return $stackedStyle;
}
}
throw new InvalidArgumentException('Incorrectly nested style tag found.');
}
public function getCurrent()
{
if (empty($this->styles)) {
return $this->emptyStyle;
}
return $this->styles[\count($this->styles) - 1];
}
public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle)
{
$this->emptyStyle = $emptyStyle;
return $this;
}
public function getEmptyStyle()
{
return $this->emptyStyle;
}
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatterStyle implements OutputFormatterStyleInterface
{
private static $availableForegroundColors = [
'black' => ['set' => 30, 'unset' => 39],
'red' => ['set' => 31, 'unset' => 39],
'green' => ['set' => 32, 'unset' => 39],
'yellow' => ['set' => 33, 'unset' => 39],
'blue' => ['set' => 34, 'unset' => 39],
'magenta' => ['set' => 35, 'unset' => 39],
'cyan' => ['set' => 36, 'unset' => 39],
'white' => ['set' => 37, 'unset' => 39],
'default' => ['set' => 39, 'unset' => 39],
];
private static $availableBackgroundColors = [
'black' => ['set' => 40, 'unset' => 49],
'red' => ['set' => 41, 'unset' => 49],
'green' => ['set' => 42, 'unset' => 49],
'yellow' => ['set' => 43, 'unset' => 49],
'blue' => ['set' => 44, 'unset' => 49],
'magenta' => ['set' => 45, 'unset' => 49],
'cyan' => ['set' => 46, 'unset' => 49],
'white' => ['set' => 47, 'unset' => 49],
'default' => ['set' => 49, 'unset' => 49],
];
private static $availableOptions = [
'bold' => ['set' => 1, 'unset' => 22],
'underscore' => ['set' => 4, 'unset' => 24],
'blink' => ['set' => 5, 'unset' => 25],
'reverse' => ['set' => 7, 'unset' => 27],
'conceal' => ['set' => 8, 'unset' => 28],
];
private $foreground;
private $background;
private $options = [];
public function __construct($foreground = null, $background = null, array $options = [])
{
if (null !== $foreground) {
$this->setForeground($foreground);
}
if (null !== $background) {
$this->setBackground($background);
}
if (\count($options)) {
$this->setOptions($options);
}
}
public function setForeground($color = null)
{
if (null === $color) {
$this->foreground = null;
return;
}
if (!isset(static::$availableForegroundColors[$color])) {
throw new InvalidArgumentException(sprintf('Invalid foreground color specified: "%s". Expected one of (%s).', $color, implode(', ', array_keys(static::$availableForegroundColors))));
}
$this->foreground = static::$availableForegroundColors[$color];
}
public function setBackground($color = null)
{
if (null === $color) {
$this->background = null;
return;
}
if (!isset(static::$availableBackgroundColors[$color])) {
throw new InvalidArgumentException(sprintf('Invalid background color specified: "%s". Expected one of (%s).', $color, implode(', ', array_keys(static::$availableBackgroundColors))));
}
$this->background = static::$availableBackgroundColors[$color];
}
public function setOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s).', $option, implode(', ', array_keys(static::$availableOptions))));
}
if (!\in_array(static::$availableOptions[$option], $this->options)) {
$this->options[] = static::$availableOptions[$option];
}
}
public function unsetOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s).', $option, implode(', ', array_keys(static::$availableOptions))));
}
$pos = array_search(static::$availableOptions[$option], $this->options);
if (false !== $pos) {
unset($this->options[$pos]);
}
}
public function setOptions(array $options)
{
$this->options = [];
foreach ($options as $option) {
$this->setOption($option);
}
}
public function apply($text)
{
$setCodes = [];
$unsetCodes = [];
if (null !== $this->foreground) {
$setCodes[] = $this->foreground['set'];
$unsetCodes[] = $this->foreground['unset'];
}
if (null !== $this->background) {
$setCodes[] = $this->background['set'];
$unsetCodes[] = $this->background['unset'];
}
if (\count($this->options)) {
foreach ($this->options as $option) {
$setCodes[] = $option['set'];
$unsetCodes[] = $option['unset'];
}
}
if (0 === \count($setCodes)) {
return $text;
}
return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
}
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatter implements OutputFormatterInterface
{
private $decorated;
private $styles = [];
private $styleStack;
public static function escape($text)
{
$text = preg_replace('/([^\\\\]?)</', '$1\\<', $text);
return self::escapeTrailingBackslash($text);
}
public static function escapeTrailingBackslash($text)
{
if ('\\' === substr($text, -1)) {
$len = \strlen($text);
$text = rtrim($text, '\\');
$text = str_replace("\0", '', $text);
$text .= str_repeat("\0", $len - \strlen($text));
}
return $text;
}
public function __construct($decorated = false, array $styles = [])
{
$this->decorated = (bool) $decorated;
$this->setStyle('error', new OutputFormatterStyle('white', 'red'));
$this->setStyle('info', new OutputFormatterStyle('green'));
$this->setStyle('comment', new OutputFormatterStyle('yellow'));
$this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
foreach ($styles as $name => $style) {
$this->setStyle($name, $style);
}
$this->styleStack = new OutputFormatterStyleStack();
}
public function setDecorated($decorated)
{
$this->decorated = (bool) $decorated;
}
public function isDecorated()
{
return $this->decorated;
}
public function setStyle($name, OutputFormatterStyleInterface $style)
{
$this->styles[strtolower($name)] = $style;
}
public function hasStyle($name)
{
return isset($this->styles[strtolower($name)]);
}
public function getStyle($name)
{
if (!$this->hasStyle($name)) {
throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name));
}
return $this->styles[strtolower($name)];
}
public function format($message)
{
$message = (string) $message;
$offset = 0;
$output = '';
$tagRegex = '[a-z][a-z0-9,_=;-]*+';
preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $i => $match) {
$pos = $match[1];
$text = $match[0];
if (0 != $pos && '\\' == $message[$pos - 1]) {
continue;
}
$output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
$offset = $pos + \strlen($text);
if ($open = '/' != $text[1]) {
$tag = $matches[1][$i][0];
} else {
$tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
}
if (!$open && !$tag) {
$this->styleStack->pop();
} elseif (false === $style = $this->createStyleFromString($tag)) {
$output .= $this->applyCurrentStyle($text);
} elseif ($open) {
$this->styleStack->push($style);
} else {
$this->styleStack->pop($style);
}
}
$output .= $this->applyCurrentStyle(substr($message, $offset));
if (false !== strpos($output, "\0")) {
return strtr($output, ["\0" => '\\', '\\<' => '<']);
}
return str_replace('\\<', '<', $output);
}
public function getStyleStack()
{
return $this->styleStack;
}
private function createStyleFromString($string)
{
if (isset($this->styles[$string])) {
return $this->styles[$string];
}
if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
return false;
}
$style = new OutputFormatterStyle();
foreach ($matches as $match) {
array_shift($match);
$match[0] = strtolower($match[0]);
if ('fg' == $match[0]) {
$style->setForeground(strtolower($match[1]));
} elseif ('bg' == $match[0]) {
$style->setBackground(strtolower($match[1]));
} elseif ('options' === $match[0]) {
preg_match_all('([^,;]+)', strtolower($match[1]), $options);
$options = array_shift($options);
foreach ($options as $option) {
try {
$style->setOption($option);
} catch (\InvalidArgumentException $e) {
@trigger_error(sprintf('Unknown style options are deprecated since Symfony 3.2 and will be removed in 4.0. Exception "%s".', $e->getMessage()), \E_USER_DEPRECATED);
return false;
}
}
} else {
return false;
}
}
return $style;
}
private function applyCurrentStyle($text)
{
return $this->isDecorated() && \strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
}
}
<?php
namespace Symfony\Component\Console\Formatter;
interface OutputFormatterInterface
{
public function setDecorated($decorated);
public function isDecorated();
public function setStyle($name, OutputFormatterStyleInterface $style);
public function hasStyle($name);
public function getStyle($name);
public function format($message);
}
<?php
namespace Symfony\Component\Console\Formatter;
interface OutputFormatterStyleInterface
{
public function setForeground($color = null);
public function setBackground($color = null);
public function setOption($option);
public function unsetOption($option);
public function setOptions(array $options);
public function apply($text);
}
<?php
namespace Symfony\Component\Console\Question;
class ConfirmationQuestion extends Question
{
private $trueAnswerRegex;
public function __construct($question, $default = true, $trueAnswerRegex = '/^y/i')
{
parent::__construct($question, (bool) $default);
$this->trueAnswerRegex = $trueAnswerRegex;
$this->setNormalizer($this->getDefaultNormalizer());
}
private function getDefaultNormalizer()
{
$default = $this->getDefault();
$regex = $this->trueAnswerRegex;
return function ($answer) use ($default, $regex) {
if (\is_bool($answer)) {
return $answer;
}
$answerIsTrue = (bool) preg_match($regex, $answer);
if (false === $default) {
return $answer && $answerIsTrue;
}
return '' === $answer || $answerIsTrue;
};
}
}
<?php
namespace Symfony\Component\Console\Question;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class Question
{
private $question;
private $attempts;
private $hidden = false;
private $hiddenFallback = true;
private $autocompleterValues;
private $validator;
private $default;
private $normalizer;
public function __construct($question, $default = null)
{
$this->question = $question;
$this->default = $default;
}
public function getQuestion()
{
return $this->question;
}
public function getDefault()
{
return $this->default;
}
public function isHidden()
{
return $this->hidden;
}
public function setHidden($hidden)
{
if ($this->autocompleterValues) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}
$this->hidden = (bool) $hidden;
return $this;
}
public function isHiddenFallback()
{
return $this->hiddenFallback;
}
public function setHiddenFallback($fallback)
{
$this->hiddenFallback = (bool) $fallback;
return $this;
}
public function getAutocompleterValues()
{
return $this->autocompleterValues;
}
public function setAutocompleterValues($values)
{
if (\is_array($values)) {
$values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values);
}
if (null !== $values && !\is_array($values) && !$values instanceof \Traversable) {
throw new InvalidArgumentException('Autocompleter values can be either an array, `null` or a `Traversable` object.');
}
if ($this->hidden) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}
$this->autocompleterValues = $values;
return $this;
}
public function setValidator(callable $validator = null)
{
$this->validator = $validator;
return $this;
}
public function getValidator()
{
return $this->validator;
}
public function setMaxAttempts($attempts)
{
if (null !== $attempts) {
$attempts = (int) $attempts;
if ($attempts < 1) {
throw new InvalidArgumentException('Maximum number of attempts must be a positive value.');
}
}
$this->attempts = $attempts;
return $this;
}
public function getMaxAttempts()
{
return $this->attempts;
}
public function setNormalizer(callable $normalizer)
{
$this->normalizer = $normalizer;
return $this;
}
public function getNormalizer()
{
return $this->normalizer;
}
protected function isAssoc($array)
{
return (bool) \count(array_filter(array_keys($array), 'is_string'));
}
}
<?php
namespace Symfony\Component\Console\Question;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class ChoiceQuestion extends Question
{
private $choices;
private $multiselect = false;
private $prompt = ' > ';
private $errorMessage = 'Value "%s" is invalid';
public function __construct($question, array $choices, $default = null)
{
if (!$choices) {
throw new \LogicException('Choice question must have at least 1 choice available.');
}
parent::__construct($question, $default);
$this->choices = $choices;
$this->setValidator($this->getDefaultValidator());
$this->setAutocompleterValues($choices);
}
public function getChoices()
{
return $this->choices;
}
public function setMultiselect($multiselect)
{
$this->multiselect = $multiselect;
$this->setValidator($this->getDefaultValidator());
return $this;
}
public function isMultiselect()
{
return $this->multiselect;
}
public function getPrompt()
{
return $this->prompt;
}
public function setPrompt($prompt)
{
$this->prompt = $prompt;
return $this;
}
public function setErrorMessage($errorMessage)
{
$this->errorMessage = $errorMessage;
$this->setValidator($this->getDefaultValidator());
return $this;
}
private function getDefaultValidator()
{
$choices = $this->choices;
$errorMessage = $this->errorMessage;
$multiselect = $this->multiselect;
$isAssoc = $this->isAssoc($choices);
return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) {
if ($multiselect) {
if (!preg_match('/^[^,]+(?:,[^,]+)*$/', $selected, $matches)) {
throw new InvalidArgumentException(sprintf($errorMessage, $selected));
}
$selectedChoices = array_map('trim', explode(',', $selected));
} else {
$selectedChoices = [trim($selected)];
}
$multiselectChoices = [];
foreach ($selectedChoices as $value) {
$results = [];
foreach ($choices as $key => $choice) {
if ($choice === $value) {
$results[] = $key;
}
}
if (\count($results) > 1) {
throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of "%s".', implode('" or "', $results)));
}
$result = array_search($value, $choices);
if (!$isAssoc) {
if (false !== $result) {
$result = $choices[$result];
} elseif (isset($choices[$value])) {
$result = $choices[$value];
}
} elseif (false === $result && isset($choices[$value])) {
$result = $value;
}
if (false === $result) {
throw new InvalidArgumentException(sprintf($errorMessage, $value));
}
$multiselectChoices[] = (string) $result;
}
if ($multiselect) {
return $multiselectChoices;
}
return current($multiselectChoices);
};
}
}
<?php
namespace Symfony\Component\Console\DependencyInjection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\TypedReference;
class AddConsoleCommandPass implements CompilerPassInterface
{
private $commandLoaderServiceId;
private $commandTag;
public function __construct($commandLoaderServiceId = 'console.command_loader', $commandTag = 'console.command')
{
$this->commandLoaderServiceId = $commandLoaderServiceId;
$this->commandTag = $commandTag;
}
public function process(ContainerBuilder $container)
{
$commandServices = $container->findTaggedServiceIds($this->commandTag, true);
$lazyCommandMap = [];
$lazyCommandRefs = [];
$serviceIds = [];
$lazyServiceIds = [];
foreach ($commandServices as $id => $tags) {
$definition = $container->getDefinition($id);
$class = $container->getParameterBag()->resolveValue($definition->getClass());
$commandId = 'console.command.'.strtolower(str_replace('\\', '_', $class));
if (isset($tags[0]['command'])) {
$commandName = $tags[0]['command'];
} else {
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(Command::class)) {
throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, $this->commandTag, Command::class));
}
$commandName = $class::getDefaultName();
}
if (null === $commandName) {
if (isset($serviceIds[$commandId]) || $container->hasAlias($commandId)) {
$commandId = $commandId.'_'.$id;
}
if (!$definition->isPublic() || $definition->isPrivate()) {
$container->setAlias($commandId, $id)->setPublic(true);
$id = $commandId;
}
$serviceIds[$commandId] = $id;
continue;
}
$serviceIds[$commandId] = $id;
$lazyServiceIds[$id] = true;
unset($tags[0]);
$lazyCommandMap[$commandName] = $id;
$lazyCommandRefs[$id] = new TypedReference($id, $class);
$aliases = [];
foreach ($tags as $tag) {
if (isset($tag['command'])) {
$aliases[] = $tag['command'];
$lazyCommandMap[$tag['command']] = $id;
}
}
$definition->addMethodCall('setName', [$commandName]);
if ($aliases) {
$definition->addMethodCall('setAliases', [$aliases]);
}
}
$container
->register($this->commandLoaderServiceId, ContainerCommandLoader::class)
->setPublic(true)
->setArguments([ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap]);
$container->setParameter('console.command.ids', $serviceIds);
$container->setParameter('console.lazy_command.ids', $lazyServiceIds);
}
}
<?php
namespace Symfony\Component\Console;
class Terminal
{
private static $width;
private static $height;
private static $stty;
public function getWidth()
{
$width = getenv('COLUMNS');
if (false !== $width) {
return (int) trim($width);
}
if (null === self::$width) {
self::initDimensions();
}
return self::$width ?: 80;
}
public function getHeight()
{
$height = getenv('LINES');
if (false !== $height) {
return (int) trim($height);
}
if (null === self::$height) {
self::initDimensions();
}
return self::$height ?: 50;
}
public static function hasSttyAvailable()
{
if (null !== self::$stty) {
return self::$stty;
}
if (!\function_exists('exec')) {
return false;
}
exec('stty 2>&1', $output, $exitcode);
return self::$stty = 0 === $exitcode;
}
private static function initDimensions()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
if (preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim(getenv('ANSICON')), $matches)) {
self::$width = (int) $matches[1];
self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2];
} elseif (!self::hasVt100Support() && self::hasSttyAvailable()) {
self::initDimensionsUsingStty();
} elseif (null !== $dimensions = self::getConsoleMode()) {
self::$width = (int) $dimensions[0];
self::$height = (int) $dimensions[1];
}
} else {
self::initDimensionsUsingStty();
}
}
private static function hasVt100Support()
{
return \function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support(fopen('php://stdout', 'w'));
}
private static function initDimensionsUsingStty()
{
if ($sttyString = self::getSttyColumns()) {
if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
self::$width = (int) $matches[2];
self::$height = (int) $matches[1];
} elseif (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
self::$width = (int) $matches[2];
self::$height = (int) $matches[1];
}
}
}
private static function getConsoleMode()
{
$info = self::readFromProcess('mode CON');
if (null === $info || !preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
return null;
}
return [(int) $matches[2], (int) $matches[1]];
}
private static function getSttyColumns()
{
return self::readFromProcess('stty -a | grep columns');
}
private static function readFromProcess($command)
{
if (!\function_exists('proc_open')) {
return null;
}
$descriptorspec = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($command, $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
if (!\is_resource($process)) {
return null;
}
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $info;
}
}
<?php
namespace Symfony\Component\Console\Output;
class BufferedOutput extends Output
{
private $buffer = '';
public function fetch()
{
$content = $this->buffer;
$this->buffer = '';
return $content;
}
protected function doWrite($message, $newline)
{
$this->buffer .= $message;
if ($newline) {
$this->buffer .= \PHP_EOL;
}
}
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
abstract class Output implements OutputInterface
{
private $verbosity;
private $formatter;
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = false, OutputFormatterInterface $formatter = null)
{
$this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity;
$this->formatter = $formatter ?: new OutputFormatter();
$this->formatter->setDecorated($decorated);
}
public function setFormatter(OutputFormatterInterface $formatter)
{
$this->formatter = $formatter;
}
public function getFormatter()
{
return $this->formatter;
}
public function setDecorated($decorated)
{
$this->formatter->setDecorated($decorated);
}
public function isDecorated()
{
return $this->formatter->isDecorated();
}
public function setVerbosity($level)
{
$this->verbosity = (int) $level;
}
public function getVerbosity()
{
return $this->verbosity;
}
public function isQuiet()
{
return self::VERBOSITY_QUIET === $this->verbosity;
}
public function isVerbose()
{
return self::VERBOSITY_VERBOSE <= $this->verbosity;
}
public function isVeryVerbose()
{
return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity;
}
public function isDebug()
{
return self::VERBOSITY_DEBUG <= $this->verbosity;
}
public function writeln($messages, $options = self::OUTPUT_NORMAL)
{
$this->write($messages, true, $options);
}
public function write($messages, $newline = false, $options = self::OUTPUT_NORMAL)
{
$messages = (array) $messages;
$types = self::OUTPUT_NORMAL | self::OUTPUT_RAW | self::OUTPUT_PLAIN;
$type = $types & $options ?: self::OUTPUT_NORMAL;
$verbosities = self::VERBOSITY_QUIET | self::VERBOSITY_NORMAL | self::VERBOSITY_VERBOSE | self::VERBOSITY_VERY_VERBOSE | self::VERBOSITY_DEBUG;
$verbosity = $verbosities & $options ?: self::VERBOSITY_NORMAL;
if ($verbosity > $this->getVerbosity()) {
return;
}
foreach ($messages as $message) {
switch ($type) {
case OutputInterface::OUTPUT_NORMAL:
$message = $this->formatter->format($message);
break;
case OutputInterface::OUTPUT_RAW:
break;
case OutputInterface::OUTPUT_PLAIN:
$message = strip_tags($this->formatter->format($message));
break;
}
$this->doWrite($message, $newline);
}
}
abstract protected function doWrite($message, $newline);
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
{
private $stderr;
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
parent::__construct($this->openOutputStream(), $verbosity, $decorated, $formatter);
$actualDecorated = $this->isDecorated();
$this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated, $this->getFormatter());
if (null === $decorated) {
$this->setDecorated($actualDecorated && $this->stderr->isDecorated());
}
}
public function setDecorated($decorated)
{
parent::setDecorated($decorated);
$this->stderr->setDecorated($decorated);
}
public function setFormatter(OutputFormatterInterface $formatter)
{
parent::setFormatter($formatter);
$this->stderr->setFormatter($formatter);
}
public function setVerbosity($level)
{
parent::setVerbosity($level);
$this->stderr->setVerbosity($level);
}
public function getErrorOutput()
{
return $this->stderr;
}
public function setErrorOutput(OutputInterface $error)
{
$this->stderr = $error;
}
protected function hasStdoutSupport()
{
return false === $this->isRunningOS400();
}
protected function hasStderrSupport()
{
return false === $this->isRunningOS400();
}
private function isRunningOS400()
{
$checks = [
\function_exists('php_uname') ? php_uname('s') : '',
getenv('OSTYPE'),
\PHP_OS,
];
return false !== stripos(implode(';', $checks), 'OS400');
}
private function openOutputStream()
{
if (!$this->hasStdoutSupport()) {
return fopen('php://output', 'w');
}
return @fopen('php://stdout', 'w') ?: fopen('php://output', 'w');
}
private function openErrorStream()
{
return fopen($this->hasStderrSupport() ? 'php://stderr' : 'php://output', 'w');
}
}
<?php
namespace Symfony\Component\Console\Output;
interface ConsoleOutputInterface extends OutputInterface
{
public function getErrorOutput();
public function setErrorOutput(OutputInterface $error);
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class StreamOutput extends Output
{
private $stream;
public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
throw new InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
}
$this->stream = $stream;
if (null === $decorated) {
$decorated = $this->hasColorSupport();
}
parent::__construct($verbosity, $decorated, $formatter);
}
public function getStream()
{
return $this->stream;
}
protected function doWrite($message, $newline)
{
if ($newline) {
$message .= \PHP_EOL;
}
@fwrite($this->stream, $message);
fflush($this->stream);
}
protected function hasColorSupport()
{
if ('Hyper' === getenv('TERM_PROGRAM')) {
return true;
}
if (\DIRECTORY_SEPARATOR === '\\') {
return (\function_exists('sapi_windows_vt100_support')
&& @sapi_windows_vt100_support($this->stream))
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
if (\function_exists('stream_isatty')) {
return @stream_isatty($this->stream);
}
if (\function_exists('posix_isatty')) {
return @posix_isatty($this->stream);
}
$stat = @fstat($this->stream);
return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
}
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
interface OutputInterface
{
const VERBOSITY_QUIET = 16;
const VERBOSITY_NORMAL = 32;
const VERBOSITY_VERBOSE = 64;
const VERBOSITY_VERY_VERBOSE = 128;
const VERBOSITY_DEBUG = 256;
const OUTPUT_NORMAL = 1;
const OUTPUT_RAW = 2;
const OUTPUT_PLAIN = 4;
public function write($messages, $newline = false, $options = 0);
public function writeln($messages, $options = 0);
public function setVerbosity($level);
public function getVerbosity();
public function isQuiet();
public function isVerbose();
public function isVeryVerbose();
public function isDebug();
public function setDecorated($decorated);
public function isDecorated();
public function setFormatter(OutputFormatterInterface $formatter);
public function getFormatter();
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class NullOutput implements OutputInterface
{
public function setFormatter(OutputFormatterInterface $formatter)
{
}
public function getFormatter()
{
return new OutputFormatter();
}
public function setDecorated($decorated)
{
}
public function isDecorated()
{
return false;
}
public function setVerbosity($level)
{
}
public function getVerbosity()
{
return self::VERBOSITY_QUIET;
}
public function isQuiet()
{
return true;
}
public function isVerbose()
{
return false;
}
public function isVeryVerbose()
{
return false;
}
public function isDebug()
{
return false;
}
public function writeln($messages, $options = self::OUTPUT_NORMAL)
{
}
public function write($messages, $newline = false, $options = self::OUTPUT_NORMAL)
{
}
}
<?php
namespace Symfony\Component\Console\Event;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead.', ConsoleExceptionEvent::class), \E_USER_DEPRECATED);
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionEvent extends ConsoleEvent
{
private $exception;
private $exitCode;
public function __construct(Command $command, InputInterface $input, OutputInterface $output, \Exception $exception, $exitCode)
{
parent::__construct($command, $input, $output);
$this->setException($exception);
$this->exitCode = (int) $exitCode;
}
public function getException()
{
return $this->exception;
}
public function setException(\Exception $exception)
{
$this->exception = $exception;
}
public function getExitCode()
{
return $this->exitCode;
}
}
<?php
namespace Symfony\Component\Console\Event;
class ConsoleCommandEvent extends ConsoleEvent
{
const RETURN_CODE_DISABLED = 113;
private $commandShouldRun = true;
public function disableCommand()
{
return $this->commandShouldRun = false;
}
public function enableCommand()
{
return $this->commandShouldRun = true;
}
public function commandShouldRun()
{
return $this->commandShouldRun;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleTerminateEvent extends ConsoleEvent
{
private $exitCode;
public function __construct(Command $command, InputInterface $input, OutputInterface $output, $exitCode)
{
parent::__construct($command, $input, $output);
$this->setExitCode($exitCode);
}
public function setExitCode($exitCode)
{
$this->exitCode = (int) $exitCode;
}
public function getExitCode()
{
return $this->exitCode;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\Event;
class ConsoleEvent extends Event
{
protected $command;
private $input;
private $output;
public function __construct(Command $command = null, InputInterface $input, OutputInterface $output)
{
$this->command = $command;
$this->input = $input;
$this->output = $output;
}
public function getCommand()
{
return $this->command;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class ConsoleErrorEvent extends ConsoleEvent
{
private $error;
private $exitCode;
public function __construct(InputInterface $input, OutputInterface $output, $error, Command $command = null)
{
parent::__construct($command, $input, $output);
$this->setError($error);
}
public function getError()
{
return $this->error;
}
public function setError($error)
{
if (!$error instanceof \Throwable && !$error instanceof \Exception) {
throw new InvalidArgumentException(sprintf('The error passed to ConsoleErrorEvent must be an instance of \Throwable or \Exception, "%s" was passed instead.', \is_object($error) ? \get_class($error) : \gettype($error)));
}
$this->error = $error;
}
public function setExitCode($exitCode)
{
$this->exitCode = (int) $exitCode;
$r = new \ReflectionProperty($this->error, 'code');
$r->setAccessible(true);
$r->setValue($this->error, $this->exitCode);
}
public function getExitCode()
{
return null !== $this->exitCode ? $this->exitCode : (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputArgument
{
const REQUIRED = 1;
const OPTIONAL = 2;
const IS_ARRAY = 4;
private $name;
private $mode;
private $default;
private $description;
public function __construct($name, $mode = null, $description = '', $default = null)
{
if (null === $mode) {
$mode = self::OPTIONAL;
} elseif (!\is_int($mode) || $mode > 7 || $mode < 1) {
throw new InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
}
$this->name = $name;
$this->mode = $mode;
$this->description = $description;
$this->setDefault($default);
}
public function getName()
{
return $this->name;
}
public function isRequired()
{
return self::REQUIRED === (self::REQUIRED & $this->mode);
}
public function isArray()
{
return self::IS_ARRAY === (self::IS_ARRAY & $this->mode);
}
public function setDefault($default = null)
{
if (self::REQUIRED === $this->mode && null !== $default) {
throw new LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.');
}
if ($this->isArray()) {
if (null === $default) {
$default = [];
} elseif (!\is_array($default)) {
throw new LogicException('A default value for an array argument must be an array.');
}
}
$this->default = $default;
}
public function getDefault()
{
return $this->default;
}
public function getDescription()
{
return $this->description;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputDefinition
{
private $arguments;
private $requiredCount;
private $hasAnArrayArgument = false;
private $hasOptional;
private $options;
private $shortcuts;
public function __construct(array $definition = [])
{
$this->setDefinition($definition);
}
public function setDefinition(array $definition)
{
$arguments = [];
$options = [];
foreach ($definition as $item) {
if ($item instanceof InputOption) {
$options[] = $item;
} else {
$arguments[] = $item;
}
}
$this->setArguments($arguments);
$this->setOptions($options);
}
public function setArguments($arguments = [])
{
$this->arguments = [];
$this->requiredCount = 0;
$this->hasOptional = false;
$this->hasAnArrayArgument = false;
$this->addArguments($arguments);
}
public function addArguments($arguments = [])
{
if (null !== $arguments) {
foreach ($arguments as $argument) {
$this->addArgument($argument);
}
}
}
public function addArgument(InputArgument $argument)
{
if (isset($this->arguments[$argument->getName()])) {
throw new LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName()));
}
if ($this->hasAnArrayArgument) {
throw new LogicException('Cannot add an argument after an array argument.');
}
if ($argument->isRequired() && $this->hasOptional) {
throw new LogicException('Cannot add a required argument after an optional one.');
}
if ($argument->isArray()) {
$this->hasAnArrayArgument = true;
}
if ($argument->isRequired()) {
++$this->requiredCount;
} else {
$this->hasOptional = true;
}
$this->arguments[$argument->getName()] = $argument;
}
public function getArgument($name)
{
if (!$this->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments;
return $arguments[$name];
}
public function hasArgument($name)
{
$arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments;
return isset($arguments[$name]);
}
public function getArguments()
{
return $this->arguments;
}
public function getArgumentCount()
{
return $this->hasAnArrayArgument ? \PHP_INT_MAX : \count($this->arguments);
}
public function getArgumentRequiredCount()
{
return $this->requiredCount;
}
public function getArgumentDefaults()
{
$values = [];
foreach ($this->arguments as $argument) {
$values[$argument->getName()] = $argument->getDefault();
}
return $values;
}
public function setOptions($options = [])
{
$this->options = [];
$this->shortcuts = [];
$this->addOptions($options);
}
public function addOptions($options = [])
{
foreach ($options as $option) {
$this->addOption($option);
}
}
public function addOption(InputOption $option)
{
if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) {
throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName()));
}
if ($option->getShortcut()) {
foreach (explode('|', $option->getShortcut()) as $shortcut) {
if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) {
throw new LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut));
}
}
}
$this->options[$option->getName()] = $option;
if ($option->getShortcut()) {
foreach (explode('|', $option->getShortcut()) as $shortcut) {
$this->shortcuts[$shortcut] = $option->getName();
}
}
}
public function getOption($name)
{
if (!$this->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
}
return $this->options[$name];
}
public function hasOption($name)
{
return isset($this->options[$name]);
}
public function getOptions()
{
return $this->options;
}
public function hasShortcut($name)
{
return isset($this->shortcuts[$name]);
}
public function getOptionForShortcut($shortcut)
{
return $this->getOption($this->shortcutToName($shortcut));
}
public function getOptionDefaults()
{
$values = [];
foreach ($this->options as $option) {
$values[$option->getName()] = $option->getDefault();
}
return $values;
}
public function shortcutToName($shortcut)
{
if (!isset($this->shortcuts[$shortcut])) {
throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
}
return $this->shortcuts[$shortcut];
}
public function getSynopsis($short = false)
{
$elements = [];
if ($short && $this->getOptions()) {
$elements[] = '[options]';
} elseif (!$short) {
foreach ($this->getOptions() as $option) {
$value = '';
if ($option->acceptValue()) {
$value = sprintf(
' %s%s%s',
$option->isValueOptional() ? '[' : '',
strtoupper($option->getName()),
$option->isValueOptional() ? ']' : ''
);
}
$shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
$elements[] = sprintf('[%s--%s%s]', $shortcut, $option->getName(), $value);
}
}
if (\count($elements) && $this->getArguments()) {
$elements[] = '[--]';
}
foreach ($this->getArguments() as $argument) {
$element = '<'.$argument->getName().'>';
if (!$argument->isRequired()) {
$element = '['.$element.']';
} elseif ($argument->isArray()) {
$element .= ' ('.$element.')';
}
if ($argument->isArray()) {
$element .= '...';
}
$elements[] = $element;
}
return implode(' ', $elements);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
abstract class Input implements InputInterface, StreamableInputInterface
{
protected $definition;
protected $stream;
protected $options = [];
protected $arguments = [];
protected $interactive = true;
public function __construct(InputDefinition $definition = null)
{
if (null === $definition) {
$this->definition = new InputDefinition();
} else {
$this->bind($definition);
$this->validate();
}
}
public function bind(InputDefinition $definition)
{
$this->arguments = [];
$this->options = [];
$this->definition = $definition;
$this->parse();
}
abstract protected function parse();
public function validate()
{
$definition = $this->definition;
$givenArguments = $this->arguments;
$missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) {
return !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired();
});
if (\count($missingArguments) > 0) {
throw new RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments)));
}
}
public function isInteractive()
{
return $this->interactive;
}
public function setInteractive($interactive)
{
$this->interactive = (bool) $interactive;
}
public function getArguments()
{
return array_merge($this->definition->getArgumentDefaults(), $this->arguments);
}
public function getArgument($name)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
return isset($this->arguments[$name]) ? $this->arguments[$name] : $this->definition->getArgument($name)->getDefault();
}
public function setArgument($name, $value)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$this->arguments[$name] = $value;
}
public function hasArgument($name)
{
return $this->definition->hasArgument($name);
}
public function getOptions()
{
return array_merge($this->definition->getOptionDefaults(), $this->options);
}
public function getOption($name)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
}
return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();
}
public function setOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
}
$this->options[$name] = $value;
}
public function hasOption($name)
{
return $this->definition->hasOption($name);
}
public function escapeToken($token)
{
return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token);
}
public function setStream($stream)
{
$this->stream = $stream;
}
public function getStream()
{
return $this->stream;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class StringInput extends ArgvInput
{
const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
public function __construct($input)
{
parent::__construct([]);
$this->setTokens($this->tokenize($input));
}
private function tokenize($input)
{
$tokens = [];
$length = \strlen($input);
$cursor = 0;
while ($cursor < $length) {
if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
} elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
$tokens[] = $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, \strlen($match[3]) - 2)));
} elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
$tokens[] = stripcslashes(substr($match[0], 1, \strlen($match[0]) - 2));
} elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
$tokens[] = stripcslashes($match[1]);
} else {
throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10)));
}
$cursor += \strlen($match[0]);
}
return $tokens;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\RuntimeException;
class ArgvInput extends Input
{
private $tokens;
private $parsed;
public function __construct(array $argv = null, InputDefinition $definition = null)
{
$argv = null !== $argv ? $argv : (isset($_SERVER['argv']) ? $_SERVER['argv'] : []);
array_shift($argv);
$this->tokens = $argv;
parent::__construct($definition);
}
protected function setTokens(array $tokens)
{
$this->tokens = $tokens;
}
protected function parse()
{
$parseOptions = true;
$this->parsed = $this->tokens;
while (null !== $token = array_shift($this->parsed)) {
if ($parseOptions && '' == $token) {
$this->parseArgument($token);
} elseif ($parseOptions && '--' == $token) {
$parseOptions = false;
} elseif ($parseOptions && 0 === strpos($token, '--')) {
$this->parseLongOption($token);
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
$this->parseShortOption($token);
} else {
$this->parseArgument($token);
}
}
}
private function parseShortOption($token)
{
$name = substr($token, 1);
if (\strlen($name) > 1) {
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
$this->addShortOption($name[0], substr($name, 1));
} else {
$this->parseShortOptionSet($name);
}
} else {
$this->addShortOption($name, null);
}
}
private function parseShortOptionSet($name)
{
$len = \strlen($name);
for ($i = 0; $i < $len; ++$i) {
if (!$this->definition->hasShortcut($name[$i])) {
$encoding = mb_detect_encoding($name, null, true);
throw new RuntimeException(sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding)));
}
$option = $this->definition->getOptionForShortcut($name[$i]);
if ($option->acceptValue()) {
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
break;
} else {
$this->addLongOption($option->getName(), null);
}
}
}
private function parseLongOption($token)
{
$name = substr($token, 2);
if (false !== $pos = strpos($name, '=')) {
if (0 === \strlen($value = substr($name, $pos + 1))) {
if (\PHP_VERSION_ID < 70000 && false === $value) {
$value = '';
}
array_unshift($this->parsed, $value);
}
$this->addLongOption(substr($name, 0, $pos), $value);
} else {
$this->addLongOption($name, null);
}
}
private function parseArgument($token)
{
$c = \count($this->arguments);
if ($this->definition->hasArgument($c)) {
$arg = $this->definition->getArgument($c);
$this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
} elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
$arg = $this->definition->getArgument($c - 1);
$this->arguments[$arg->getName()][] = $token;
} else {
$all = $this->definition->getArguments();
if (\count($all)) {
throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
}
throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
}
}
private function addShortOption($shortcut, $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
}
private function addLongOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
}
$option = $this->definition->getOption($name);
if (null !== $value && !$option->acceptValue()) {
throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
}
if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
$next = array_shift($this->parsed);
if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
$value = $next;
} else {
array_unshift($this->parsed, $next);
}
}
if (null === $value) {
if ($option->isValueRequired()) {
throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
}
if (!$option->isArray() && !$option->isValueOptional()) {
$value = true;
}
}
if ($option->isArray()) {
$this->options[$name][] = $value;
} else {
$this->options[$name] = $value;
}
}
public function getFirstArgument()
{
$isOption = false;
foreach ($this->tokens as $i => $token) {
if ($token && '-' === $token[0]) {
if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) {
continue;
}
$name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
} elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
$isOption = true;
}
continue;
}
if ($isOption) {
$isOption = false;
continue;
}
return $token;
}
return null;
}
public function hasParameterOption($values, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->tokens as $token) {
if ($onlyParams && '--' === $token) {
return false;
}
foreach ($values as $value) {
$leading = 0 === strpos($value, '--') ? $value.'=' : $value;
if ($token === $value || '' !== $leading && 0 === strpos($token, $leading)) {
return true;
}
}
}
return false;
}
public function getParameterOption($values, $default = false, $onlyParams = false)
{
$values = (array) $values;
$tokens = $this->tokens;
while (0 < \count($tokens)) {
$token = array_shift($tokens);
if ($onlyParams && '--' === $token) {
return $default;
}
foreach ($values as $value) {
if ($token === $value) {
return array_shift($tokens);
}
$leading = 0 === strpos($value, '--') ? $value.'=' : $value;
if ('' !== $leading && 0 === strpos($token, $leading)) {
return substr($token, \strlen($leading));
}
}
}
return $default;
}
public function __toString()
{
$tokens = array_map(function ($token) {
if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
return $match[1].$this->escapeToken($match[2]);
}
if ($token && '-' !== $token[0]) {
return $this->escapeToken($token);
}
return $token;
}, $this->tokens);
return implode(' ', $tokens);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
interface InputInterface
{
public function getFirstArgument();
public function hasParameterOption($values, $onlyParams = false);
public function getParameterOption($values, $default = false, $onlyParams = false);
public function bind(InputDefinition $definition);
public function validate();
public function getArguments();
public function getArgument($name);
public function setArgument($name, $value);
public function hasArgument($name);
public function getOptions();
public function getOption($name);
public function setOption($name, $value);
public function hasOption($name);
public function isInteractive();
public function setInteractive($interactive);
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputOption
{
const VALUE_NONE = 1;
const VALUE_REQUIRED = 2;
const VALUE_OPTIONAL = 4;
const VALUE_IS_ARRAY = 8;
private $name;
private $shortcut;
private $mode;
private $default;
private $description;
public function __construct($name, $shortcut = null, $mode = null, $description = '', $default = null)
{
if (0 === strpos($name, '--')) {
$name = substr($name, 2);
}
if (empty($name)) {
throw new InvalidArgumentException('An option name cannot be empty.');
}
if (empty($shortcut)) {
$shortcut = null;
}
if (null !== $shortcut) {
if (\is_array($shortcut)) {
$shortcut = implode('|', $shortcut);
}
$shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-'));
$shortcuts = array_filter($shortcuts);
$shortcut = implode('|', $shortcuts);
if (empty($shortcut)) {
throw new InvalidArgumentException('An option shortcut cannot be empty.');
}
}
if (null === $mode) {
$mode = self::VALUE_NONE;
} elseif (!\is_int($mode) || $mode > 15 || $mode < 1) {
throw new InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode));
}
$this->name = $name;
$this->shortcut = $shortcut;
$this->mode = $mode;
$this->description = $description;
if ($this->isArray() && !$this->acceptValue()) {
throw new InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.');
}
$this->setDefault($default);
}
public function getShortcut()
{
return $this->shortcut;
}
public function getName()
{
return $this->name;
}
public function acceptValue()
{
return $this->isValueRequired() || $this->isValueOptional();
}
public function isValueRequired()
{
return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode);
}
public function isValueOptional()
{
return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode);
}
public function isArray()
{
return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode);
}
public function setDefault($default = null)
{
if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && null !== $default) {
throw new LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.');
}
if ($this->isArray()) {
if (null === $default) {
$default = [];
} elseif (!\is_array($default)) {
throw new LogicException('A default value for an array option must be an array.');
}
}
$this->default = $this->acceptValue() ? $default : false;
}
public function getDefault()
{
return $this->default;
}
public function getDescription()
{
return $this->description;
}
public function equals(self $option)
{
return $option->getName() === $this->getName()
&& $option->getShortcut() === $this->getShortcut()
&& $option->getDefault() === $this->getDefault()
&& $option->isArray() === $this->isArray()
&& $option->isValueRequired() === $this->isValueRequired()
&& $option->isValueOptional() === $this->isValueOptional()
;
}
}
<?php
namespace Symfony\Component\Console\Input;
interface InputAwareInterface
{
public function setInput(InputInterface $input);
}
<?php
namespace Symfony\Component\Console\Input;
interface StreamableInputInterface extends InputInterface
{
public function setStream($stream);
public function getStream();
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\InvalidOptionException;
class ArrayInput extends Input
{
private $parameters;
public function __construct(array $parameters, InputDefinition $definition = null)
{
$this->parameters = $parameters;
parent::__construct($definition);
}
public function getFirstArgument()
{
foreach ($this->parameters as $param => $value) {
if ($param && \is_string($param) && '-' === $param[0]) {
continue;
}
return $value;
}
return null;
}
public function hasParameterOption($values, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->parameters as $k => $v) {
if (!\is_int($k)) {
$v = $k;
}
if ($onlyParams && '--' === $v) {
return false;
}
if (\in_array($v, $values)) {
return true;
}
}
return false;
}
public function getParameterOption($values, $default = false, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->parameters as $k => $v) {
if ($onlyParams && ('--' === $k || (\is_int($k) && '--' === $v))) {
return $default;
}
if (\is_int($k)) {
if (\in_array($v, $values)) {
return true;
}
} elseif (\in_array($k, $values)) {
return $v;
}
}
return $default;
}
public function __toString()
{
$params = [];
foreach ($this->parameters as $param => $val) {
if ($param && \is_string($param) && '-' === $param[0]) {
if (\is_array($val)) {
foreach ($val as $v) {
$params[] = $param.('' != $v ? '='.$this->escapeToken($v) : '');
}
} else {
$params[] = $param.('' != $val ? '='.$this->escapeToken($val) : '');
}
} else {
$params[] = \is_array($val) ? implode(' ', array_map([$this, 'escapeToken'], $val)) : $this->escapeToken($val);
}
}
return implode(' ', $params);
}
protected function parse()
{
foreach ($this->parameters as $key => $value) {
if ('--' === $key) {
return;
}
if (0 === strpos($key, '--')) {
$this->addLongOption(substr($key, 2), $value);
} elseif (0 === strpos($key, '-')) {
$this->addShortOption(substr($key, 1), $value);
} else {
$this->addArgument($key, $value);
}
}
}
private function addShortOption($shortcut, $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
throw new InvalidOptionException(sprintf('The "-%s" option does not exist.', $shortcut));
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
}
private function addLongOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidOptionException(sprintf('The "--%s" option does not exist.', $name));
}
$option = $this->definition->getOption($name);
if (null === $value) {
if ($option->isValueRequired()) {
throw new InvalidOptionException(sprintf('The "--%s" option requires a value.', $name));
}
if (!$option->isValueOptional()) {
$value = true;
}
}
$this->options[$name] = $value;
}
private function addArgument($name, $value)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$this->arguments[$name] = $value;
}
}
<?php
namespace Symfony\Component\Console\Exception;
class CommandNotFoundException extends \InvalidArgumentException implements ExceptionInterface
{
private $alternatives;
public function __construct($message, array $alternatives = [], $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->alternatives = $alternatives;
}
public function getAlternatives()
{
return $this->alternatives;
}
}
<?php
namespace Symfony\Component\Console\Exception;
class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class LogicException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class MarkdownDescriptor extends Descriptor
{
public function describe(OutputInterface $output, $object, array $options = [])
{
$decorated = $output->isDecorated();
$output->setDecorated(false);
parent::describe($output, $object, $options);
$output->setDecorated($decorated);
}
protected function write($content, $decorated = true)
{
parent::write($content, $decorated);
}
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->write(
'#### `'.($argument->getName() ?: '<none>')."`\n\n"
.($argument->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $argument->getDescription())."\n\n" : '')
.'* Is required: '.($argument->isRequired() ? 'yes' : 'no')."\n"
.'* Is array: '.($argument->isArray() ? 'yes' : 'no')."\n"
.'* Default: `'.str_replace("\n", '', var_export($argument->getDefault(), true)).'`'
);
}
protected function describeInputOption(InputOption $option, array $options = [])
{
$name = '--'.$option->getName();
if ($option->getShortcut()) {
$name .= '|-'.str_replace('|', '|-', $option->getShortcut()).'';
}
$this->write(
'#### `'.$name.'`'."\n\n"
.($option->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $option->getDescription())."\n\n" : '')
.'* Accept value: '.($option->acceptValue() ? 'yes' : 'no')."\n"
.'* Is value required: '.($option->isValueRequired() ? 'yes' : 'no')."\n"
.'* Is multiple: '.($option->isArray() ? 'yes' : 'no')."\n"
.'* Default: `'.str_replace("\n", '', var_export($option->getDefault(), true)).'`'
);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
if ($showArguments = \count($definition->getArguments()) > 0) {
$this->write('### Arguments');
foreach ($definition->getArguments() as $argument) {
$this->write("\n\n");
$this->write($this->describeInputArgument($argument));
}
}
if (\count($definition->getOptions()) > 0) {
if ($showArguments) {
$this->write("\n\n");
}
$this->write('### Options');
foreach ($definition->getOptions() as $option) {
$this->write("\n\n");
$this->write($this->describeInputOption($option));
}
}
}
protected function describeCommand(Command $command, array $options = [])
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
$this->write(
'`'.$command->getName()."`\n"
.str_repeat('-', Helper::strlen($command->getName()) + 2)."\n\n"
.($command->getDescription() ? $command->getDescription()."\n\n" : '')
.'### Usage'."\n\n"
.array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), function ($carry, $usage) {
return $carry.'* `'.$usage.'`'."\n";
})
);
if ($help = $command->getProcessedHelp()) {
$this->write("\n");
$this->write($help);
}
if ($command->getNativeDefinition()) {
$this->write("\n\n");
$this->describeInputDefinition($command->getNativeDefinition());
}
}
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
$title = $this->getApplicationTitle($application);
$this->write($title."\n".str_repeat('=', Helper::strlen($title)));
foreach ($description->getNamespaces() as $namespace) {
if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
$this->write("\n\n");
$this->write('**'.$namespace['id'].':**');
}
$this->write("\n\n");
$this->write(implode("\n", array_map(function ($commandName) use ($description) {
return sprintf('* [`%s`](#%s)', $commandName, str_replace(':', '', $description->getCommand($commandName)->getName()));
}, $namespace['commands'])));
}
foreach ($description->getCommands() as $command) {
$this->write("\n\n");
$this->write($this->describeCommand($command));
}
}
private function getApplicationTitle(Application $application)
{
if ('UNKNOWN' !== $application->getName()) {
if ('UNKNOWN' !== $application->getVersion()) {
return sprintf('%s %s', $application->getName(), $application->getVersion());
}
return $application->getName();
}
return 'Console Tool';
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\CommandNotFoundException;
class ApplicationDescription
{
const GLOBAL_NAMESPACE = '_global';
private $application;
private $namespace;
private $showHidden;
private $namespaces;
private $commands;
private $aliases;
public function __construct(Application $application, $namespace = null, $showHidden = false)
{
$this->application = $application;
$this->namespace = $namespace;
$this->showHidden = $showHidden;
}
public function getNamespaces()
{
if (null === $this->namespaces) {
$this->inspectApplication();
}
return $this->namespaces;
}
public function getCommands()
{
if (null === $this->commands) {
$this->inspectApplication();
}
return $this->commands;
}
public function getCommand($name)
{
if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
}
return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
}
private function inspectApplication()
{
$this->commands = [];
$this->namespaces = [];
$all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
foreach ($this->sortCommands($all) as $namespace => $commands) {
$names = [];
foreach ($commands as $name => $command) {
if (!$command->getName() || (!$this->showHidden && $command->isHidden())) {
continue;
}
if ($command->getName() === $name) {
$this->commands[$name] = $command;
} else {
$this->aliases[$name] = $command;
}
$names[] = $name;
}
$this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
}
}
private function sortCommands(array $commands)
{
$namespacedCommands = [];
$globalCommands = [];
$sortedCommands = [];
foreach ($commands as $name => $command) {
$key = $this->application->extractNamespace($name, 1);
if (\in_array($key, ['', self::GLOBAL_NAMESPACE], true)) {
$globalCommands[$name] = $command;
} else {
$namespacedCommands[$key][$name] = $command;
}
}
if ($globalCommands) {
ksort($globalCommands);
$sortedCommands[self::GLOBAL_NAMESPACE] = $globalCommands;
}
if ($namespacedCommands) {
ksort($namespacedCommands);
foreach ($namespacedCommands as $key => $commandsSet) {
ksort($commandsSet);
$sortedCommands[$key] = $commandsSet;
}
}
return $sortedCommands;
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
abstract class Descriptor implements DescriptorInterface
{
protected $output;
public function describe(OutputInterface $output, $object, array $options = [])
{
$this->output = $output;
switch (true) {
case $object instanceof InputArgument:
$this->describeInputArgument($object, $options);
break;
case $object instanceof InputOption:
$this->describeInputOption($object, $options);
break;
case $object instanceof InputDefinition:
$this->describeInputDefinition($object, $options);
break;
case $object instanceof Command:
$this->describeCommand($object, $options);
break;
case $object instanceof Application:
$this->describeApplication($object, $options);
break;
default:
throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', \get_class($object)));
}
}
protected function write($content, $decorated = false)
{
$this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW);
}
abstract protected function describeInputArgument(InputArgument $argument, array $options = []);
abstract protected function describeInputOption(InputOption $option, array $options = []);
abstract protected function describeInputDefinition(InputDefinition $definition, array $options = []);
abstract protected function describeCommand(Command $command, array $options = []);
abstract protected function describeApplication(Application $application, array $options = []);
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class JsonDescriptor extends Descriptor
{
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->writeData($this->getInputArgumentData($argument), $options);
}
protected function describeInputOption(InputOption $option, array $options = [])
{
$this->writeData($this->getInputOptionData($option), $options);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$this->writeData($this->getInputDefinitionData($definition), $options);
}
protected function describeCommand(Command $command, array $options = [])
{
$this->writeData($this->getCommandData($command), $options);
}
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace, true);
$commands = [];
foreach ($description->getCommands() as $command) {
$commands[] = $this->getCommandData($command);
}
$data = [];
if ('UNKNOWN' !== $application->getName()) {
$data['application']['name'] = $application->getName();
if ('UNKNOWN' !== $application->getVersion()) {
$data['application']['version'] = $application->getVersion();
}
}
$data['commands'] = $commands;
if ($describedNamespace) {
$data['namespace'] = $describedNamespace;
} else {
$data['namespaces'] = array_values($description->getNamespaces());
}
$this->writeData($data, $options);
}
private function writeData(array $data, array $options)
{
$flags = isset($options['json_encoding']) ? $options['json_encoding'] : 0;
$this->write(json_encode($data, $flags));
}
private function getInputArgumentData(InputArgument $argument)
{
return [
'name' => $argument->getName(),
'is_required' => $argument->isRequired(),
'is_array' => $argument->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()),
'default' => \INF === $argument->getDefault() ? 'INF' : $argument->getDefault(),
];
}
private function getInputOptionData(InputOption $option)
{
return [
'name' => '--'.$option->getName(),
'shortcut' => $option->getShortcut() ? '-'.str_replace('|', '|-', $option->getShortcut()) : '',
'accept_value' => $option->acceptValue(),
'is_value_required' => $option->isValueRequired(),
'is_multiple' => $option->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()),
'default' => \INF === $option->getDefault() ? 'INF' : $option->getDefault(),
];
}
private function getInputDefinitionData(InputDefinition $definition)
{
$inputArguments = [];
foreach ($definition->getArguments() as $name => $argument) {
$inputArguments[$name] = $this->getInputArgumentData($argument);
}
$inputOptions = [];
foreach ($definition->getOptions() as $name => $option) {
$inputOptions[$name] = $this->getInputOptionData($option);
}
return ['arguments' => $inputArguments, 'options' => $inputOptions];
}
private function getCommandData(Command $command)
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
return [
'name' => $command->getName(),
'usage' => array_merge([$command->getSynopsis()], $command->getUsages(), $command->getAliases()),
'description' => $command->getDescription(),
'help' => $command->getProcessedHelp(),
'definition' => $this->getInputDefinitionData($command->getNativeDefinition()),
'hidden' => $command->isHidden(),
];
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Output\OutputInterface;
interface DescriptorInterface
{
public function describe(OutputInterface $output, $object, array $options = []);
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class TextDescriptor extends Descriptor
{
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
} else {
$default = '';
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : Helper::strlen($argument->getName());
$spacingWidth = $totalWidth - \strlen($argument->getName());
$this->writeText(sprintf(' <info>%s</info> %s%s%s',
$argument->getName(),
str_repeat(' ', $spacingWidth),
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()),
$default
), $options);
}
protected function describeInputOption(InputOption $option, array $options = [])
{
if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
} else {
$default = '';
}
$value = '';
if ($option->acceptValue()) {
$value = '='.strtoupper($option->getName());
if ($option->isValueOptional()) {
$value = '['.$value.']';
}
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions([$option]);
$synopsis = sprintf('%s%s',
$option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ',
sprintf('--%s%s', $option->getName(), $value)
);
$spacingWidth = $totalWidth - Helper::strlen($synopsis);
$this->writeText(sprintf(' <info>%s</info> %s%s%s%s',
$synopsis,
str_repeat(' ', $spacingWidth),
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()),
$default,
$option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
), $options);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
foreach ($definition->getArguments() as $argument) {
$totalWidth = max($totalWidth, Helper::strlen($argument->getName()));
}
if ($definition->getArguments()) {
$this->writeText('<comment>Arguments:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getArguments() as $argument) {
$this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
$this->writeText("\n");
}
}
if ($definition->getArguments() && $definition->getOptions()) {
$this->writeText("\n");
}
if ($definition->getOptions()) {
$laterOptions = [];
$this->writeText('<comment>Options:</comment>', $options);
foreach ($definition->getOptions() as $option) {
if (\strlen($option->getShortcut()) > 1) {
$laterOptions[] = $option;
continue;
}
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
foreach ($laterOptions as $option) {
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
}
}
protected function describeCommand(Command $command, array $options = [])
{
$command->getSynopsis(true);
$command->getSynopsis(false);
$command->mergeApplicationDefinition(false);
$this->writeText('<comment>Usage:</comment>', $options);
foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
$this->writeText("\n");
$this->writeText(' '.OutputFormatter::escape($usage), $options);
}
$this->writeText("\n");
$definition = $command->getNativeDefinition();
if ($definition->getOptions() || $definition->getArguments()) {
$this->writeText("\n");
$this->describeInputDefinition($definition, $options);
$this->writeText("\n");
}
if ($help = $command->getProcessedHelp()) {
$this->writeText("\n");
$this->writeText('<comment>Help:</comment>', $options);
$this->writeText("\n");
$this->writeText(' '.str_replace("\n", "\n ", $help), $options);
$this->writeText("\n");
}
}
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
if (isset($options['raw_text']) && $options['raw_text']) {
$width = $this->getColumnWidth($description->getCommands());
foreach ($description->getCommands() as $command) {
$this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options);
$this->writeText("\n");
}
} else {
if ('' != $help = $application->getHelp()) {
$this->writeText("$help\n\n", $options);
}
$this->writeText("<comment>Usage:</comment>\n", $options);
$this->writeText(" command [options] [arguments]\n\n", $options);
$this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options);
$this->writeText("\n");
$this->writeText("\n");
$commands = $description->getCommands();
$namespaces = $description->getNamespaces();
if ($describedNamespace && $namespaces) {
$describedNamespaceInfo = reset($namespaces);
foreach ($describedNamespaceInfo['commands'] as $name) {
$commands[$name] = $description->getCommand($name);
}
}
$width = $this->getColumnWidth(\call_user_func_array('array_merge', array_map(function ($namespace) use ($commands) {
return array_intersect($namespace['commands'], array_keys($commands));
}, array_values($namespaces))));
if ($describedNamespace) {
$this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
} else {
$this->writeText('<comment>Available commands:</comment>', $options);
}
foreach ($namespaces as $namespace) {
$namespace['commands'] = array_filter($namespace['commands'], function ($name) use ($commands) {
return isset($commands[$name]);
});
if (!$namespace['commands']) {
continue;
}
if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
$this->writeText("\n");
$this->writeText(' <comment>'.$namespace['id'].'</comment>', $options);
}
foreach ($namespace['commands'] as $name) {
$this->writeText("\n");
$spacingWidth = $width - Helper::strlen($name);
$command = $commands[$name];
$commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : '';
$this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options);
}
}
$this->writeText("\n");
}
}
private function writeText($content, array $options = [])
{
$this->write(
isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
isset($options['raw_output']) ? !$options['raw_output'] : true
);
}
private function getCommandAliasesText(Command $command)
{
$text = '';
$aliases = $command->getAliases();
if ($aliases) {
$text = '['.implode('|', $aliases).'] ';
}
return $text;
}
private function formatDefaultValue($default)
{
if (\INF === $default) {
return 'INF';
}
if (\is_string($default)) {
$default = OutputFormatter::escape($default);
} elseif (\is_array($default)) {
foreach ($default as $key => $value) {
if (\is_string($value)) {
$default[$key] = OutputFormatter::escape($value);
}
}
}
return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE));
}
private function getColumnWidth(array $commands)
{
$widths = [];
foreach ($commands as $command) {
if ($command instanceof Command) {
$widths[] = Helper::strlen($command->getName());
foreach ($command->getAliases() as $alias) {
$widths[] = Helper::strlen($alias);
}
} else {
$widths[] = Helper::strlen($command);
}
}
return $widths ? max($widths) + 2 : 0;
}
private function calculateTotalWidthForOptions(array $options)
{
$totalWidth = 0;
foreach ($options as $option) {
$nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName());
if ($option->acceptValue()) {
$valueLength = 1 + Helper::strlen($option->getName());
$valueLength += $option->isValueOptional() ? 2 : 0;
$nameLength += $valueLength;
}
$totalWidth = max($totalWidth, $nameLength);
}
return $totalWidth;
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class XmlDescriptor extends Descriptor
{
public function getInputDefinitionDocument(InputDefinition $definition)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($definitionXML = $dom->createElement('definition'));
$definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
foreach ($definition->getArguments() as $argument) {
$this->appendDocument($argumentsXML, $this->getInputArgumentDocument($argument));
}
$definitionXML->appendChild($optionsXML = $dom->createElement('options'));
foreach ($definition->getOptions() as $option) {
$this->appendDocument($optionsXML, $this->getInputOptionDocument($option));
}
return $dom;
}
public function getCommandDocument(Command $command)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($commandXML = $dom->createElement('command'));
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
$commandXML->setAttribute('id', $command->getName());
$commandXML->setAttribute('name', $command->getName());
$commandXML->setAttribute('hidden', $command->isHidden() ? 1 : 0);
$commandXML->appendChild($usagesXML = $dom->createElement('usages'));
foreach (array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()) as $usage) {
$usagesXML->appendChild($dom->createElement('usage', $usage));
}
$commandXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getDescription())));
$commandXML->appendChild($helpXML = $dom->createElement('help'));
$helpXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getProcessedHelp())));
$definitionXML = $this->getInputDefinitionDocument($command->getNativeDefinition());
$this->appendDocument($commandXML, $definitionXML->getElementsByTagName('definition')->item(0));
return $dom;
}
public function getApplicationDocument(Application $application, $namespace = null)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($rootXml = $dom->createElement('symfony'));
if ('UNKNOWN' !== $application->getName()) {
$rootXml->setAttribute('name', $application->getName());
if ('UNKNOWN' !== $application->getVersion()) {
$rootXml->setAttribute('version', $application->getVersion());
}
}
$rootXml->appendChild($commandsXML = $dom->createElement('commands'));
$description = new ApplicationDescription($application, $namespace, true);
if ($namespace) {
$commandsXML->setAttribute('namespace', $namespace);
}
foreach ($description->getCommands() as $command) {
$this->appendDocument($commandsXML, $this->getCommandDocument($command));
}
if (!$namespace) {
$rootXml->appendChild($namespacesXML = $dom->createElement('namespaces'));
foreach ($description->getNamespaces() as $namespaceDescription) {
$namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
$namespaceArrayXML->setAttribute('id', $namespaceDescription['id']);
foreach ($namespaceDescription['commands'] as $name) {
$namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
$commandXML->appendChild($dom->createTextNode($name));
}
}
}
return $dom;
}
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->writeDocument($this->getInputArgumentDocument($argument));
}
protected function describeInputOption(InputOption $option, array $options = [])
{
$this->writeDocument($this->getInputOptionDocument($option));
}
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$this->writeDocument($this->getInputDefinitionDocument($definition));
}
protected function describeCommand(Command $command, array $options = [])
{
$this->writeDocument($this->getCommandDocument($command));
}
protected function describeApplication(Application $application, array $options = [])
{
$this->writeDocument($this->getApplicationDocument($application, isset($options['namespace']) ? $options['namespace'] : null));
}
private function appendDocument(\DOMNode $parentNode, \DOMNode $importedParent)
{
foreach ($importedParent->childNodes as $childNode) {
$parentNode->appendChild($parentNode->ownerDocument->importNode($childNode, true));
}
}
private function writeDocument(\DOMDocument $dom)
{
$dom->formatOutput = true;
$this->write($dom->saveXML());
}
private function getInputArgumentDocument(InputArgument $argument)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($objectXML = $dom->createElement('argument'));
$objectXML->setAttribute('name', $argument->getName());
$objectXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
$objectXML->setAttribute('is_array', $argument->isArray() ? 1 : 0);
$objectXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($argument->getDescription()));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$defaults = \is_array($argument->getDefault()) ? $argument->getDefault() : (\is_bool($argument->getDefault()) ? [var_export($argument->getDefault(), true)] : ($argument->getDefault() ? [$argument->getDefault()] : []));
foreach ($defaults as $default) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default));
}
return $dom;
}
private function getInputOptionDocument(InputOption $option)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($objectXML = $dom->createElement('option'));
$objectXML->setAttribute('name', '--'.$option->getName());
$pos = strpos($option->getShortcut(), '|');
if (false !== $pos) {
$objectXML->setAttribute('shortcut', '-'.substr($option->getShortcut(), 0, $pos));
$objectXML->setAttribute('shortcuts', '-'.str_replace('|', '|-', $option->getShortcut()));
} else {
$objectXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
}
$objectXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0);
$objectXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0);
$objectXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0);
$objectXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
if ($option->acceptValue()) {
$defaults = \is_array($option->getDefault()) ? $option->getDefault() : (\is_bool($option->getDefault()) ? [var_export($option->getDefault(), true)] : ($option->getDefault() ? [$option->getDefault()] : []));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
if (!empty($defaults)) {
foreach ($defaults as $default) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default));
}
}
}
return $dom;
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class HelpCommand extends Command
{
private $command;
protected function configure()
{
$this->ignoreValidationErrors();
$this
->setName('help')
->setDefinition([
new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
])
->setDescription('Displays help for a command')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command displays help for a given command:
<info>php %command.full_name% list</info>
You can also output the help in other formats by using the <comment>--format</comment> option:
<info>php %command.full_name% --format=xml list</info>
To display the list of available commands, please use the <info>list</info> command.
EOF
)
;
}
public function setCommand(Command $command)
{
$this->command = $command;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (null === $this->command) {
$this->command = $this->getApplication()->find($input->getArgument('command_name'));
}
$helper = new DescriptorHelper();
$helper->describe($output, $this->command, [
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
]);
$this->command = null;
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListCommand extends Command
{
protected function configure()
{
$this
->setName('list')
->setDefinition($this->createDefinition())
->setDescription('Lists commands')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command lists all commands:
<info>php %command.full_name%</info>
You can also display the commands for a specific namespace:
<info>php %command.full_name% test</info>
You can also output the information in other formats by using the <comment>--format</comment> option:
<info>php %command.full_name% --format=xml</info>
It's also possible to get raw list of commands (useful for embedding command runner):
<info>php %command.full_name% --raw</info>
EOF
)
;
}
public function getNativeDefinition()
{
return $this->createDefinition();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$helper = new DescriptorHelper();
$helper->describe($output, $this->getApplication(), [
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
'namespace' => $input->getArgument('namespace'),
]);
}
private function createDefinition()
{
return new InputDefinition([
new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
]);
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Command
{
protected static $defaultName;
private $application;
private $name;
private $processTitle;
private $aliases = [];
private $definition;
private $hidden = false;
private $help = '';
private $description = '';
private $ignoreValidationErrors = false;
private $applicationDefinitionMerged = false;
private $applicationDefinitionMergedWithArgs = false;
private $code;
private $synopsis = [];
private $usages = [];
private $helperSet;
public static function getDefaultName()
{
$class = static::class;
$r = new \ReflectionProperty($class, 'defaultName');
return $class === $r->class ? static::$defaultName : null;
}
public function __construct($name = null)
{
$this->definition = new InputDefinition();
if (null !== $name || null !== $name = static::getDefaultName()) {
$this->setName($name);
}
$this->configure();
}
public function ignoreValidationErrors()
{
$this->ignoreValidationErrors = true;
}
public function setApplication(Application $application = null)
{
$this->application = $application;
if ($application) {
$this->setHelperSet($application->getHelperSet());
} else {
$this->helperSet = null;
}
}
public function setHelperSet(HelperSet $helperSet)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
return $this->helperSet;
}
public function getApplication()
{
return $this->application;
}
public function isEnabled()
{
return true;
}
protected function configure()
{
}
protected function execute(InputInterface $input, OutputInterface $output)
{
throw new LogicException('You must override the execute() method in the concrete command class.');
}
protected function interact(InputInterface $input, OutputInterface $output)
{
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
}
public function run(InputInterface $input, OutputInterface $output)
{
$this->getSynopsis(true);
$this->getSynopsis(false);
$this->mergeApplicationDefinition();
try {
$input->bind($this->definition);
} catch (ExceptionInterface $e) {
if (!$this->ignoreValidationErrors) {
throw $e;
}
}
$this->initialize($input, $output);
if (null !== $this->processTitle) {
if (\function_exists('cli_set_process_title')) {
if (!@cli_set_process_title($this->processTitle)) {
if ('Darwin' === \PHP_OS) {
$output->writeln('<comment>Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE);
} else {
cli_set_process_title($this->processTitle);
}
}
} elseif (\function_exists('setproctitle')) {
setproctitle($this->processTitle);
} elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
$output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
}
}
if ($input->isInteractive()) {
$this->interact($input, $output);
}
if ($input->hasArgument('command') && null === $input->getArgument('command')) {
$input->setArgument('command', $this->getName());
}
$input->validate();
if ($this->code) {
$statusCode = \call_user_func($this->code, $input, $output);
} else {
$statusCode = $this->execute($input, $output);
}
return is_numeric($statusCode) ? (int) $statusCode : 0;
}
public function setCode(callable $code)
{
if ($code instanceof \Closure) {
$r = new \ReflectionFunction($code);
if (null === $r->getClosureThis()) {
if (\PHP_VERSION_ID < 70000) {
$code = @\Closure::bind($code, $this);
} else {
$code = \Closure::bind($code, $this);
}
}
}
$this->code = $code;
return $this;
}
public function mergeApplicationDefinition($mergeArgs = true)
{
if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
return;
}
$this->definition->addOptions($this->application->getDefinition()->getOptions());
$this->applicationDefinitionMerged = true;
if ($mergeArgs) {
$currentArguments = $this->definition->getArguments();
$this->definition->setArguments($this->application->getDefinition()->getArguments());
$this->definition->addArguments($currentArguments);
$this->applicationDefinitionMergedWithArgs = true;
}
}
public function setDefinition($definition)
{
if ($definition instanceof InputDefinition) {
$this->definition = $definition;
} else {
$this->definition->setDefinition($definition);
}
$this->applicationDefinitionMerged = false;
return $this;
}
public function getDefinition()
{
if (null === $this->definition) {
throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', static::class));
}
return $this->definition;
}
public function getNativeDefinition()
{
return $this->getDefinition();
}
public function addArgument($name, $mode = null, $description = '', $default = null)
{
$this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
return $this;
}
public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
{
$this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
return $this;
}
public function setName($name)
{
$this->validateName($name);
$this->name = $name;
return $this;
}
public function setProcessTitle($title)
{
$this->processTitle = $title;
return $this;
}
public function getName()
{
return $this->name;
}
public function setHidden($hidden)
{
$this->hidden = (bool) $hidden;
return $this;
}
public function isHidden()
{
return $this->hidden;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setHelp($help)
{
$this->help = $help;
return $this;
}
public function getHelp()
{
return $this->help;
}
public function getProcessedHelp()
{
$name = $this->name;
$isSingleCommand = $this->application && $this->application->isSingleCommand();
$placeholders = [
'%command.name%',
'%command.full_name%',
];
$replacements = [
$name,
$isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name,
];
return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
}
public function setAliases($aliases)
{
if (!\is_array($aliases) && !$aliases instanceof \Traversable) {
throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable.');
}
foreach ($aliases as $alias) {
$this->validateName($alias);
}
$this->aliases = $aliases;
return $this;
}
public function getAliases()
{
return $this->aliases;
}
public function getSynopsis($short = false)
{
$key = $short ? 'short' : 'long';
if (!isset($this->synopsis[$key])) {
$this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
}
return $this->synopsis[$key];
}
public function addUsage($usage)
{
if (0 !== strpos($usage, $this->name)) {
$usage = sprintf('%s %s', $this->name, $usage);
}
$this->usages[] = $usage;
return $this;
}
public function getUsages()
{
return $this->usages;
}
public function getHelper($name)
{
if (null === $this->helperSet) {
throw new LogicException(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name));
}
return $this->helperSet->get($name);
}
private function validateName($name)
{
if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
}
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Lock\Factory;
use Symfony\Component\Lock\Lock;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\SemaphoreStore;
trait LockableTrait
{
private $lock;
private function lock($name = null, $blocking = false)
{
if (!class_exists(SemaphoreStore::class)) {
throw new RuntimeException('To enable the locking feature you must install the symfony/lock component.');
}
if (null !== $this->lock) {
throw new LogicException('A lock is already in place.');
}
if (SemaphoreStore::isSupported($blocking)) {
$store = new SemaphoreStore();
} else {
$store = new FlockStore();
}
$this->lock = (new Factory($store))->createLock($name ?: $this->getName());
if (!$this->lock->acquire($blocking)) {
$this->lock = null;
return false;
}
return true;
}
private function release()
{
if ($this->lock) {
$this->lock->release();
$this->lock = null;
}
}
}
<?php
namespace Symfony\Component\Console\Tester;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
/**
@gmail
*/
class CommandTester
{
private $command;
private $input;
private $output;
private $inputs = [];
private $statusCode;
public function __construct(Command $command)
{
$this->command = $command;
}
public function execute(array $input, array $options = [])
{
if (!isset($input['command'])
&& (null !== $application = $this->command->getApplication())
&& $application->getDefinition()->hasArgument('command')
) {
$input = array_merge(['command' => $this->command->getName()], $input);
}
$this->input = new ArrayInput($input);
$this->input->setStream(self::createStream($this->inputs));
if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);
}
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
$this->output->setDecorated(isset($options['decorated']) ? $options['decorated'] : false);
if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
return $this->statusCode = $this->command->run($this->input, $this->output);
}
public function getDisplay($normalize = false)
{
if (null === $this->output) {
throw new \RuntimeException('Output not initialized, did you execute the command before requesting the display?');
}
rewind($this->output->getStream());
$display = stream_get_contents($this->output->getStream());
if ($normalize) {
$display = str_replace(\PHP_EOL, "\n", $display);
}
return $display;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setInputs(array $inputs)
{
$this->inputs = $inputs;
return $this;
}
private static function createStream(array $inputs)
{
$stream = fopen('php://memory', 'r+', false);
foreach ($inputs as $input) {
fwrite($stream, $input.\PHP_EOL);
}
rewind($stream);
return $stream;
}
}
<?php
namespace Symfony\Component\Console\Tester;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
class ApplicationTester
{
private $application;
private $input;
private $statusCode;
private $output;
private $captureStreamsIndependently = false;
public function __construct(Application $application)
{
$this->application = $application;
}
public function run(array $input, $options = [])
{
$this->input = new ArrayInput($input);
if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);
}
$this->captureStreamsIndependently = \array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately'];
if (!$this->captureStreamsIndependently) {
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
} else {
$this->output = new ConsoleOutput(
isset($options['verbosity']) ? $options['verbosity'] : ConsoleOutput::VERBOSITY_NORMAL,
isset($options['decorated']) ? $options['decorated'] : null
);
$errorOutput = new StreamOutput(fopen('php://memory', 'w', false));
$errorOutput->setFormatter($this->output->getFormatter());
$errorOutput->setVerbosity($this->output->getVerbosity());
$errorOutput->setDecorated($this->output->isDecorated());
$reflectedOutput = new \ReflectionObject($this->output);
$strErrProperty = $reflectedOutput->getProperty('stderr');
$strErrProperty->setAccessible(true);
$strErrProperty->setValue($this->output, $errorOutput);
$reflectedParent = $reflectedOutput->getParentClass();
$streamProperty = $reflectedParent->getProperty('stream');
$streamProperty->setAccessible(true);
$streamProperty->setValue($this->output, fopen('php://memory', 'w', false));
}
return $this->statusCode = $this->application->run($this->input, $this->output);
}
public function getDisplay($normalize = false)
{
rewind($this->output->getStream());
$display = stream_get_contents($this->output->getStream());
if ($normalize) {
$display = str_replace(\PHP_EOL, "\n", $display);
}
return $display;
}
public function getErrorOutput($normalize = false)
{
if (!$this->captureStreamsIndependently) {
throw new \LogicException('The error output is not available when the tester is run without "capture_stderr_separately" option set.');
}
rewind($this->output->getErrorOutput()->getStream());
$display = stream_get_contents($this->output->getErrorOutput()->getStream());
if ($normalize) {
$display = str_replace(\PHP_EOL, "\n", $display);
}
return $display;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
public function getStatusCode()
{
return $this->statusCode;
}
}
<?php
namespace Symfony\Component\Console\Helper;
class DebugFormatterHelper extends Helper
{
private $colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default'];
private $started = [];
private $count = -1;
public function start($id, $message, $prefix = 'RUN')
{
$this->started[$id] = ['border' => ++$this->count % \count($this->colors)];
return sprintf("%s<bg=blue;fg=white> %s </> <fg=blue>%s</>\n", $this->getBorder($id), $prefix, $message);
}
public function progress($id, $buffer, $error = false, $prefix = 'OUT', $errorPrefix = 'ERR')
{
$message = '';
if ($error) {
if (isset($this->started[$id]['out'])) {
$message .= "\n";
unset($this->started[$id]['out']);
}
if (!isset($this->started[$id]['err'])) {
$message .= sprintf('%s<bg=red;fg=white> %s </> ', $this->getBorder($id), $errorPrefix);
$this->started[$id]['err'] = true;
}
$message .= str_replace("\n", sprintf("\n%s<bg=red;fg=white> %s </> ", $this->getBorder($id), $errorPrefix), $buffer);
} else {
if (isset($this->started[$id]['err'])) {
$message .= "\n";
unset($this->started[$id]['err']);
}
if (!isset($this->started[$id]['out'])) {
$message .= sprintf('%s<bg=green;fg=white> %s </> ', $this->getBorder($id), $prefix);
$this->started[$id]['out'] = true;
}
$message .= str_replace("\n", sprintf("\n%s<bg=green;fg=white> %s </> ", $this->getBorder($id), $prefix), $buffer);
}
return $message;
}
public function stop($id, $message, $successful, $prefix = 'RES')
{
$trailingEOL = isset($this->started[$id]['out']) || isset($this->started[$id]['err']) ? "\n" : '';
if ($successful) {
return sprintf("%s%s<bg=green;fg=white> %s </> <fg=green>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
}
$message = sprintf("%s%s<bg=red;fg=white> %s </> <fg=red>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
unset($this->started[$id]['out'], $this->started[$id]['err']);
return $message;
}
private function getBorder($id)
{
return sprintf('<bg=%s> </>', $this->colors[$this->started[$id]['border']]);
}
public function getName()
{
return 'debug_formatter';
}
}
<?php
namespace Symfony\Component\Console\Helper;
interface HelperInterface
{
public function setHelperSet(HelperSet $helperSet = null);
public function getHelperSet();
public function getName();
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class ProcessHelper extends Helper
{
public function run(OutputInterface $output, $cmd, $error = null, callable $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE)
{
if (!class_exists(Process::class)) {
throw new \LogicException('The ProcessHelper cannot be run as the Process component is not installed. Try running "compose require symfony/process".');
}
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$formatter = $this->getHelperSet()->get('debug_formatter');
if ($cmd instanceof Process) {
$process = $cmd;
} else {
$process = new Process($cmd);
}
if ($verbosity <= $output->getVerbosity()) {
$output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine())));
}
if ($output->isDebug()) {
$callback = $this->wrapCallback($output, $process, $callback);
}
$process->run($callback);
if ($verbosity <= $output->getVerbosity()) {
$message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode());
$output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
}
if (!$process->isSuccessful() && null !== $error) {
$output->writeln(sprintf('<error>%s</error>', $this->escapeString($error)));
}
return $process;
}
public function mustRun(OutputInterface $output, $cmd, $error = null, callable $callback = null)
{
$process = $this->run($output, $cmd, $error, $callback);
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $process;
}
public function wrapCallback(OutputInterface $output, Process $process, callable $callback = null)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$formatter = $this->getHelperSet()->get('debug_formatter');
return function ($type, $buffer) use ($output, $process, $callback, $formatter) {
$output->write($formatter->progress(spl_object_hash($process), $this->escapeString($buffer), Process::ERR === $type));
if (null !== $callback) {
\call_user_func($callback, $type, $buffer);
}
};
}
private function escapeString($str)
{
return str_replace('<', '\\<', $str);
}
public function getName()
{
return 'process';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Input\InputAwareInterface;
use Symfony\Component\Console\Input\InputInterface;
abstract class InputAwareHelper extends Helper implements InputAwareInterface
{
protected $input;
public function setInput(InputInterface $input)
{
$this->input = $input;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
abstract class Helper implements HelperInterface
{
protected $helperSet = null;
public function setHelperSet(HelperSet $helperSet = null)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
return $this->helperSet;
}
public static function strlen($string)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return \strlen($string);
}
return mb_strwidth($string, $encoding);
}
public static function substr($string, $from, $length = null)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return substr($string, $from, $length);
}
return mb_substr($string, $from, $length, $encoding);
}
public static function formatTime($secs)
{
static $timeFormats = [
[0, '< 1 sec'],
[1, '1 sec'],
[2, 'secs', 1],
[60, '1 min'],
[120, 'mins', 60],
[3600, '1 hr'],
[7200, 'hrs', 3600],
[86400, '1 day'],
[172800, 'days', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
|| $index == \count($timeFormats) - 1
) {
if (2 == \count($format)) {
return $format[1];
}
return floor($secs / $format[2]).' '.$format[1];
}
}
}
}
public static function formatMemory($memory)
{
if ($memory >= 1024 * 1024 * 1024) {
return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
}
if ($memory >= 1024 * 1024) {
return sprintf('%.1f MiB', $memory / 1024 / 1024);
}
if ($memory >= 1024) {
return sprintf('%d KiB', $memory / 1024);
}
return sprintf('%d B', $memory);
}
public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
{
return self::strlen(self::removeDecoration($formatter, $string));
}
public static function removeDecoration(OutputFormatterInterface $formatter, $string)
{
$isDecorated = $formatter->isDecorated();
$formatter->setDecorated(false);
$string = $formatter->format($string);
$string = preg_replace("/\033\[[^m]*m/", '', $string);
$formatter->setDecorated($isDecorated);
return $string;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Output\OutputInterface;
/**
@gmail
@gmail
@gmail
*/
class Table
{
private $headers = [];
private $rows = [];
private $effectiveColumnWidths = [];
private $numberOfColumns;
private $output;
private $style;
private $columnStyles = [];
private $columnWidths = [];
private static $styles;
public function __construct(OutputInterface $output)
{
$this->output = $output;
if (!self::$styles) {
self::$styles = self::initStyles();
}
$this->setStyle('default');
}
public static function setStyleDefinition($name, TableStyle $style)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
self::$styles[$name] = $style;
}
public static function getStyleDefinition($name)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
if (isset(self::$styles[$name])) {
return self::$styles[$name];
}
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
public function setStyle($name)
{
$this->style = $this->resolveStyle($name);
return $this;
}
public function getStyle()
{
return $this->style;
}
public function setColumnStyle($columnIndex, $name)
{
$columnIndex = (int) $columnIndex;
$this->columnStyles[$columnIndex] = $this->resolveStyle($name);
return $this;
}
public function getColumnStyle($columnIndex)
{
if (isset($this->columnStyles[$columnIndex])) {
return $this->columnStyles[$columnIndex];
}
return $this->getStyle();
}
public function setColumnWidth($columnIndex, $width)
{
$this->columnWidths[(int) $columnIndex] = (int) $width;
return $this;
}
public function setColumnWidths(array $widths)
{
$this->columnWidths = [];
foreach ($widths as $index => $width) {
$this->setColumnWidth($index, $width);
}
return $this;
}
public function setHeaders(array $headers)
{
$headers = array_values($headers);
if (!empty($headers) && !\is_array($headers[0])) {
$headers = [$headers];
}
$this->headers = $headers;
return $this;
}
public function setRows(array $rows)
{
$this->rows = [];
return $this->addRows($rows);
}
public function addRows(array $rows)
{
foreach ($rows as $row) {
$this->addRow($row);
}
return $this;
}
public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rows[] = $row;
return $this;
}
if (!\is_array($row)) {
throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rows[] = array_values($row);
return $this;
}
public function setRow($column, array $row)
{
$this->rows[$column] = $row;
return $this;
}
public function render()
{
$this->calculateNumberOfColumns();
$rows = $this->buildTableRows($this->rows);
$headers = $this->buildTableRows($this->headers);
$this->calculateColumnsWidth(array_merge($headers, $rows));
$this->renderRowSeparator();
if (!empty($headers)) {
foreach ($headers as $header) {
$this->renderRow($header, $this->style->getCellHeaderFormat());
$this->renderRowSeparator();
}
}
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
$this->renderRowSeparator();
} else {
$this->renderRow($row, $this->style->getCellRowFormat());
}
}
if (!empty($rows)) {
$this->renderRowSeparator();
}
$this->cleanup();
}
private function renderRowSeparator()
{
if (0 === $count = $this->numberOfColumns) {
return;
}
if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
return;
}
$markup = $this->style->getCrossingChar();
for ($column = 0; $column < $count; ++$column) {
$markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
}
$this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
}
private function renderColumnSeparator()
{
return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
}
private function renderRow(array $row, $cellFormat)
{
if (empty($row)) {
return;
}
$rowContent = $this->renderColumnSeparator();
foreach ($this->getRowColumns($row) as $column) {
$rowContent .= $this->renderCell($row, $column, $cellFormat);
$rowContent .= $this->renderColumnSeparator();
}
$this->output->writeln($rowContent);
}
private function renderCell(array $row, $column, $cellFormat)
{
$cell = isset($row[$column]) ? $row[$column] : '';
$width = $this->effectiveColumnWidths[$column];
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
$width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
}
}
if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
$width += \strlen($cell) - mb_strwidth($cell, $encoding);
}
$style = $this->getColumnStyle($column);
if ($cell instanceof TableSeparator) {
return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
}
$width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
$content = sprintf($style->getCellRowContentFormat(), $cell);
return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
}
private function calculateNumberOfColumns()
{
if (null !== $this->numberOfColumns) {
return;
}
$columns = [0];
foreach (array_merge($this->headers, $this->rows) as $row) {
if ($row instanceof TableSeparator) {
continue;
}
$columns[] = $this->getNumberOfColumns($row);
}
$this->numberOfColumns = max($columns);
}
private function buildTableRows($rows)
{
$unmergedRows = [];
for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
$rows = $this->fillNextRows($rows, $rowKey);
foreach ($rows[$rowKey] as $column => $cell) {
if (!strstr($cell, "\n")) {
continue;
}
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
foreach ($lines as $lineKey => $line) {
if ($cell instanceof TableCell) {
$line = new TableCell($line, ['colspan' => $cell->getColspan()]);
}
if (0 === $lineKey) {
$rows[$rowKey][$column] = $line;
} else {
$unmergedRows[$rowKey][$lineKey][$column] = $line;
}
}
}
}
$tableRows = [];
foreach ($rows as $rowKey => $row) {
$tableRows[] = $this->fillCells($row);
if (isset($unmergedRows[$rowKey])) {
$tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
}
}
return $tableRows;
}
private function fillNextRows(array $rows, $line)
{
$unmergedRows = [];
foreach ($rows[$line] as $column => $cell) {
if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', \gettype($cell)));
}
if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
$nbLines = $cell->getRowspan() - 1;
$lines = [$cell];
if (strstr($cell, "\n")) {
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
$nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
$rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]);
unset($lines[0]);
}
$unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
$value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
$unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]);
if ($nbLines === $unmergedRowKey - $line) {
break;
}
}
}
}
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
foreach ($unmergedRow as $cellKey => $cell) {
array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
}
} else {
$row = $this->copyRow($rows, $unmergedRowKey - 1);
foreach ($unmergedRow as $column => $cell) {
if (!empty($cell)) {
$row[$column] = $unmergedRow[$column];
}
}
array_splice($rows, $unmergedRowKey, 0, [$row]);
}
}
return $rows;
}
private function fillCells($row)
{
$newRow = [];
foreach ($row as $column => $cell) {
$newRow[] = $cell;
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
$newRow[] = '';
}
}
}
return $newRow ?: $row;
}
private function copyRow(array $rows, $line)
{
$row = $rows[$line];
foreach ($row as $cellKey => $cellValue) {
$row[$cellKey] = '';
if ($cellValue instanceof TableCell) {
$row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
}
}
return $row;
}
private function getNumberOfColumns(array $row)
{
$columns = \count($row);
foreach ($row as $column) {
$columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
}
return $columns;
}
private function getRowColumns(array $row)
{
$columns = range(0, $this->numberOfColumns - 1);
foreach ($row as $cellKey => $cell) {
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
$columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
}
}
return $columns;
}
private function calculateColumnsWidth(array $rows)
{
for ($column = 0; $column < $this->numberOfColumns; ++$column) {
$lengths = [];
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
continue;
}
foreach ($row as $i => $cell) {
if ($cell instanceof TableCell) {
$textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
$textLength = Helper::strlen($textContent);
if ($textLength > 0) {
$contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
foreach ($contentColumns as $position => $content) {
$row[$i + $position] = $content;
}
}
}
}
$lengths[] = $this->getCellWidth($row, $column);
}
$this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
}
}
private function getColumnSeparatorWidth()
{
return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
}
private function getCellWidth(array $row, $column)
{
$cellWidth = 0;
if (isset($row[$column])) {
$cell = $row[$column];
$cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
}
$columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
return max($cellWidth, $columnWidth);
}
private function cleanup()
{
$this->effectiveColumnWidths = [];
$this->numberOfColumns = null;
}
private static function initStyles()
{
$borderless = new TableStyle();
$borderless
->setHorizontalBorderChar('=')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
;
$compact = new TableStyle();
$compact
->setHorizontalBorderChar('')
->setVerticalBorderChar(' ')
->setCrossingChar('')
->setCellRowContentFormat('%s')
;
$styleGuide = new TableStyle();
$styleGuide
->setHorizontalBorderChar('-')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
->setCellHeaderFormat('%s')
;
return [
'default' => new TableStyle(),
'borderless' => $borderless,
'compact' => $compact,
'symfony-style-guide' => $styleGuide,
];
}
private function resolveStyle($name)
{
if ($name instanceof TableStyle) {
return $name;
}
if (isset(self::$styles[$name])) {
return self::$styles[$name];
}
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Descriptor\DescriptorInterface;
use Symfony\Component\Console\Descriptor\JsonDescriptor;
use Symfony\Component\Console\Descriptor\MarkdownDescriptor;
use Symfony\Component\Console\Descriptor\TextDescriptor;
use Symfony\Component\Console\Descriptor\XmlDescriptor;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Output\OutputInterface;
class DescriptorHelper extends Helper
{
private $descriptors = [];
public function __construct()
{
$this
->register('txt', new TextDescriptor())
->register('xml', new XmlDescriptor())
->register('json', new JsonDescriptor())
->register('md', new MarkdownDescriptor())
;
}
public function describe(OutputInterface $output, $object, array $options = [])
{
$options = array_merge([
'raw_text' => false,
'format' => 'txt',
], $options);
if (!isset($this->descriptors[$options['format']])) {
throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
}
$descriptor = $this->descriptors[$options['format']];
$descriptor->describe($output, $object, $options);
}
public function register($format, DescriptorInterface $descriptor)
{
$this->descriptors[$format] = $descriptor;
return $this;
}
public function getName()
{
return 'descriptor';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
class SymfonyQuestionHelper extends QuestionHelper
{
public function ask(InputInterface $input, OutputInterface $output, Question $question)
{
$validator = $question->getValidator();
$question->setValidator(function ($value) use ($validator) {
if (null !== $validator) {
$value = $validator($value);
} else {
if (!\is_array($value) && !\is_bool($value) && 0 === \strlen($value)) {
@trigger_error('The default question validator is deprecated since Symfony 3.3 and will not be used anymore in version 4.0. Set a custom question validator if needed.', \E_USER_DEPRECATED);
throw new LogicException('A value is required.');
}
}
return $value;
});
return parent::ask($input, $output, $question);
}
protected function writePrompt(OutputInterface $output, Question $question)
{
$text = OutputFormatter::escapeTrailingBackslash($question->getQuestion());
$default = $question->getDefault();
switch (true) {
case null === $default:
$text = sprintf(' <info>%s</info>:', $text);
break;
case $question instanceof ConfirmationQuestion:
$text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
break;
case $question instanceof ChoiceQuestion && $question->isMultiselect():
$choices = $question->getChoices();
$default = explode(',', $default);
foreach ($default as $key => $value) {
$default[$key] = $choices[trim($value)];
}
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape(implode(', ', $default)));
break;
case $question instanceof ChoiceQuestion:
$choices = $question->getChoices();
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape(isset($choices[$default]) ? $choices[$default] : $default));
break;
default:
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($default));
}
$output->writeln($text);
$prompt = ' > ';
if ($question instanceof ChoiceQuestion) {
$output->writeln($this->formatChoiceQuestionChoices($question, 'comment'));
$prompt = $question->getPrompt();
}
$output->write($prompt);
}
protected function writeError(OutputInterface $output, \Exception $error)
{
if ($output instanceof SymfonyStyle) {
$output->newLine();
$output->error($error->getMessage());
return;
}
parent::writeError($output, $error);
}
}
<?php
namespace Symfony\Component\Console\Helper;
class TableSeparator extends TableCell
{
public function __construct(array $options = [])
{
parent::__construct('', $options);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Formatter\OutputFormatter;
class FormatterHelper extends Helper
{
public function formatSection($section, $message, $style = 'info')
{
return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
}
public function formatBlock($messages, $style, $large = false)
{
if (!\is_array($messages)) {
$messages = [$messages];
}
$len = 0;
$lines = [];
foreach ($messages as $message) {
$message = OutputFormatter::escape($message);
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max(self::strlen($message) + ($large ? 4 : 2), $len);
}
$messages = $large ? [str_repeat(' ', $len)] : [];
for ($i = 0; isset($lines[$i]); ++$i) {
$messages[] = $lines[$i].str_repeat(' ', $len - self::strlen($lines[$i]));
}
if ($large) {
$messages[] = str_repeat(' ', $len);
}
for ($i = 0; isset($messages[$i]); ++$i) {
$messages[$i] = sprintf('<%s>%s</%s>', $style, $messages[$i], $style);
}
return implode("\n", $messages);
}
public function truncate($message, $length, $suffix = '...')
{
$computedLength = $length - self::strlen($suffix);
if ($computedLength > self::strlen($message)) {
return $message;
}
return self::substr($message, 0, $length).$suffix;
}
public function getName()
{
return 'formatter';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class HelperSet implements \IteratorAggregate
{
private $helpers = [];
private $command;
public function __construct(array $helpers = [])
{
foreach ($helpers as $alias => $helper) {
$this->set($helper, \is_int($alias) ? null : $alias);
}
}
public function set(HelperInterface $helper, $alias = null)
{
$this->helpers[$helper->getName()] = $helper;
if (null !== $alias) {
$this->helpers[$alias] = $helper;
}
$helper->setHelperSet($this);
}
public function has($name)
{
return isset($this->helpers[$name]);
}
public function get($name)
{
if (!$this->has($name)) {
throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
}
return $this->helpers[$name];
}
public function setCommand(Command $command = null)
{
$this->command = $command;
}
public function getCommand()
{
return $this->command;
}
public function getIterator()
{
return new \ArrayIterator($this->helpers);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
/**
@gmail
*/
class TableStyle
{
private $paddingChar = ' ';
private $horizontalBorderChar = '-';
private $verticalBorderChar = '|';
private $crossingChar = '+';
private $cellHeaderFormat = '<info>%s</info>';
private $cellRowFormat = '%s';
private $cellRowContentFormat = ' %s ';
private $borderFormat = '%s';
private $padType = \STR_PAD_RIGHT;
public function setPaddingChar($paddingChar)
{
if (!$paddingChar) {
throw new LogicException('The padding char must not be empty.');
}
$this->paddingChar = $paddingChar;
return $this;
}
public function getPaddingChar()
{
return $this->paddingChar;
}
public function setHorizontalBorderChar($horizontalBorderChar)
{
$this->horizontalBorderChar = $horizontalBorderChar;
return $this;
}
public function getHorizontalBorderChar()
{
return $this->horizontalBorderChar;
}
public function setVerticalBorderChar($verticalBorderChar)
{
$this->verticalBorderChar = $verticalBorderChar;
return $this;
}
public function getVerticalBorderChar()
{
return $this->verticalBorderChar;
}
public function setCrossingChar($crossingChar)
{
$this->crossingChar = $crossingChar;
return $this;
}
public function getCrossingChar()
{
return $this->crossingChar;
}
public function setCellHeaderFormat($cellHeaderFormat)
{
$this->cellHeaderFormat = $cellHeaderFormat;
return $this;
}
public function getCellHeaderFormat()
{
return $this->cellHeaderFormat;
}
public function setCellRowFormat($cellRowFormat)
{
$this->cellRowFormat = $cellRowFormat;
return $this;
}
public function getCellRowFormat()
{
return $this->cellRowFormat;
}
public function setCellRowContentFormat($cellRowContentFormat)
{
$this->cellRowContentFormat = $cellRowContentFormat;
return $this;
}
public function getCellRowContentFormat()
{
return $this->cellRowContentFormat;
}
public function setBorderFormat($borderFormat)
{
$this->borderFormat = $borderFormat;
return $this;
}
public function getBorderFormat()
{
return $this->borderFormat;
}
public function setPadType($padType)
{
if (!\in_array($padType, [\STR_PAD_LEFT, \STR_PAD_RIGHT, \STR_PAD_BOTH], true)) {
throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).');
}
$this->padType = $padType;
return $this;
}
public function getPadType()
{
return $this->padType;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class TableCell
{
private $value;
private $options = [
'rowspan' => 1,
'colspan' => 1,
];
public function __construct($value = '', array $options = [])
{
if (is_numeric($value) && !\is_string($value)) {
$value = (string) $value;
}
$this->value = $value;
if ($diff = array_diff(array_keys($options), array_keys($this->options))) {
throw new InvalidArgumentException(sprintf('The TableCell does not support the following options: \'%s\'.', implode('\', \'', $diff)));
}
$this->options = array_merge($this->options, $options);
}
public function __toString()
{
return $this->value;
}
public function getColspan()
{
return (int) $this->options['colspan'];
}
public function getRowspan()
{
return (int) $this->options['rowspan'];
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Output\OutputInterface;
class ProgressIndicator
{
private $output;
private $startTime;
private $format;
private $message;
private $indicatorValues;
private $indicatorCurrent;
private $indicatorChangeInterval;
private $indicatorUpdateTime;
private $started = false;
private static $formatters;
private static $formats;
public function __construct(OutputInterface $output, $format = null, $indicatorChangeInterval = 100, $indicatorValues = null)
{
$this->output = $output;
if (null === $format) {
$format = $this->determineBestFormat();
}
if (null === $indicatorValues) {
$indicatorValues = ['-', '\\', '|', '/'];
}
$indicatorValues = array_values($indicatorValues);
if (2 > \count($indicatorValues)) {
throw new InvalidArgumentException('Must have at least 2 indicator value characters.');
}
$this->format = self::getFormatDefinition($format);
$this->indicatorChangeInterval = $indicatorChangeInterval;
$this->indicatorValues = $indicatorValues;
$this->startTime = time();
}
public function setMessage($message)
{
$this->message = $message;
$this->display();
}
public function start($message)
{
if ($this->started) {
throw new LogicException('Progress indicator already started.');
}
$this->message = $message;
$this->started = true;
$this->startTime = time();
$this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval;
$this->indicatorCurrent = 0;
$this->display();
}
public function advance()
{
if (!$this->started) {
throw new LogicException('Progress indicator has not yet been started.');
}
if (!$this->output->isDecorated()) {
return;
}
$currentTime = $this->getCurrentTimeInMilliseconds();
if ($currentTime < $this->indicatorUpdateTime) {
return;
}
$this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval;
++$this->indicatorCurrent;
$this->display();
}
public function finish($message)
{
if (!$this->started) {
throw new LogicException('Progress indicator has not yet been started.');
}
$this->message = $message;
$this->display();
$this->output->writeln('');
$this->started = false;
}
public static function getFormatDefinition($name)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
return isset(self::$formats[$name]) ? self::$formats[$name] : null;
}
public static function setPlaceholderFormatterDefinition($name, $callable)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
self::$formatters[$name] = $callable;
}
public static function getPlaceholderFormatterDefinition($name)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
}
private function display()
{
if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
return;
}
$self = $this;
$this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self) {
if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
return \call_user_func($formatter, $self);
}
return $matches[0];
}, $this->format));
}
private function determineBestFormat()
{
switch ($this->output->getVerbosity()) {
case OutputInterface::VERBOSITY_VERBOSE:
return $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi';
case OutputInterface::VERBOSITY_VERY_VERBOSE:
case OutputInterface::VERBOSITY_DEBUG:
return $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi';
default:
return $this->output->isDecorated() ? 'normal' : 'normal_no_ansi';
}
}
private function overwrite($message)
{
if ($this->output->isDecorated()) {
$this->output->write("\x0D\x1B[2K");
$this->output->write($message);
} else {
$this->output->writeln($message);
}
}
private function getCurrentTimeInMilliseconds()
{
return round(microtime(true) * 1000);
}
private static function initPlaceholderFormatters()
{
return [
'indicator' => function (self $indicator) {
return $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)];
},
'message' => function (self $indicator) {
return $indicator->message;
},
'elapsed' => function (self $indicator) {
return Helper::formatTime(time() - $indicator->startTime);
},
'memory' => function () {
return Helper::formatMemory(memory_get_usage(true));
},
];
}
private static function initFormats()
{
return [
'normal' => ' %indicator% %message%',
'normal_no_ansi' => ' %message%',
'verbose' => ' %indicator% %message% (%elapsed:6s%)',
'verbose_no_ansi' => ' %message% (%elapsed:6s%)',
'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
];
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Terminal;
class QuestionHelper extends Helper
{
private $inputStream;
private static $shell;
private static $stty = true;
public function ask(InputInterface $input, OutputInterface $output, Question $question)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
if (!$input->isInteractive()) {
$default = $question->getDefault();
if (null === $default) {
return $default;
}
if ($validator = $question->getValidator()) {
return \call_user_func($question->getValidator(), $default);
} elseif ($question instanceof ChoiceQuestion) {
$choices = $question->getChoices();
if (!$question->isMultiselect()) {
return isset($choices[$default]) ? $choices[$default] : $default;
}
$default = explode(',', $default);
foreach ($default as $k => $v) {
$v = trim($v);
$default[$k] = isset($choices[$v]) ? $choices[$v] : $v;
}
}
return $default;
}
if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
$this->inputStream = $stream;
}
if (!$question->getValidator()) {
return $this->doAsk($output, $question);
}
$interviewer = function () use ($output, $question) {
return $this->doAsk($output, $question);
};
return $this->validateAttempts($interviewer, $output, $question);
}
public function setInputStream($stream)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.2 and will be removed in 4.0. Use %s::setStream() instead.', __METHOD__, StreamableInputInterface::class), \E_USER_DEPRECATED);
if (!\is_resource($stream)) {
throw new InvalidArgumentException('Input stream must be a valid resource.');
}
$this->inputStream = $stream;
}
public function getInputStream()
{
if (0 === \func_num_args() || func_get_arg(0)) {
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.2 and will be removed in 4.0. Use %s::getStream() instead.', __METHOD__, StreamableInputInterface::class), \E_USER_DEPRECATED);
}
return $this->inputStream;
}
public function getName()
{
return 'question';
}
public static function disableStty()
{
self::$stty = false;
}
private function doAsk(OutputInterface $output, Question $question)
{
$this->writePrompt($output, $question);
$inputStream = $this->inputStream ?: \STDIN;
$autocomplete = $question->getAutocompleterValues();
if (\function_exists('sapi_windows_cp_set')) {
@sapi_windows_cp_set(1252);
}
if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
$ret = false;
if ($question->isHidden()) {
try {
$ret = trim($this->getHiddenResponse($output, $inputStream));
} catch (RuntimeException $e) {
if (!$question->isHiddenFallback()) {
throw $e;
}
}
}
if (false === $ret) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new RuntimeException('Aborted.');
}
$ret = trim($ret);
}
} else {
$ret = trim($this->autocomplete($output, $question, $inputStream, \is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
}
$ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
if ($normalizer = $question->getNormalizer()) {
return $normalizer($ret);
}
return $ret;
}
protected function writePrompt(OutputInterface $output, Question $question)
{
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$output->writeln(array_merge([
$question->getQuestion(),
], $this->formatChoiceQuestionChoices($question, 'info')));
$message = $question->getPrompt();
}
$output->write($message);
}
protected function formatChoiceQuestionChoices(ChoiceQuestion $question, $tag)
{
$messages = [];
$maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
foreach ($choices as $key => $value) {
$padding = str_repeat(' ', $maxWidth - self::strlen($key));
$messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
}
return $messages;
}
protected function writeError(OutputInterface $output, \Exception $error)
{
if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
$message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
} else {
$message = '<error>'.$error->getMessage().'</error>';
}
$output->writeln($message);
}
private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete)
{
$fullChoice = '';
$ret = '';
$i = 0;
$ofs = -1;
$matches = $autocomplete;
$numMatches = \count($matches);
$sttyMode = shell_exec('stty -g');
shell_exec('stty -icanon -echo');
$output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
while (!feof($inputStream)) {
$c = fread($inputStream, 1);
if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
shell_exec(sprintf('stty %s', $sttyMode));
throw new RuntimeException('Aborted.');
} elseif ("\177" === $c) {
if (0 === $numMatches && 0 !== $i) {
--$i;
$fullChoice = self::substr($fullChoice, 0, $i);
$output->write("\033[1D");
}
if (0 === $i) {
$ofs = -1;
$matches = $autocomplete;
$numMatches = \count($matches);
} else {
$numMatches = 0;
}
$ret = self::substr($ret, 0, $i);
} elseif ("\033" === $c) {
$c .= fread($inputStream, 2);
if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
if ('A' === $c[2] && -1 === $ofs) {
$ofs = 0;
}
if (0 === $numMatches) {
continue;
}
$ofs += ('A' === $c[2]) ? -1 : 1;
$ofs = ($numMatches + $ofs) % $numMatches;
}
} elseif (\ord($c) < 32) {
if ("\t" === $c || "\n" === $c) {
if ($numMatches > 0 && -1 !== $ofs) {
$ret = $matches[$ofs];
$remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
$output->write($remainingCharacters);
$fullChoice .= $remainingCharacters;
$i = self::strlen($fullChoice);
}
if ("\n" === $c) {
$output->write($c);
break;
}
$numMatches = 0;
}
continue;
} else {
if ("\x80" <= $c) {
$c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
}
$output->write($c);
$ret .= $c;
$fullChoice .= $c;
++$i;
$tempRet = $ret;
if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
$tempRet = $this->mostRecentlyEnteredValue($fullChoice);
}
$numMatches = 0;
$ofs = 0;
foreach ($autocomplete as $value) {
if (0 === strpos($value, $tempRet)) {
$matches[$numMatches++] = $value;
}
}
}
$output->write("\033[K");
if ($numMatches > 0 && -1 !== $ofs) {
$output->write("\0337");
$charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
$output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
$output->write("\0338");
}
}
shell_exec(sprintf('stty %s', $sttyMode));
return $fullChoice;
}
private function mostRecentlyEnteredValue($entered)
{
if (false === strpos($entered, ',')) {
return $entered;
}
$choices = explode(',', $entered);
if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
return $lastChoice;
}
return $entered;
}
private function getHiddenResponse(OutputInterface $output, $inputStream)
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
copy($exe, $tmpExe);
$exe = $tmpExe;
}
$value = rtrim(shell_exec($exe));
$output->writeln('');
if (isset($tmpExe)) {
unlink($tmpExe);
}
return $value;
}
if (self::$stty && Terminal::hasSttyAvailable()) {
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
$value = fgets($inputStream, 4096);
shell_exec(sprintf('stty %s', $sttyMode));
if (false === $value) {
throw new RuntimeException('Aborted.');
}
$value = trim($value);
$output->writeln('');
return $value;
}
if (false !== $shell = $this->getShell()) {
$readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
$value = rtrim(shell_exec($command));
$output->writeln('');
return $value;
}
throw new RuntimeException('Unable to hide the response.');
}
private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
{
$error = null;
$attempts = $question->getMaxAttempts();
while (null === $attempts || $attempts--) {
if (null !== $error) {
$this->writeError($output, $error);
}
try {
return \call_user_func($question->getValidator(), $interviewer());
} catch (RuntimeException $e) {
throw $e;
} catch (\Exception $error) {
}
}
throw $error;
}
private function getShell()
{
if (null !== self::$shell) {
return self::$shell;
}
self::$shell = false;
if (file_exists('/usr/bin/env')) {
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
self::$shell = $sh;
break;
}
}
}
return self::$shell;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal;
/**
@gmail
*/
final class ProgressBar
{
private $barWidth = 28;
private $barChar;
private $emptyBarChar = '-';
private $progressChar = '>';
private $format;
private $internalFormat;
private $redrawFreq = 1;
private $output;
private $step = 0;
private $max;
private $startTime;
private $stepWidth;
private $percent = 0.0;
private $formatLineCount;
private $messages = [];
private $overwrite = true;
private $terminal;
private $firstRun = true;
private static $formatters;
private static $formats;
public function __construct(OutputInterface $output, $max = 0)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$this->output = $output;
$this->setMaxSteps($max);
$this->terminal = new Terminal();
if (!$this->output->isDecorated()) {
$this->overwrite = false;
$this->setRedrawFrequency($max / 10);
}
$this->startTime = time();
}
public static function setPlaceholderFormatterDefinition($name, callable $callable)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
self::$formatters[$name] = $callable;
}
public static function getPlaceholderFormatterDefinition($name)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
}
public static function setFormatDefinition($name, $format)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
self::$formats[$name] = $format;
}
public static function getFormatDefinition($name)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
return isset(self::$formats[$name]) ? self::$formats[$name] : null;
}
public function setMessage($message, $name = 'message')
{
$this->messages[$name] = $message;
}
public function getMessage($name = 'message')
{
return $this->messages[$name];
}
public function getStartTime()
{
return $this->startTime;
}
public function getMaxSteps()
{
return $this->max;
}
public function getProgress()
{
return $this->step;
}
private function getStepWidth()
{
return $this->stepWidth;
}
public function getProgressPercent()
{
return $this->percent;
}
public function setBarWidth($size)
{
$this->barWidth = max(1, (int) $size);
}
public function getBarWidth()
{
return $this->barWidth;
}
public function setBarCharacter($char)
{
$this->barChar = $char;
}
public function getBarCharacter()
{
if (null === $this->barChar) {
return $this->max ? '=' : $this->emptyBarChar;
}
return $this->barChar;
}
public function setEmptyBarCharacter($char)
{
$this->emptyBarChar = $char;
}
public function getEmptyBarCharacter()
{
return $this->emptyBarChar;
}
public function setProgressCharacter($char)
{
$this->progressChar = $char;
}
public function getProgressCharacter()
{
return $this->progressChar;
}
public function setFormat($format)
{
$this->format = null;
$this->internalFormat = $format;
}
public function setRedrawFrequency($freq)
{
$this->redrawFreq = max((int) $freq, 1);
}
public function start($max = null)
{
$this->startTime = time();
$this->step = 0;
$this->percent = 0.0;
if (null !== $max) {
$this->setMaxSteps($max);
}
$this->display();
}
public function advance($step = 1)
{
$this->setProgress($this->step + $step);
}
public function setOverwrite($overwrite)
{
$this->overwrite = (bool) $overwrite;
}
public function setProgress($step)
{
$step = (int) $step;
if ($this->max && $step > $this->max) {
$this->max = $step;
} elseif ($step < 0) {
$step = 0;
}
$prevPeriod = (int) ($this->step / $this->redrawFreq);
$currPeriod = (int) ($step / $this->redrawFreq);
$this->step = $step;
$this->percent = $this->max ? (float) $this->step / $this->max : 0;
if ($prevPeriod !== $currPeriod || $this->max === $step) {
$this->display();
}
}
public function finish()
{
if (!$this->max) {
$this->max = $this->step;
}
if ($this->step === $this->max && !$this->overwrite) {
return;
}
$this->setProgress($this->max);
}
public function display()
{
if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
return;
}
if (null === $this->format) {
$this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
}
$this->overwrite($this->buildLine());
}
public function clear()
{
if (!$this->overwrite) {
return;
}
if (null === $this->format) {
$this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
}
$this->overwrite('');
}
private function setRealFormat($format)
{
if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
$this->format = self::getFormatDefinition($format.'_nomax');
} elseif (null !== self::getFormatDefinition($format)) {
$this->format = self::getFormatDefinition($format);
} else {
$this->format = $format;
}
$this->formatLineCount = substr_count($this->format, "\n");
}
private function setMaxSteps($max)
{
$this->max = max(0, (int) $max);
$this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
}
private function overwrite($message)
{
if ($this->overwrite) {
if (!$this->firstRun) {
if ($this->formatLineCount > 0) {
$message = str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount).$message;
}
$message = "\x0D\x1B[2K$message";
}
} elseif ($this->step > 0) {
$message = \PHP_EOL.$message;
}
$this->firstRun = false;
$this->output->write($message);
}
private function determineBestFormat()
{
switch ($this->output->getVerbosity()) {
case OutputInterface::VERBOSITY_VERBOSE:
return $this->max ? 'verbose' : 'verbose_nomax';
case OutputInterface::VERBOSITY_VERY_VERBOSE:
return $this->max ? 'very_verbose' : 'very_verbose_nomax';
case OutputInterface::VERBOSITY_DEBUG:
return $this->max ? 'debug' : 'debug_nomax';
default:
return $this->max ? 'normal' : 'normal_nomax';
}
}
private static function initPlaceholderFormatters()
{
return [
'bar' => function (self $bar, OutputInterface $output) {
$completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
$display = str_repeat($bar->getBarCharacter(), $completeBars);
if ($completeBars < $bar->getBarWidth()) {
$emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
$display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
}
return $display;
},
'elapsed' => function (self $bar) {
return Helper::formatTime(time() - $bar->getStartTime());
},
'remaining' => function (self $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
}
if (!$bar->getProgress()) {
$remaining = 0;
} else {
$remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
}
return Helper::formatTime($remaining);
},
'estimated' => function (self $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
}
if (!$bar->getProgress()) {
$estimated = 0;
} else {
$estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
}
return Helper::formatTime($estimated);
},
'memory' => function (self $bar) {
return Helper::formatMemory(memory_get_usage(true));
},
'current' => function (self $bar) {
return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT);
},
'max' => function (self $bar) {
return $bar->getMaxSteps();
},
'percent' => function (self $bar) {
return floor($bar->getProgressPercent() * 100);
},
];
}
private static function initFormats()
{
return [
'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
'normal_nomax' => ' %current% [%bar%]',
'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
];
}
private function buildLine()
{
$regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i";
$callback = function ($matches) {
if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
$text = \call_user_func($formatter, $this, $this->output);
} elseif (isset($this->messages[$matches[1]])) {
$text = $this->messages[$matches[1]];
} else {
return $matches[0];
}
if (isset($matches[2])) {
$text = sprintf('%'.$matches[2], $text);
}
return $text;
};
$line = preg_replace_callback($regex, $callback, $this->format);
$linesLength = array_map(function ($subLine) {
return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
}, explode("\n", $line));
$linesWidth = max($linesLength);
$terminalWidth = $this->terminal->getWidth();
if ($linesWidth <= $terminalWidth) {
return $line;
}
$this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
return preg_replace_callback($regex, $callback, $this->format);
}
}
<?php
namespace Symfony\Component\Console\Style;
interface StyleInterface
{
public function title($message);
public function section($message);
public function listing(array $elements);
public function text($message);
public function success($message);
public function error($message);
public function warning($message);
public function note($message);
public function caution($message);
public function table(array $headers, array $rows);
public function ask($question, $default = null, $validator = null);
public function askHidden($question, $validator = null);
public function confirm($question, $default = true);
public function choice($question, array $choices, $default = null);
public function newLine($count = 1);
public function progressStart($max = 0);
public function progressAdvance($step = 1);
public function progressFinish();
}
<?php
namespace Symfony\Component\Console\Style;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Terminal;
class SymfonyStyle extends OutputStyle
{
const MAX_LINE_LENGTH = 120;
private $input;
private $questionHelper;
private $progressBar;
private $lineLength;
private $bufferedOutput;
public function __construct(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->bufferedOutput = new BufferedOutput($output->getVerbosity(), false, clone $output->getFormatter());
$width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
$this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
parent::__construct($output);
}
public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = true)
{
$messages = \is_array($messages) ? array_values($messages) : [$messages];
$this->autoPrependBlock();
$this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
$this->newLine();
}
public function title($message)
{
$this->autoPrependBlock();
$this->writeln([
sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
]);
$this->newLine();
}
public function section($message)
{
$this->autoPrependBlock();
$this->writeln([
sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
]);
$this->newLine();
}
public function listing(array $elements)
{
$this->autoPrependText();
$elements = array_map(function ($element) {
return sprintf(' * %s', $element);
}, $elements);
$this->writeln($elements);
$this->newLine();
}
public function text($message)
{
$this->autoPrependText();
$messages = \is_array($message) ? array_values($message) : [$message];
foreach ($messages as $message) {
$this->writeln(sprintf(' %s', $message));
}
}
public function comment($message)
{
$this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
}
public function success($message)
{
$this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
}
public function error($message)
{
$this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
}
public function warning($message)
{
$this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
}
public function note($message)
{
$this->block($message, 'NOTE', 'fg=yellow', ' ! ');
}
public function caution($message)
{
$this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
}
public function table(array $headers, array $rows)
{
$style = clone Table::getStyleDefinition('symfony-style-guide');
$style->setCellHeaderFormat('<info>%s</info>');
$table = new Table($this);
$table->setHeaders($headers);
$table->setRows($rows);
$table->setStyle($style);
$table->render();
$this->newLine();
}
public function ask($question, $default = null, $validator = null)
{
$question = new Question($question, $default);
$question->setValidator($validator);
return $this->askQuestion($question);
}
public function askHidden($question, $validator = null)
{
$question = new Question($question);
$question->setHidden(true);
$question->setValidator($validator);
return $this->askQuestion($question);
}
public function confirm($question, $default = true)
{
return $this->askQuestion(new ConfirmationQuestion($question, $default));
}
public function choice($question, array $choices, $default = null)
{
if (null !== $default) {
$values = array_flip($choices);
$default = isset($values[$default]) ? $values[$default] : $default;
}
return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
}
public function progressStart($max = 0)
{
$this->progressBar = $this->createProgressBar($max);
$this->progressBar->start();
}
public function progressAdvance($step = 1)
{
$this->getProgressBar()->advance($step);
}
public function progressFinish()
{
$this->getProgressBar()->finish();
$this->newLine(2);
$this->progressBar = null;
}
public function createProgressBar($max = 0)
{
$progressBar = parent::createProgressBar($max);
if ('\\' !== \DIRECTORY_SEPARATOR || 'Hyper' === getenv('TERM_PROGRAM')) {
$progressBar->setEmptyBarCharacter('░');
$progressBar->setProgressCharacter('');
$progressBar->setBarCharacter('▓');
}
return $progressBar;
}
public function askQuestion(Question $question)
{
if ($this->input->isInteractive()) {
$this->autoPrependBlock();
}
if (!$this->questionHelper) {
$this->questionHelper = new SymfonyQuestionHelper();
}
$answer = $this->questionHelper->ask($this->input, $this, $question);
if ($this->input->isInteractive()) {
$this->newLine();
$this->bufferedOutput->write("\n");
}
return $answer;
}
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
parent::writeln($messages, $type);
$this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
}
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
parent::write($messages, $newline, $type);
$this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
}
public function newLine($count = 1)
{
parent::newLine($count);
$this->bufferedOutput->write(str_repeat("\n", $count));
}
public function getErrorStyle()
{
return new self($this->input, $this->getErrorOutput());
}
private function getProgressBar()
{
if (!$this->progressBar) {
throw new RuntimeException('The ProgressBar is not started.');
}
return $this->progressBar;
}
private function autoPrependBlock()
{
$chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
if (!isset($chars[0])) {
$this->newLine();
return;
}
$this->newLine(2 - substr_count($chars, "\n"));
}
private function autoPrependText()
{
$fetched = $this->bufferedOutput->fetch();
if ("\n" !== substr($fetched, -1)) {
$this->newLine();
}
}
private function reduceBuffer($messages)
{
return array_map(function ($value) {
return substr($value, -4);
}, array_merge([$this->bufferedOutput->fetch()], (array) $messages));
}
private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
{
$indentLength = 0;
$prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
$lines = [];
if (null !== $type) {
$type = sprintf('[%s] ', $type);
$indentLength = \strlen($type);
$lineIndentation = str_repeat(' ', $indentLength);
}
foreach ($messages as $key => $message) {
if ($escape) {
$message = OutputFormatter::escape($message);
}
$lines = array_merge($lines, explode(\PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, \PHP_EOL, true)));
if (\count($messages) > 1 && $key < \count($messages) - 1) {
$lines[] = '';
}
}
$firstLineIndex = 0;
if ($padding && $this->isDecorated()) {
$firstLineIndex = 1;
array_unshift($lines, '');
$lines[] = '';
}
foreach ($lines as $i => &$line) {
if (null !== $type) {
$line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
}
$line = $prefix.$line;
$line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
if ($style) {
$line = sprintf('<%s>%s</>', $style, $line);
}
}
return $lines;
}
}
<?php
namespace Symfony\Component\Console\Style;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
abstract class OutputStyle implements OutputInterface, StyleInterface
{
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function newLine($count = 1)
{
$this->output->write(str_repeat(\PHP_EOL, $count));
}
public function createProgressBar($max = 0)
{
return new ProgressBar($this->output, $max);
}
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
$this->output->write($messages, $newline, $type);
}
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
$this->output->writeln($messages, $type);
}
public function setVerbosity($level)
{
$this->output->setVerbosity($level);
}
public function getVerbosity()
{
return $this->output->getVerbosity();
}
public function setDecorated($decorated)
{
$this->output->setDecorated($decorated);
}
public function isDecorated()
{
return $this->output->isDecorated();
}
public function setFormatter(OutputFormatterInterface $formatter)
{
$this->output->setFormatter($formatter);
}
public function getFormatter()
{
return $this->output->getFormatter();
}
public function isQuiet()
{
return $this->output->isQuiet();
}
public function isVerbose()
{
return $this->output->isVerbose();
}
public function isVeryVerbose()
{
return $this->output->isVeryVerbose();
}
public function isDebug()
{
return $this->output->isDebug();
}
protected function getErrorOutput()
{
if (!$this->output instanceof ConsoleOutputInterface) {
return $this->output;
}
return $this->output->getErrorOutput();
}
}
<?php
namespace Symfony\Component\Console\Logger;
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleLogger extends AbstractLogger
{
const INFO = 'info';
const ERROR = 'error';
private $output;
private $verbosityLevelMap = [
LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL,
LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE,
LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE,
LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG,
];
private $formatLevelMap = [
LogLevel::EMERGENCY => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
LogLevel::ERROR => self::ERROR,
LogLevel::WARNING => self::INFO,
LogLevel::NOTICE => self::INFO,
LogLevel::INFO => self::INFO,
LogLevel::DEBUG => self::INFO,
];
private $errored = false;
public function __construct(OutputInterface $output, array $verbosityLevelMap = [], array $formatLevelMap = [])
{
$this->output = $output;
$this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
$this->formatLevelMap = $formatLevelMap + $this->formatLevelMap;
}
public function log($level, $message, array $context = [])
{
if (!isset($this->verbosityLevelMap[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
}
$output = $this->output;
if (self::ERROR === $this->formatLevelMap[$level]) {
if ($this->output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$this->errored = true;
}
if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) {
$output->writeln(sprintf('<%1$s>[%2$s] %3$s</%1$s>', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)), $this->verbosityLevelMap[$level]);
}
}
public function hasErrored()
{
return $this->errored;
}
private function interpolate($message, array $context)
{
if (false === strpos($message, '{')) {
return $message;
}
$replacements = [];
foreach ($context as $key => $val) {
if (null === $val || is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
$replacements["{{$key}}"] = $val;
} elseif ($val instanceof \DateTimeInterface) {
$replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
} elseif (\is_object($val)) {
$replacements["{{$key}}"] = '[object '.\get_class($val).']';
} else {
$replacements["{{$key}}"] = '['.\gettype($val).']';
}
}
return strtr($message, $replacements);
}
}
<?php
namespace Symfony\Component\Console;
final class ConsoleEvents
{
/**
@Event("Symfony\Component\Console\Event\ConsoleCommandEvent")
*/
const COMMAND = 'console.command';
/**
@Event("Symfony\Component\Console\Event\ConsoleTerminateEvent")
*/
const TERMINATE = 'console.terminate';
/**
@Event("Symfony\Component\Console\Event\ConsoleExceptionEvent")
*/
const EXCEPTION = 'console.exception';
/**
@Event("Symfony\Component\Console\Event\ConsoleErrorEvent")
*/
const ERROR = 'console.error';
}
<?php
namespace Symfony\Component\Console\CommandLoader;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Exception\CommandNotFoundException;
class ContainerCommandLoader implements CommandLoaderInterface
{
private $container;
private $commandMap;
public function __construct(ContainerInterface $container, array $commandMap)
{
$this->container = $container;
$this->commandMap = $commandMap;
}
public function get($name)
{
if (!$this->has($name)) {
throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
}
return $this->container->get($this->commandMap[$name]);
}
public function has($name)
{
return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
}
public function getNames()
{
return array_keys($this->commandMap);
}
}
<?php
namespace Symfony\Component\Console\CommandLoader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\CommandNotFoundException;
interface CommandLoaderInterface
{
public function get($name);
public function has($name);
public function getNames();
}
<?php
namespace Symfony\Component\Console\CommandLoader;
use Symfony\Component\Console\Exception\CommandNotFoundException;
class FactoryCommandLoader implements CommandLoaderInterface
{
private $factories;
public function __construct(array $factories)
{
$this->factories = $factories;
}
public function has($name)
{
return isset($this->factories[$name]);
}
public function get($name)
{
if (!isset($this->factories[$name])) {
throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
}
$factory = $this->factories[$name];
return $factory();
}
public function getNames()
{
return array_keys($this->factories);
}
}
<?php
namespace Symfony\Component\Console\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
@gmail
*/
class ErrorListener implements EventSubscriberInterface
{
private $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
public function onConsoleError(ConsoleErrorEvent $event)
{
if (null === $this->logger) {
return;
}
$error = $event->getError();
if (!$inputString = $this->getInputString($event)) {
$this->logger->error('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]);
return;
}
$this->logger->error('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]);
}
public function onConsoleTerminate(ConsoleTerminateEvent $event)
{
if (null === $this->logger) {
return;
}
$exitCode = $event->getExitCode();
if (0 === $exitCode) {
return;
}
if (!$inputString = $this->getInputString($event)) {
$this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);
return;
}
$this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]);
}
public static function getSubscribedEvents()
{
return [
ConsoleEvents::ERROR => ['onConsoleError', -128],
ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128],
];
}
private static function getInputString(ConsoleEvent $event)
{
$commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
$input = $event->getInput();
if (method_exists($input, '__toString')) {
if ($commandName) {
return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input);
}
return (string) $input;
}
return $commandName;
}
}
<?php
namespace Symfony\Component\Debug;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\Debug\Exception\ContextErrorException;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
use Symfony\Component\Debug\Exception\SilencedErrorContext;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
/**
* A generic ErrorHandler for the PHP engine.
*
* Provides five bit fields that control how errors are handled:
* - thrownErrors: errors thrown as \ErrorException
* - loggedErrors: logged errors, when not @-silenced
* - scopedErrors: errors thrown or logged with their local context
* - tracedErrors: errors logged with their stack trace
* - screamedErrors: never @-silenced errors
*
* Each error level can be logged by a dedicated PSR-3 logger object.
* Screaming only applies to logging.
* Throwing takes precedence over logging.
* Uncaught exceptions are logged as E_ERROR.
* E_DEPRECATED and E_USER_DEPRECATED levels never throw.
* E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
* Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
* As errors have a performance cost, repeated errors are all logged, so that the developer
* can see them and weight them as more important to fix than others of the same level.
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class ErrorHandler
{
private $levels = [
\E_DEPRECATED => 'Deprecated',
\E_USER_DEPRECATED => 'User Deprecated',
\E_NOTICE => 'Notice',
\E_USER_NOTICE => 'User Notice',
\E_STRICT => 'Runtime Notice',
\E_WARNING => 'Warning',
\E_USER_WARNING => 'User Warning',
\E_COMPILE_WARNING => 'Compile Warning',
\E_CORE_WARNING => 'Core Warning',
\E_USER_ERROR => 'User Error',
\E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
\E_COMPILE_ERROR => 'Compile Error',
\E_PARSE => 'Parse Error',
\E_ERROR => 'Error',
\E_CORE_ERROR => 'Core Error',
];
private $loggers = [
\E_DEPRECATED => [null, LogLevel::INFO],
\E_USER_DEPRECATED => [null, LogLevel::INFO],
\E_NOTICE => [null, LogLevel::WARNING],
\E_USER_NOTICE => [null, LogLevel::WARNING],
\E_STRICT => [null, LogLevel::WARNING],
\E_WARNING => [null, LogLevel::WARNING],
\E_USER_WARNING => [null, LogLevel::WARNING],
\E_COMPILE_WARNING => [null, LogLevel::WARNING],
\E_CORE_WARNING => [null, LogLevel::WARNING],
\E_USER_ERROR => [null, LogLevel::CRITICAL],
\E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL],
\E_COMPILE_ERROR => [null, LogLevel::CRITICAL],
\E_PARSE => [null, LogLevel::CRITICAL],
\E_ERROR => [null, LogLevel::CRITICAL],
\E_CORE_ERROR => [null, LogLevel::CRITICAL],
];
private $thrownErrors = 0x1FFF;
private $scopedErrors = 0x1FFF;
private $tracedErrors = 0x77FB;
private $screamedErrors = 0x55;
private $loggedErrors = 0;
private $traceReflector;
private $isRecursive = 0;
private $isRoot = false;
private $exceptionHandler;
private $bootstrappingLogger;
private static $reservedMemory;
private static $stackedErrors = [];
private static $stackedErrorLevels = [];
private static $toStringException = null;
private static $silencedErrorCache = [];
private static $silencedErrorCount = 0;
private static $exitCode = 0;
public static function register(self $handler = null, $replace = true)
{
if (null === self::$reservedMemory) {
self::$reservedMemory = str_repeat('x', 10240);
register_shutdown_function(__CLASS__.'::handleFatalError');
}
if ($handlerIsNew = null === $handler) {
$handler = new static();
}
if (null === $prev = set_error_handler([$handler, 'handleError'])) {
restore_error_handler();
set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors);
$handler->isRoot = true;
}
if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
$handler = $prev[0];
$replace = false;
}
if (!$replace && $prev) {
restore_error_handler();
$handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
} else {
$handlerIsRegistered = true;
}
if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) {
restore_exception_handler();
if (!$handlerIsRegistered) {
$handler = $prev[0];
} elseif ($handler !== $prev[0] && $replace) {
set_exception_handler([$handler, 'handleException']);
$p = $prev[0]->setExceptionHandler(null);
$handler->setExceptionHandler($p);
$prev[0]->setExceptionHandler($p);
}
} else {
$handler->setExceptionHandler($prev);
}
$handler->throwAt(\E_ALL & $handler->thrownErrors, true);
return $handler;
}
public function __construct(BufferingLogger $bootstrappingLogger = null)
{
if ($bootstrappingLogger) {
$this->bootstrappingLogger = $bootstrappingLogger;
$this->setDefaultLogger($bootstrappingLogger);
}
$this->traceReflector = new \ReflectionProperty('Exception', 'trace');
$this->traceReflector->setAccessible(true);
}
public function setDefaultLogger(LoggerInterface $logger, $levels = \E_ALL, $replace = false)
{
$loggers = [];
if (\is_array($levels)) {
foreach ($levels as $type => $logLevel) {
if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
$loggers[$type] = [$logger, $logLevel];
}
}
} else {
if (null === $levels) {
$levels = \E_ALL;
}
foreach ($this->loggers as $type => $log) {
if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
$log[0] = $logger;
$loggers[$type] = $log;
}
}
}
$this->setLoggers($loggers);
}
public function setLoggers(array $loggers)
{
$prevLogged = $this->loggedErrors;
$prev = $this->loggers;
$flush = [];
foreach ($loggers as $type => $log) {
if (!isset($prev[$type])) {
throw new \InvalidArgumentException('Unknown error type: '.$type);
}
if (!\is_array($log)) {
$log = [$log];
} elseif (!\array_key_exists(0, $log)) {
throw new \InvalidArgumentException('No logger provided.');
}
if (null === $log[0]) {
$this->loggedErrors &= ~$type;
} elseif ($log[0] instanceof LoggerInterface) {
$this->loggedErrors |= $type;
} else {
throw new \InvalidArgumentException('Invalid logger provided.');
}
$this->loggers[$type] = $log + $prev[$type];
if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
$flush[$type] = $type;
}
}
$this->reRegister($prevLogged | $this->thrownErrors);
if ($flush) {
foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
$type = $log[2]['exception'] instanceof \ErrorException ? $log[2]['exception']->getSeverity() : \E_ERROR;
if (!isset($flush[$type])) {
$this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
} elseif ($this->loggers[$type][0]) {
$this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
}
}
}
return $prev;
}
public function setExceptionHandler(callable $handler = null)
{
$prev = $this->exceptionHandler;
$this->exceptionHandler = $handler;
return $prev;
}
public function throwAt($levels, $replace = false)
{
$prev = $this->thrownErrors;
$this->thrownErrors = ($levels | \E_RECOVERABLE_ERROR | \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED;
if (!$replace) {
$this->thrownErrors |= $prev;
}
$this->reRegister($prev | $this->loggedErrors);
return $prev;
}
public function scopeAt($levels, $replace = false)
{
$prev = $this->scopedErrors;
$this->scopedErrors = (int) $levels;
if (!$replace) {
$this->scopedErrors |= $prev;
}
return $prev;
}
public function traceAt($levels, $replace = false)
{
$prev = $this->tracedErrors;
$this->tracedErrors = (int) $levels;
if (!$replace) {
$this->tracedErrors |= $prev;
}
return $prev;
}
/**
* Sets the error levels where the @-operator is ignored.
*
* @param int $levels A bit field of E_* constants for screamed errors
* @param bool $replace Replace or amend the previous value
*
* @return int The previous value
*/
public function screamAt($levels, $replace = false)
{
$prev = $this->screamedErrors;
$this->screamedErrors = (int) $levels;
if (!$replace) {
$this->screamedErrors |= $prev;
}
return $prev;
}
private function reRegister($prev)
{
if ($prev !== $this->thrownErrors | $this->loggedErrors) {
$handler = set_error_handler('var_dump');
$handler = \is_array($handler) ? $handler[0] : null;
restore_error_handler();
if ($handler === $this) {
restore_error_handler();
if ($this->isRoot) {
set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors);
} else {
set_error_handler([$this, 'handleError']);
}
}
}
}
public function handleError($type, $message, $file, $line)
{
if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) {
$type = \E_DEPRECATED;
}
$level = error_reporting();
$silenced = 0 === ($level & $type);
$level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED;
$log = $this->loggedErrors & $type;
$throw = $this->thrownErrors & $type & $level;
$type &= $level | $this->screamedErrors;
if (!$type || (!$log && !$throw)) {
return !$silenced && $type && $log;
}
$scope = $this->scopedErrors & $type;
if (4 < $numArgs = \func_num_args()) {
$context = func_get_arg(4) ?: [];
$backtrace = 5 < $numArgs ? func_get_arg(5) : null;
} else {
$context = [];
$backtrace = null;
}
if (isset($context['GLOBALS']) && $scope) {
$e = $context;
unset($e['GLOBALS'], $context);
$context = $e;
}
if (null !== $backtrace && $type & \E_ERROR) {
$this->handleFatalError(compact('type', 'message', 'file', 'line', 'backtrace'));
return true;
}
$logMessage = $this->levels[$type].': '.$message;
if (null !== self::$toStringException) {
$errorAsException = self::$toStringException;
self::$toStringException = null;
} elseif (!$throw && !($type & $level)) {
if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) {
$lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3), $type, $file, $line, false) : [];
$errorAsException = new SilencedErrorContext($type, $file, $line, $lightTrace);
} elseif (isset(self::$silencedErrorCache[$id][$message])) {
$lightTrace = null;
$errorAsException = self::$silencedErrorCache[$id][$message];
++$errorAsException->count;
} else {
$lightTrace = [];
$errorAsException = null;
}
if (100 < ++self::$silencedErrorCount) {
self::$silencedErrorCache = $lightTrace = [];
self::$silencedErrorCount = 1;
}
if ($errorAsException) {
self::$silencedErrorCache[$id][$message] = $errorAsException;
}
if (null === $lightTrace) {
return true;
}
} else {
if ($scope) {
$errorAsException = new ContextErrorException($logMessage, 0, $type, $file, $line, $context);
} else {
$errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
}
if ($throw || $this->tracedErrors & $type) {
$backtrace = $backtrace ?: $errorAsException->getTrace();
$lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
$this->traceReflector->setValue($errorAsException, $lightTrace);
} else {
$this->traceReflector->setValue($errorAsException, []);
}
}
if ($throw) {
if (\PHP_VERSION_ID < 70400 && \E_USER_ERROR & $type) {
for ($i = 1; isset($backtrace[$i]); ++$i) {
if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
&& '__toString' === $backtrace[$i]['function']
&& '->' === $backtrace[$i]['type']
&& !isset($backtrace[$i - 1]['class'])
&& ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
) {
foreach ($context as $e) {
if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
if (1 === $i) {
$errorAsException = $e;
break;
}
self::$toStringException = $e;
return true;
}
}
if (1 < $i) {
$this->handleException($errorAsException);
return false;
}
}
}
}
throw $errorAsException;
}
if ($this->isRecursive) {
$log = 0;
} elseif (self::$stackedErrorLevels) {
self::$stackedErrors[] = [
$this->loggers[$type][0],
($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG,
$logMessage,
$errorAsException ? ['exception' => $errorAsException] : [],
];
} else {
if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404) && !\defined('HHVM_VERSION')) {
$currentErrorHandler = set_error_handler('var_dump');
restore_error_handler();
}
try {
$this->isRecursive = true;
$level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
$this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []);
} finally {
$this->isRecursive = false;
if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404) && !\defined('HHVM_VERSION')) {
set_error_handler($currentErrorHandler);
}
}
}
return !$silenced && $type && $log;
}
public function handleException($exception, array $error = null)
{
if (null === $error) {
self::$exitCode = 255;
}
if (!$exception instanceof \Exception) {
$exception = new FatalThrowableError($exception);
}
$type = $exception instanceof FatalErrorException ? $exception->getSeverity() : \E_ERROR;
$handlerException = null;
if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
if ($exception instanceof FatalErrorException) {
if ($exception instanceof FatalThrowableError) {
$error = [
'type' => $type,
'message' => $message = $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
];
} else {
$message = 'Fatal '.$exception->getMessage();
}
} elseif ($exception instanceof \ErrorException) {
$message = 'Uncaught '.$exception->getMessage();
} else {
$message = 'Uncaught Exception: '.$exception->getMessage();
}
}
if ($this->loggedErrors & $type) {
try {
$this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
}
if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
foreach ($this->getFatalErrorHandlers() as $handler) {
if ($e = $handler->handleError($error, $exception)) {
$exception = $e;
break;
}
}
}
$exceptionHandler = $this->exceptionHandler;
$this->exceptionHandler = null;
try {
if (null !== $exceptionHandler) {
$exceptionHandler($exception);
return;
}
$handlerException = $handlerException ?: $exception;
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
if ($exception === $handlerException) {
self::$reservedMemory = null;
throw $exception;
}
$this->handleException($handlerException);
}
public static function handleFatalError(array $error = null)
{
if (null === self::$reservedMemory) {
return;
}
$handler = self::$reservedMemory = null;
$handlers = [];
$previousHandler = null;
$sameHandlerLimit = 10;
while (!\is_array($handler) || !$handler[0] instanceof self) {
$handler = set_exception_handler('var_dump');
restore_exception_handler();
if (!$handler) {
break;
}
restore_exception_handler();
if ($handler !== $previousHandler) {
array_unshift($handlers, $handler);
$previousHandler = $handler;
} elseif (0 === --$sameHandlerLimit) {
$handler = null;
break;
}
}
foreach ($handlers as $h) {
set_exception_handler($h);
}
if (!$handler) {
return;
}
if ($handler !== $h) {
$handler[0]->setExceptionHandler($h);
}
$handler = $handler[0];
$handlers = [];
if ($exit = null === $error) {
$error = error_get_last();
}
try {
while (self::$stackedErrorLevels) {
static::unstackErrors();
}
} catch (\Exception $exception) {
} catch (\Throwable $exception) {
}
if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) {
$handler->throwAt(0, true);
$trace = isset($error['backtrace']) ? $error['backtrace'] : null;
if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
$exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
} else {
$exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
}
}
try {
if (isset($exception)) {
self::$exitCode = 255;
$handler->handleException($exception, $error);
}
} catch (FatalErrorException $e) {
}
if ($exit && self::$exitCode) {
$exitCode = self::$exitCode;
register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
}
}
public static function stackErrors()
{
@trigger_error('Support for stacking errors is deprecated since Symfony 3.4 and will be removed in 4.0.', \E_USER_DEPRECATED);
self::$stackedErrorLevels[] = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
}
public static function unstackErrors()
{
@trigger_error('Support for unstacking errors is deprecated since Symfony 3.4 and will be removed in 4.0.', \E_USER_DEPRECATED);
$level = array_pop(self::$stackedErrorLevels);
if (null !== $level) {
$errorReportingLevel = error_reporting($level);
if ($errorReportingLevel !== ($level | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR)) {
error_reporting($errorReportingLevel);
}
}
if (empty(self::$stackedErrorLevels)) {
$errors = self::$stackedErrors;
self::$stackedErrors = [];
foreach ($errors as $error) {
$error[0]->log($error[1], $error[2], $error[3]);
}
}
}
protected function getFatalErrorHandlers()
{
return [
new UndefinedFunctionFatalErrorHandler(),
new UndefinedMethodFatalErrorHandler(),
new ClassNotFoundFatalErrorHandler(),
];
}
private function cleanTrace($backtrace, $type, $file, $line, $throw)
{
$lightTrace = $backtrace;
for ($i = 0; isset($backtrace[$i]); ++$i) {
if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
$lightTrace = \array_slice($lightTrace, 1 + $i);
break;
}
}
if (!($throw || $this->scopedErrors & $type)) {
for ($i = 0; isset($lightTrace[$i]); ++$i) {
unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
}
}
return $lightTrace;
}
}
<?php
namespace Symfony\Component\Debug;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
/**
@tchwork
*/
class ExceptionHandler
{
private $debug;
private $charset;
private $handler;
private $caughtBuffer;
private $caughtLength;
private $fileLinkFormat;
public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
{
$this->debug = $debug;
$this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
$this->fileLinkFormat = $fileLinkFormat;
}
public static function register($debug = true, $charset = null, $fileLinkFormat = null)
{
$handler = new static($debug, $charset, $fileLinkFormat);
$prev = set_exception_handler([$handler, 'handle']);
if (\is_array($prev) && $prev[0] instanceof ErrorHandler) {
restore_exception_handler();
$prev[0]->setExceptionHandler([$handler, 'handle']);
}
return $handler;
}
public function setHandler(callable $handler = null)
{
$old = $this->handler;
$this->handler = $handler;
return $old;
}
public function setFileLinkFormat($fileLinkFormat)
{
$old = $this->fileLinkFormat;
$this->fileLinkFormat = $fileLinkFormat;
return $old;
}
public function handle(\Exception $exception)
{
if (null === $this->handler || $exception instanceof OutOfMemoryException) {
$this->sendPhpResponse($exception);
return;
}
$caughtLength = $this->caughtLength = 0;
ob_start(function ($buffer) {
$this->caughtBuffer = $buffer;
return '';
});
$this->sendPhpResponse($exception);
while (null === $this->caughtBuffer && ob_end_flush()) {
}
if (isset($this->caughtBuffer[0])) {
ob_start(function ($buffer) {
if ($this->caughtLength) {
$cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
if (isset($cleanBuffer[0])) {
$buffer = $cleanBuffer;
}
}
return $buffer;
});
echo $this->caughtBuffer;
$caughtLength = ob_get_length();
}
$this->caughtBuffer = null;
try {
\call_user_func($this->handler, $exception);
$this->caughtLength = $caughtLength;
} catch (\Exception $e) {
if (!$caughtLength) {
throw $exception;
}
}
}
public function sendPhpResponse($exception)
{
if (!$exception instanceof FlattenException) {
$exception = FlattenException::create($exception);
}
if (!headers_sent()) {
header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
foreach ($exception->getHeaders() as $name => $value) {
header($name.': '.$value, false);
}
header('Content-Type: text/html; charset='.$this->charset);
}
echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
}
public function getHtml($exception)
{
if (!$exception instanceof FlattenException) {
$exception = FlattenException::create($exception);
}
return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
}
public function getContent(FlattenException $exception)
{
switch ($exception->getStatusCode()) {
case 404:
$title = 'Sorry, the page you are looking for could not be found.';
break;
default:
$title = 'Whoops, looks like something went wrong.';
}
if (!$this->debug) {
return <<<EOF
<div class="container">
<h1>$title</h1>
</div>
EOF;
}
$content = '';
try {
$count = \count($exception->getAllPrevious());
$total = $count + 1;
foreach ($exception->toArray() as $position => $e) {
$ind = $count - $position + 1;
$class = $this->formatClass($e['class']);
$message = nl2br($this->escapeHtml($e['message']));
$content .= sprintf(<<<'EOF'
<div class="trace trace-as-html">
<table class="trace-details">
<thead class="trace-head"><tr><th>
<h3 class="trace-class">
<span class="text-muted">(%d/%d)</span>
<span class="exception_title">%s</span>
</h3>
<p class="break-long-words trace-message">%s</p>
</th></tr></thead>
<tbody>
EOF
, $ind, $total, $class, $message);
foreach ($e['trace'] as $trace) {
$content .= '<tr><td>';
if ($trace['function']) {
$content .= sprintf('at <span class="trace-class">%s</span><span class="trace-type">%s</span><span class="trace-method">%s</span>(<span class="trace-arguments">%s</span>)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
}
if (isset($trace['file']) && isset($trace['line'])) {
$content .= $this->formatPath($trace['file'], $trace['line']);
}
$content .= "</td></tr>\n";
}
$content .= "</tbody>\n</table>\n</div>\n";
}
} catch (\Exception $e) {
if ($this->debug) {
$title = sprintf('Exception thrown when handling an exception (%s: %s)', \get_class($e), $this->escapeHtml($e->getMessage()));
} else {
$title = 'Whoops, looks like something went wrong.';
}
}
$symfonyGhostImageContents = $this->getSymfonyGhostAsSvg();
return <<<EOF
<div class="exception-summary">
<div class="container">
<div class="exception-message-wrapper">
<h1 class="break-long-words exception-message">$title</h1>
<div class="exception-illustration hidden-xs-down">$symfonyGhostImageContents</div>
</div>
</div>
</div>
<div class="container">
$content
</div>
EOF;
}
public function getStylesheet(FlattenException $exception)
{
if (!$this->debug) {
return <<<'EOF'
body { background-color: #fff; color: #222; font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; }
.container { margin: 30px; max-width: 600px; }
h1 { color: #dc3545; font-size: 24px; }
EOF;
}
return <<<'EOF'
body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }
a { cursor: pointer; text-decoration: none; }
a:hover { text-decoration: underline; }
abbr[title] { border-bottom: none; cursor: help; text-decoration: none; }
code, pre { font: 13px/1.5 Consolas, Monaco, Menlo, "Ubuntu Mono", "Liberation Mono", monospace; }
table, tr, th, td { background: #FFF; border-collapse: collapse; vertical-align: top; }
table { background: #FFF; border: 1px solid #E0E0E0; box-shadow: 0px 0px 1px rgba(128, 128, 128, .2); margin: 1em 0; width: 100%; }
table th, table td { border: solid #E0E0E0; border-width: 1px 0; padding: 8px 10px; }
table th { background-color: #E0E0E0; font-weight: bold; text-align: left; }
.hidden-xs-down { display: none; }
.block { display: block; }
.break-long-words { -ms-word-break: break-all; word-break: break-all; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; }
.text-muted { color: #999; }
.container { max-width: 1024px; margin: 0 auto; padding: 0 15px; }
.container::after { content: ""; display: table; clear: both; }
.exception-summary { background: #B0413E; border-bottom: 2px solid rgba(0, 0, 0, 0.1); border-top: 1px solid rgba(0, 0, 0, .3); flex: 0 0 auto; margin-bottom: 30px; }
.exception-message-wrapper { display: flex; align-items: center; min-height: 70px; }
.exception-message { flex-grow: 1; padding: 30px 0; }
.exception-message, .exception-message a { color: #FFF; font-size: 21px; font-weight: 400; margin: 0; }
.exception-message.long { font-size: 18px; }
.exception-message a { border-bottom: 1px solid rgba(255, 255, 255, 0.5); font-size: inherit; text-decoration: none; }
.exception-message a:hover { border-bottom-color: #ffffff; }
.exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; }
.trace + .trace { margin-top: 30px; }
.trace-head .trace-class { color: #222; font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; }
.trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; }
.trace-file-path, .trace-file-path a { color: #222; margin-top: 3px; font-size: 13px; }
.trace-class { color: #B0413E; }
.trace-type { padding: 0 2px; }
.trace-method { color: #B0413E; font-weight: bold; }
.trace-arguments { color: #777; font-weight: normal; padding-left: 2px; }
@media (min-width: 575px) {
.hidden-xs-down { display: initial; }
}
EOF;
}
private function decorate($content, $css)
{
return <<<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="{$this->charset}" />
<meta name="robots" content="noindex,nofollow" />
<style>$css</style>
</head>
<body>
$content
</body>
</html>
EOF;
}
private function formatClass($class)
{
$parts = explode('\\', $class);
return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
}
private function formatPath($path, $line)
{
$file = $this->escapeHtml(preg_match('#[^/\\\\]*+$#', $path, $file) ? $file[0] : $path);
$fmt = $this->fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
if (!$fmt) {
return sprintf('<span class="block trace-file-path">in <span title="%s%3$s"><strong>%s</strong>%s</span></span>', $this->escapeHtml($path), $file, 0 < $line ? ' line '.$line : '');
}
if (\is_string($fmt)) {
$i = strpos($f = $fmt, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f);
$fmt = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, \PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; isset($fmt[$i]); ++$i) {
if (0 === strpos($path, $k = $fmt[$i++])) {
$path = substr_replace($path, $fmt[$i], 0, \strlen($k));
break;
}
}
$link = strtr($fmt[0], ['%f' => $path, '%l' => $line]);
} else {
try {
$link = $fmt->format($path, $line);
} catch (\Exception $e) {
return sprintf('<span class="block trace-file-path">in <span title="%s%3$s"><strong>%s</strong>%s</span></span>', $this->escapeHtml($path), $file, 0 < $line ? ' line '.$line : '');
}
}
return sprintf('<span class="block trace-file-path">in <a href="%s" title="Go to source"><strong>%s</string>%s</a></span>', $this->escapeHtml($link), $file, 0 < $line ? ' line '.$line : '');
}
private function formatArgs(array $args)
{
$result = [];
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
} elseif ('array' === $item[0]) {
$formattedValue = sprintf('<em>array</em>(%s)', \is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
} elseif ('null' === $item[0]) {
$formattedValue = '<em>null</em>';
} elseif ('boolean' === $item[0]) {
$formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
} elseif ('resource' === $item[0]) {
$formattedValue = '<em>resource</em>';
} else {
$formattedValue = str_replace("\n", '', $this->escapeHtml(var_export($item[1], true)));
}
$result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $this->escapeHtml($key), $formattedValue);
}
return implode(', ', $result);
}
private function escapeHtml($str)
{
return htmlspecialchars($str, \ENT_COMPAT | \ENT_SUBSTITUTE, $this->charset);
}
private function getSymfonyGhostAsSvg()
{
return '<svg viewBox="0 0 136 81" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.4"><path d="M92.4 20.4a23.2 23.2 0 0 1 9 1.9 23.7 23.7 0 0 1 5.2 3 24.3 24.3 0 0 1 3.4 3.4 24.8 24.8 0 0 1 5 9.4c.5 1.7.8 3.4 1 5.2v14.5h.4l.5.2a7.4 7.4 0 0 0 2.5.2l.2-.2.6-.8.8-1.3-.2-.1a5.5 5.5 0 0 1-.8-.3 5.6 5.6 0 0 1-2.3-1.8 5.7 5.7 0 0 1-.9-1.6 6.5 6.5 0 0 1-.2-2.8 7.3 7.3 0 0 1 .5-2l.3-.3.8-.9.3-.3c.2-.2.5-.3.8-.3H120.7c.2 0 .3-.1.4 0h.4l.2.1.3.2.2-.4.3-.4.1-.1 1.2-1 .3-.2.4-.1.4-.1h.3l1.5.1.4.1.8.5.1.2 1 1.1v.2H129.4l.4-.2 1.4-.5h1.1c.3 0 .7.2 1 .4.2 0 .3.2.5.3l.2.2.5.3.4.6.1.3.4 1.4.1.4v.6a7.8 7.8 0 0 1-.1.6 9.9 9.9 0 0 1-.8 2.4 7.8 7.8 0 0 1-3 3.3 6.4 6.4 0 0 1-1 .5 6.1 6.1 0 0 1-.6.2l-.7.1h-.1a23.4 23.4 0 0 1-.2 1.7 14.3 14.3 0 0 1-.6 2.1l-.8 2a9.2 9.2 0 0 1-.4.6l-.7 1a9.1 9.1 0 0 1-2.3 2.2c-.9.5-2 .6-3 .7l-1.4.1h-.5l-.4.1a15.8 15.8 0 0 1-2.8-.1v4.2a9.7 9.7 0 0 1-.7 3.5 9.6 9.6 0 0 1-1.7 2.8 9.3 9.3 0 0 1-3 2.3 9 9 0 0 1-5.4.7 9 9 0 0 1-3-1 9.4 9.4 0 0 1-2.7-2.5 10 10 0 0 1-1 1.2 9.3 9.3 0 0 1-2 1.3 9 9 0 0 1-2.4 1 9 9 0 0 1-6.5-1.1A9.4 9.4 0 0 1 85 77V77a10.9 10.9 0 0 1-.6.6 9.3 9.3 0 0 1-2.7 2 9 9 0 0 1-6 .8 9 9 0 0 1-2.4-1 9.3 9.3 0 0 1-2.3-1.7 9.6 9.6 0 0 1-1.8-2.8 9.7 9.7 0 0 1-.8-3.7v-4a18.5 18.5 0 0 1-2.9.2l-1.2-.1c-1.9-.3-3.7-1-5.1-2.1A8.2 8.2 0 0 1 58 64a10.2 10.2 0 0 1-.9-1.2 15.3 15.3 0 0 1-.7-1.3 20.8 20.8 0 0 1-1.9-6.2v-.2a6.5 6.5 0 0 1-1-.3 6.1 6.1 0 0 1-.6-.3 6.6 6.6 0 0 1-.9-.5 8.2 8.2 0 0 1-2.7-3.8 10 10 0 0 1-.3-1 10.3 10.3 0 0 1-.3-1.9V47v-.4l.1-.4.6-1.4.1-.2a2 2 0 0 1 .8-.8l.3-.2.3-.2a3.2 3.2 0 0 1 1.8-.5h.4l.3.2 1.4.6.2.2.4.3.3.4.7-.7.2-.2.4-.2.6-.2h2.1l.4.2.4.2.3.2.8 1 .2-.1h.1v-.1H63l1.1.1h.3l.8.5.3.4.7 1 .2.3.1.5a11 11 0 0 1 .2 1.5c0 .8 0 1.6-.3 2.3a6 6 0 0 1-.5 1.2 5.5 5.5 0 0 1-3.3 2.5 12.3 12.3 0 0 0 1.4 3h.1l.2.1 1 .2h1.5l.5-.2H67.8l.5-.2h.1V44v-.4a26.7 26.7 0 0 1 .3-2.3 24.7 24.7 0 0 1 5.7-12.5 24.2 24.2 0 0 1 3.5-3.3 23.7 23.7 0 0 1 4.9-3 23.2 23.2 0 0 1 5.6-1.7 23.7 23.7 0 0 1 4-.3zm-.3 2a21.2 21.2 0 0 0-8 1.7 21.6 21.6 0 0 0-4.8 2.7 22.2 22.2 0 0 0-3.2 3 22.7 22.7 0 0 0-5 9.2 23.4 23.4 0 0 0-.7 4.9v15.7l-.5.1a34.3 34.3 0 0 1-1.5.3h-.2l-.4.1h-.4l-.9.2a10 10 0 0 1-1.9 0c-.5 0-1-.2-1.5-.4a1.8 1.8 0 0 1-.3-.2 2 2 0 0 1-.3-.3 5.2 5.2 0 0 1-.1-.2 9 9 0 0 1-.6-.9 13.8 13.8 0 0 1-1-2 14.3 14.3 0 0 1-.6-2 14 14 0 0 1-.1-.8v-.2h.3a12.8 12.8 0 0 0 1.4-.2 4.4 4.4 0 0 0 .3 0 3.6 3.6 0 0 0 1.1-.7 3.4 3.4 0 0 0 1.2-1.7l.2-1.2a5.1 5.1 0 0 0 0-.8 7.2 7.2 0 0 0-.1-.8l-.7-1-1.2-.2-1 .7-.1 1.3a5 5 0 0 1 .1.4v.6a1 1 0 0 1 0 .3c-.1.3-.4.4-.7.5l-1.2.4v-.7A9.9 9.9 0 0 1 60 49l.3-.6v-.2l.1-.1v-1.6l-1-1.2h-1.5l-1 1.1v.4a5.3 5.3 0 0 0-.2.6 5.5 5.5 0 0 0 0 .5c0 .7 0 1.4.3 2 0 .4.2.8.4 1.2L57 51a9.5 9.5 0 0 1-1.1-.5h-.2a2 2 0 0 1-.4-.3c-.4-.4-.5-1-.6-1.6a5.6 5.6 0 0 1 0-.5v-.5-.5l-.6-1.5-1.4-.6-.9.3s-.2 0-.3.2a2 2 0 0 1-.1 0l-.6 1.4v.7a8.5 8.5 0 0 0 .5 2c.4 1.1 1 2.1 2 2.8a4.7 4.7 0 0 0 2.1.9h1a22.8 22.8 0 0 0 .1 1 18.1 18.1 0 0 0 .8 3.8 18.2 18.2 0 0 0 1.6 3.7l1 1.3c1 1 2.3 1.6 3.7 2a11.7 11.7 0 0 0 4.8 0h.4l.5-.2.5-.1.6-.2v6.6a8 8 0 0 0 .1 1.3 7.5 7.5 0 0 0 2.4 4.3 7.2 7.2 0 0 0 2.3 1.3 7 7 0 0 0 7-1.1 7.5 7.5 0 0 0 2-2.6A7.7 7.7 0 0 0 85 72V71a8.2 8.2 0 0 0 .2 1.3c0 .7.3 1.4.6 2a7.5 7.5 0 0 0 1.7 2.3 7.3 7.3 0 0 0 2.2 1.4 7.1 7.1 0 0 0 4.6.2 7.2 7.2 0 0 0 2.4-1.2 7.5 7.5 0 0 0 2.1-2.7 7.8 7.8 0 0 0 .7-2.4V71a9.3 9.3 0 0 0 .1.6 7.6 7.6 0 0 0 .6 2.5 7.5 7.5 0 0 0 2.4 3 7.1 7.1 0 0 0 7 .8 7.3 7.3 0 0 0 2.3-1.5 7.5 7.5 0 0 0 1.6-2.3 7.6 7.6 0 0 0 .5-2l.1-1.1v-6.7l.4.1a12.2 12.2 0 0 0 2 .5 11.1 11.1 0 0 0 2.5 0h.8l1.2-.1a9.5 9.5 0 0 0 1.4-.2l.9-.3a3.5 3.5 0 0 0 .6-.4l1.2-1.4a12.2 12.2 0 0 0 .8-1.2c0-.3.2-.5.3-.7a15.9 15.9 0 0 0 .7-2l.3-1.6v-1.3l.2-.9V54.6a15.5 15.5 0 0 0 1.8 0 4.5 4.5 0 0 0 1.4-.5 5.7 5.7 0 0 0 2.5-3.2 7.6 7.6 0 0 0 .4-1.5v-.3l-.4-1.4a5.2 5.2 0 0 1-.2-.1l-.4-.4a3.8 3.8 0 0 0-.2 0 1.4 1.4 0 0 0-.5-.2l-1.4.4-.7 1.3v.7a5.7 5.7 0 0 1-.1.8l-.7 1.4a1.9 1.9 0 0 1-.5.3h-.3a9.6 9.6 0 0 1-.8.3 8.8 8.8 0 0 1-.6 0l.2-.4.2-.5.2-.3v-.4l.1-.2V50l.1-1 .1-.6v-.6a4.8 4.8 0 0 0 0-.8v-.2l-1-1.1-1.5-.2-1.1 1-.2 1.4v.1l.2.4.2.3v.4l.1 1.1v.3l.1.5v.8a9.6 9.6 0 0 1-.8-.3l-.2-.1h-.3l-.8-.1h-.2a1.6 1.6 0 0 1-.2-.2.9.9 0 0 1-.2-.2 1 1 0 0 1-.1-.5l.2-.9v-1.2l-.9-.8h-1.2l-.8.9v.3a4.8 4.8 0 0 0-.3 2l.3.9a3.5 3.5 0 0 0 1.2 1.6l1 .5.8.2 1.4.1h.4l.2.1a12.1 12.1 0 0 1-1 2.6 13.2 13.2 0 0 1-.8 1.5 9.5 9.5 0 0 1-1 1.2l-.2.3a1.7 1.7 0 0 1-.4.3 2.4 2.4 0 0 1-.7.2h-2.5a7.8 7.8 0 0 1-.6-.2l-.7-.2h-.2a14.8 14.8 0 0 1-.6-.2 23.4 23.4 0 0 1-.4-.1l-.4-.1-.3-.1V43.9a34.6 34.6 0 0 0 0-.6 23.6 23.6 0 0 0-.4-3 22.7 22.7 0 0 0-1.5-4.7 22.6 22.6 0 0 0-4.6-6.7 21.9 21.9 0 0 0-6.9-4.7 21.2 21.2 0 0 0-8.1-1.8H92zm9.1 33.7l.3.1a1 1 0 0 1 .6.8v.4a8.4 8.4 0 0 1 0 .5 8.8 8.8 0 0 1-1.6 4.2l-1 1.3A10 10 0 0 1 95 66c-1.3.3-2.7.4-4 .3a10.4 10.4 0 0 1-2.7-.8 10 10 0 0 1-3.6-2.5 9.3 9.3 0 0 1-.8-1 9 9 0 0 1-.7-1.2 8.6 8.6 0 0 1-.8-3.4V57a1 1 0 0 1 .3-.6 1 1 0 0 1 1.3-.2 1 1 0 0 1 .4.8v.4a6.5 6.5 0 0 0 .5 2.2 7 7 0 0 0 2.1 2.8l1 .6c2.6 1.6 6 1.6 8.5 0a8 8 0 0 0 1.1-.6 7.6 7.6 0 0 0 1.2-1.2 7 7 0 0 0 1-1.7 6.5 6.5 0 0 0 .4-2.5 1 1 0 0 1 .7-1h.4zM30.7 43.7c-15.5 1-28.5-6-30.1-16.4C-1.2 15.7 11.6 4 29 1.3 46.6-1.7 62.3 5.5 64 17.1c1.6 10.4-8.7 21-23.7 25a31.2 31.2 0 0 0 0 .9v.3a19 19 0 0 0 .1 1l.1.4.1.9a4.7 4.7 0 0 0 .5 1l.7 1a9.2 9.2 0 0 0 1.2 1l1.5.8.6.8-.7.6-1.1.3a11.2 11.2 0 0 1-2.6.4 8.6 8.6 0 0 1-3-.5 8.5 8.5 0 0 1-1-.4 11.2 11.2 0 0 1-1.8-1.2 13.3 13.3 0 0 1-1-1 18 18 0 0 1-.7-.6l-.4-.4a23.4 23.4 0 0 1-1.3-1.8l-.1-.1-.3-.5V45l-.3-.6v-.7zM83.1 36c3.6 0 6.5 3.2 6.5 7.1 0 4-3 7.2-6.5 7.2S76.7 47 76.7 43 79.6 36 83 36zm18 0c3.6 0 6.5 3.2 6.5 7.1 0 4-2.9 7.2-6.4 7.2S94.7 47 94.7 43s3-7.1 6.5-7.1zm-18 6.1c2 0 3.5 1.6 3.5 3.6S85 49.2 83 49.2s-3.4-1.6-3.4-3.6S81.2 42 83 42zm17.9 0c1.9 0 3.4 1.6 3.4 3.6s-1.5 3.6-3.4 3.6c-2 0-3.5-1.6-3.5-3.6S99.1 42 101 42zM17 28c-.3 1.6-1.8 5-5.2 5.8-2.5.6-4.1-.8-4.5-2.6-.4-1.9.7-3.5 2.1-4.5A3.5 3.5 0 0 1 8 24.6c-.4-2 .8-3.7 3.2-4.2 1.9-.5 3.1.2 3.4 1.5.3 1.1-.5 2.2-1.8 2.5-.9.3-1.6 0-1.7-.6a1.4 1.4 0 0 1 0-.7s.3.2 1 0c.7-.1 1-.7.9-1.2-.2-.6-1-.8-1.8-.6-1 .2-2 1-1.7 2.6.3 1 .9 1.6 1.5 1.8l.7-.2c1-.2 1.5 0 1.6.5 0 .4-.2 1-1.2 1.2a3.3 3.3 0 0 1-1.5 0c-.9.7-1.6 1.9-1.3 3.2.3 1.3 1.3 2.2 3 1.8 2.5-.7 3.8-3.7 4.2-5-.3-.5-.6-1-.7-1.6-.1-.5.1-1 .9-1.2.4 0 .7.2.8.8a2.8 2.8 0 0 1 0 1l.7 1c.6-2 1.4-4 1.7-4 .6-.2 1.5.6 1.5.6-.8.7-1.7 2.4-2.3 4.2.8.6 1.6 1 2.1 1 .5-.1.8-.6 1-1.2-.3-2.2 1-4.3 2.3-4.6.7-.2 1.3.2 1.4.8.1.5 0 1.3-.9 1.7-.2-1-.6-1.3-1-1.3-.4.1-.7 1.4-.4 2.8.2 1 .7 1.5 1.3 1.4.8-.2 1.3-1.2 1.7-2.1-.3-2.1.9-4.2 2.2-4.5.7-.2 1.2.1 1.4 1 .4 1.4-1 2.8-2.2 3.4.3.7.7 1 1.3.9 1-.3 1.6-1.5 2-2.5l-.5-3v-.3s1.6-.3 1.8.6v.1c.2-.6.7-1.2 1.3-1.4.8-.1 1.5.6 1.7 1.6.5 2.2-.5 4.4-1.8 4.7H33a31.9 31.9 0 0 0 1 5.2c-.4.1-1.8.4-2-.4l-.5-5.6c-.5 1-1.3 2.2-2.5 2.4-1 .3-1.6-.3-2-1.1-.5 1-1.3 2.1-2.4 2.4-.8.2-1.5-.1-2-1-.3.8-.9 1.5-1.5 1.7-.7.1-1.5-.3-2.4-1-.3.8-.4 1.6-.4 2.2 0 0-.7 0-.8-.4-.1-.5 0-1.5.3-2.7a10.3 10.3 0 0 1-.7-.8zm38.2-17.8l.2.9c.5 1.9.4 4.4.8 6.4 0 .6-.4 3-1.4 3.3-.2 0-.3 0-.4-.4-.1-.7 0-1.6-.3-2.6-.2-1.1-.8-1.6-1.5-1.5-.8.2-1.3 1-1.6 2l-.1-.5c-.2-1-1.8-.6-1.8-.6a6.2 6.2 0 0 1 .4 1.3l.2 1c-.2.5-.6 1-1.2 1l-.2.1a7 7 0 0 0-.1-.8c-.3-1.1-1-2-1.6-1.8a.7.7 0 0 0-.4.3c-1.3.3-2.4 2-2.1 3.9-.2.9-.6 1.7-1 1.9-.5 0-.8-.5-1.1-1.8l-.1-1.2a4 4 0 0 0 0-1.7c0-.4-.4-.7-.8-.6-.7.2-.9 1.7-.5 3.8-.2 1-.6 2-1.3 2-.4.2-.8-.2-1-1l-.2-3c1.2-.5 2-1 1.8-1.7-.1-.5-.8-.7-.8-.7s0 .7-1 1.2l-.2-1.4c-.1-.6-.4-1-1.7-.6l.4 1 .2 1.5h-1v.8c0 .3.4.3 1 .2 0 1.3 0 2.7.2 3.6.3 1.4 1.2 2 2 1.7 1-.2 1.6-1.3 2-2.3.3 1.2 1 2 1.9 1.7.7-.2 1.2-1.1 1.6-2.2.4.8 1.1 1.1 2 1 1.2-.4 1.7-1.6 1.8-2.8h.2c.6-.2 1-.6 1.3-1 0 .8 0 1.5.2 2.1.1.5.3.7.6.6.5-.1 1-.9 1-.9a4 4 0 0 1-.3-1c-.3-1.3.3-3.6 1-3.7.2 0 .3.2.5.7v.8l.2 1.5v.7c.2.7.7 1.3 1.5 1 1.3-.2 2-2.6 2.1-3.9.3.2.6.2 1 .1-.6-2.2 0-6.1-.3-7.9-.1-.4-1-.5-1.7-.5h-.4zm-21.5 12c.4 0 .7.3 1 1.1.2 1.3-.3 2.6-.9 2.8-.2 0-.7 0-1-1.2v-.4c0-1.3.4-2 1-2.2zm-5.2 1c.3 0 .6.2.6.5.2.6-.3 1.3-1.2 2-.3-1.4.1-2.3.6-2.5zm18-.4c-.5.2-1-.4-1.2-1.2-.2-1 0-2.1.7-2.5v.5c.2.7.6 1.5 1.3 1.9 0 .7-.2 1.2-.7 1.3zm10-1.6c0 .5.4.7 1 .6.8-.2 1-1 .8-1.6 0-.5-.4-1-1-.8-.5.1-1 .9-.8 1.8zm-14.3-5.5c0-.4-.5-.7-1-.5-.8.2-1 1-.9 1.5.2.6.5 1 1 .8.5 0 1.1-1 1-1.8z" fill="#fff" fill-opacity=".6"/></svg>';
}
}
<?php
namespace Symfony\Component\Debug;
/**
@notk
@tchwork
*/
class DebugClassLoader
{
private $classLoader;
private $isFinder;
private $loaded = [];
private static $caseCheck;
private static $checkedClasses = [];
private static $final = [];
private static $finalMethods = [];
private static $deprecated = [];
private static $internal = [];
private static $internalMethods = [];
private static $php7Reserved = ['int' => 1, 'float' => 1, 'bool' => 1, 'string' => 1, 'true' => 1, 'false' => 1, 'null' => 1];
private static $darwinCache = ['/' => ['/', []]];
public function __construct(callable $classLoader)
{
$this->classLoader = $classLoader;
$this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
if (!isset(self::$caseCheck)) {
$file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
$i = strrpos($file, \DIRECTORY_SEPARATOR);
$dir = substr($file, 0, 1 + $i);
$file = substr($file, 1 + $i);
$test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
$test = realpath($dir.$test);
if (false === $test || false === $i) {
self::$caseCheck = 0;
} elseif (substr($test, -\strlen($file)) === $file) {
self::$caseCheck = 1;
} elseif (false !== stripos(\PHP_OS, 'darwin')) {
self::$caseCheck = 2;
} else {
self::$caseCheck = 0;
}
}
}
public function getClassLoader()
{
return $this->classLoader;
}
public static function enable()
{
class_exists('Symfony\Component\Debug\ErrorHandler');
class_exists('Psr\Log\LogLevel');
if (!\is_array($functions = spl_autoload_functions())) {
return;
}
foreach ($functions as $function) {
spl_autoload_unregister($function);
}
foreach ($functions as $function) {
if (!\is_array($function) || !$function[0] instanceof self) {
$function = [new static($function), 'loadClass'];
}
spl_autoload_register($function);
}
}
public static function disable()
{
if (!\is_array($functions = spl_autoload_functions())) {
return;
}
foreach ($functions as $function) {
spl_autoload_unregister($function);
}
foreach ($functions as $function) {
if (\is_array($function) && $function[0] instanceof self) {
$function = $function[0]->getClassLoader();
}
spl_autoload_register($function);
}
}
public function findFile($class)
{
return $this->isFinder ? $this->classLoader[0]->findFile($class) ?: null : null;
}
public function loadClass($class)
{
$e = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
try {
if ($this->isFinder && !isset($this->loaded[$class])) {
$this->loaded[$class] = true;
if (!$file = $this->classLoader[0]->findFile($class) ?: false) {
} elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
include $file;
return;
} elseif (false === include $file) {
return;
}
} else {
\call_user_func($this->classLoader, $class);
$file = false;
}
} finally {
error_reporting($e);
}
$this->checkClass($class, $file);
}
private function checkClass($class, $file = null)
{
$exists = null === $file || class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
if (null !== $file && $class && '\\' === $class[0]) {
$class = substr($class, 1);
}
if ($exists) {
if (isset(self::$checkedClasses[$class])) {
return;
}
self::$checkedClasses[$class] = true;
$refl = new \ReflectionClass($class);
if (null === $file && $refl->isInternal()) {
return;
}
$name = $refl->getName();
if ($name !== $class && 0 === strcasecmp($name, $class)) {
throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
}
$deprecations = $this->checkAnnotations($refl, $name);
if (isset(self::$php7Reserved[strtolower($refl->getShortName())])) {
$deprecations[] = sprintf('The "%s" class uses the reserved name "%s", it will break on PHP 7 and higher', $name, $refl->getShortName());
}
foreach ($deprecations as $message) {
@trigger_error($message, \E_USER_DEPRECATED);
}
}
if (!$file) {
return;
}
if (!$exists) {
if (false !== strpos($class, '/')) {
throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
}
throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
}
if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
}
}
public function checkAnnotations(\ReflectionClass $refl, $class)
{
$deprecations = [];
if (2 > $len = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) {
$len = 0;
$ns = '';
} else {
$ns = str_replace('_', '\\', substr($class, 0, $len));
}
if (false !== $doc = $refl->getDocComment()) {
foreach (['final', 'deprecated', 'internal'] as $annotation) {
if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
}
}
}
$parent = get_parent_class($class);
$parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
if ($parent) {
$parentAndOwnInterfaces[$parent] = $parent;
if (!isset(self::$checkedClasses[$parent])) {
$this->checkClass($parent);
}
if (isset(self::$final[$parent])) {
$deprecations[] = sprintf('The "%s" class is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $class);
}
}
foreach ($parentAndOwnInterfaces + class_uses($class, false) as $use) {
if (!isset(self::$checkedClasses[$use])) {
$this->checkClass($use);
}
if (isset(self::$deprecated[$use]) && strncmp($ns, str_replace('_', '\\', $use), $len) && !isset(self::$deprecated[$class])) {
$type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
$verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
$deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.', $class, $type, $verb, $use, self::$deprecated[$use]);
}
if (isset(self::$internal[$use]) && strncmp($ns, str_replace('_', '\\', $use), $len)) {
$deprecations[] = sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $class);
}
}
if (trait_exists($class)) {
return $deprecations;
}
self::$finalMethods[$class] = [];
self::$internalMethods[$class] = [];
foreach ($parentAndOwnInterfaces as $use) {
foreach (['finalMethods', 'internalMethods'] as $property) {
if (isset(self::${$property}[$use])) {
self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
}
}
}
foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
if ($method->class !== $class) {
continue;
}
if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
$deprecations[] = sprintf('The "%s::%s()" method is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $class);
}
if (isset(self::$internalMethods[$class][$method->name])) {
list($declaringClass, $message) = self::$internalMethods[$class][$method->name];
if (strncmp($ns, $declaringClass, $len)) {
$deprecations[] = sprintf('The "%s::%s()" method is considered internal%s. It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $class);
}
}
if (false === $doc = $method->getDocComment()) {
continue;
}
foreach (['final', 'internal'] as $annotation) {
if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
$message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message];
}
}
}
return $deprecations;
}
public function checkCase(\ReflectionClass $refl, $file, $class)
{
$real = explode('\\', $class.strrchr($file, '.'));
$tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
$i = \count($tail) - 1;
$j = \count($real) - 1;
while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
--$i;
--$j;
}
array_splice($tail, 0, $i + 1);
if (!$tail) {
return null;
}
$tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
$tailLen = \strlen($tail);
$real = $refl->getFileName();
if (2 === self::$caseCheck) {
$real = $this->darwinRealpath($real);
}
if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
&& 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
) {
return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)];
}
return null;
}
private function darwinRealpath($real)
{
$i = 1 + strrpos($real, '/');
$file = substr($real, $i);
$real = substr($real, 0, $i);
if (isset(self::$darwinCache[$real])) {
$kDir = $real;
} else {
$kDir = strtolower($real);
if (isset(self::$darwinCache[$kDir])) {
$real = self::$darwinCache[$kDir][0];
} else {
$dir = getcwd();
chdir($real);
$real = getcwd().'/';
chdir($dir);
$dir = $real;
$k = $kDir;
$i = \strlen($dir) - 1;
while (!isset(self::$darwinCache[$k])) {
self::$darwinCache[$k] = [$dir, []];
self::$darwinCache[$dir] = &self::$darwinCache[$k];
while ('/' !== $dir[--$i]) {
}
$k = substr($k, 0, ++$i);
$dir = substr($dir, 0, $i--);
}
}
}
$dirFiles = self::$darwinCache[$kDir][1];
if (!isset($dirFiles[$file]) && ') : eval()\'d code' === substr($file, -17)) {
$file = substr($file, 0, strrpos($file, '(', -17));
}
if (isset($dirFiles[$file])) {
return $real.$dirFiles[$file];
}
$kFile = strtolower($file);
if (!isset($dirFiles[$kFile])) {
foreach (scandir($real, 2) as $f) {
if ('.' !== $f[0]) {
$dirFiles[$f] = $f;
if ($f === $file) {
$kFile = $k = $file;
} elseif ($f !== $k = strtolower($f)) {
$dirFiles[$k] = $f;
}
}
}
self::$darwinCache[$kDir][1] = $dirFiles;
}
return $real.$dirFiles[$kFile];
}
private function getOwnInterfaces($class, $parent)
{
$ownInterfaces = class_implements($class, false);
if ($parent) {
foreach (class_implements($parent, false) as $interface) {
unset($ownInterfaces[$interface]);
}
}
foreach ($ownInterfaces as $interface) {
foreach (class_implements($interface) as $interface) {
unset($ownInterfaces[$interface]);
}
}
return $ownInterfaces;
}
}
<?php
namespace Symfony\Component\Debug\FatalErrorHandler;
use Composer\Autoload\ClassLoader as ComposerClassLoader;
use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
use Symfony\Component\Debug\DebugClassLoader;
use Symfony\Component\Debug\Exception\ClassNotFoundException;
use Symfony\Component\Debug\Exception\FatalErrorException;
class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
{
public function handleError(array $error, FatalErrorException $exception)
{
if (!preg_match('/^(Class|Interface|Trait) [\'"]([^\'"]+)[\'"] not found$/', $error['message'], $matches)) {
return null;
}
$typeName = strtolower($matches[1]);
$fullyQualifiedClassName = $matches[2];
if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
$className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
$namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
$message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
$tail = ' for another namespace?';
} else {
$className = $fullyQualifiedClassName;
$message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
$tail = '?';
}
if ($candidates = $this->getClassCandidates($className)) {
$tail = array_pop($candidates).'"?';
if ($candidates) {
$tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
} else {
$tail = ' for "'.$tail;
}
}
$message .= "\nDid you forget a \"use\" statement".$tail;
return new ClassNotFoundException($message, $exception);
}
private function getClassCandidates($class)
{
if (!\is_array($functions = spl_autoload_functions())) {
return [];
}
$classes = [];
foreach ($functions as $function) {
if (!\is_array($function)) {
continue;
}
if ($function[0] instanceof DebugClassLoader) {
$function = $function[0]->getClassLoader();
if (!\is_array($function)) {
continue;
}
}
if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
foreach ($function[0]->getPrefixes() as $prefix => $paths) {
foreach ($paths as $path) {
$classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
}
}
}
if ($function[0] instanceof ComposerClassLoader) {
foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
foreach ($paths as $path) {
$classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
}
}
}
}
return array_unique($classes);
}
private function findClassInPath($path, $class, $prefix)
{
if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
return [];
}
$classes = [];
$filename = $class.'.php';
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
$classes[] = $class;
}
}
return $classes;
}
private function convertFileToClass($path, $file, $prefix)
{
$candidates = [
$namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
$prefix.$namespacedClass,
$prefix.'\\'.$namespacedClass,
str_replace('\\', '_', $namespacedClass),
str_replace('\\', '_', $prefix.$namespacedClass),
str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
];
if ($prefix) {
$candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
}
foreach ($candidates as $candidate) {
if ($this->classExists($candidate)) {
return $candidate;
}
}
try {
require_once $file;
} catch (\Throwable $e) {
return null;
}
foreach ($candidates as $candidate) {
if ($this->classExists($candidate)) {
return $candidate;
}
}
return null;
}
private function classExists($class)
{
return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
}
}
<?php
namespace Symfony\Component\Debug\FatalErrorHandler;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\UndefinedMethodException;
class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
{
public function handleError(array $error, FatalErrorException $exception)
{
preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $error['message'], $matches);
if (!$matches) {
return null;
}
$className = $matches[1];
$methodName = $matches[2];
$message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className);
if (!class_exists($className) || null === $methods = get_class_methods($className)) {
return new UndefinedMethodException($message, $exception);
}
$candidates = [];
foreach ($methods as $definedMethodName) {
$lev = levenshtein($methodName, $definedMethodName);
if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
$candidates[] = $definedMethodName;
}
}
if ($candidates) {
sort($candidates);
$last = array_pop($candidates).'"?';
if ($candidates) {
$candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
} else {
$candidates = '"'.$last;
}
$message .= "\nDid you mean to call ".$candidates;
}
return new UndefinedMethodException($message, $exception);
}
}
<?php
namespace Symfony\Component\Debug\FatalErrorHandler;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\UndefinedFunctionException;
class UndefinedFunctionFatalErrorHandler implements FatalErrorHandlerInterface
{
public function handleError(array $error, FatalErrorException $exception)
{
$messageLen = \strlen($error['message']);
$notFoundSuffix = '()';
$notFoundSuffixLen = \strlen($notFoundSuffix);
if ($notFoundSuffixLen > $messageLen) {
return null;
}
if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) {
return null;
}
$prefix = 'Call to undefined function ';
$prefixLen = \strlen($prefix);
if (0 !== strpos($error['message'], $prefix)) {
return null;
}
$fullyQualifiedFunctionName = substr($error['message'], $prefixLen, -$notFoundSuffixLen);
if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedFunctionName, '\\')) {
$functionName = substr($fullyQualifiedFunctionName, $namespaceSeparatorIndex + 1);
$namespacePrefix = substr($fullyQualifiedFunctionName, 0, $namespaceSeparatorIndex);
$message = sprintf('Attempted to call function "%s" from namespace "%s".', $functionName, $namespacePrefix);
} else {
$functionName = $fullyQualifiedFunctionName;
$message = sprintf('Attempted to call function "%s" from the global namespace.', $functionName);
}
$candidates = [];
foreach (get_defined_functions() as $type => $definedFunctionNames) {
foreach ($definedFunctionNames as $definedFunctionName) {
if (false !== $namespaceSeparatorIndex = strrpos($definedFunctionName, '\\')) {
$definedFunctionNameBasename = substr($definedFunctionName, $namespaceSeparatorIndex + 1);
} else {
$definedFunctionNameBasename = $definedFunctionName;
}
if ($definedFunctionNameBasename === $functionName) {
$candidates[] = '\\'.$definedFunctionName;
}
}
}
if ($candidates) {
sort($candidates);
$last = array_pop($candidates).'"?';
if ($candidates) {
$candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
} else {
$candidates = '"'.$last;
}
$message .= "\nDid you mean to call ".$candidates;
}
return new UndefinedFunctionException($message, $exception);
}
}
<?php
namespace Symfony\Component\Debug\FatalErrorHandler;
use Symfony\Component\Debug\Exception\FatalErrorException;
interface FatalErrorHandlerInterface
{
public function handleError(array $error, FatalErrorException $exception);
}
<?php
namespace Symfony\Component\Debug\Exception;
class FatalErrorException extends \ErrorException
{
public function __construct($message, $code, $severity, $filename, $lineno, $traceOffset = null, $traceArgs = true, array $trace = null, $previous = null)
{
parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
if (null !== $trace) {
if (!$traceArgs) {
foreach ($trace as &$frame) {
unset($frame['args'], $frame['this'], $frame);
}
}
$this->setTrace($trace);
} elseif (null !== $traceOffset) {
if (\function_exists('xdebug_get_function_stack')) {
$trace = xdebug_get_function_stack();
if (0 < $traceOffset) {
array_splice($trace, -$traceOffset);
}
foreach ($trace as &$frame) {
if (!isset($frame['type'])) {
if (isset($frame['class'])) {
$frame['type'] = '::';
}
} elseif ('dynamic' === $frame['type']) {
$frame['type'] = '->';
} elseif ('static' === $frame['type']) {
$frame['type'] = '::';
}
if (!$traceArgs) {
unset($frame['params'], $frame['args']);
} elseif (isset($frame['params']) && !isset($frame['args'])) {
$frame['args'] = $frame['params'];
unset($frame['params']);
}
}
unset($frame);
$trace = array_reverse($trace);
} elseif (\function_exists('symfony_debug_backtrace')) {
$trace = symfony_debug_backtrace();
if (0 < $traceOffset) {
array_splice($trace, 0, $traceOffset);
}
} else {
$trace = [];
}
$this->setTrace($trace);
}
}
protected function setTrace($trace)
{
$traceReflector = new \ReflectionProperty('Exception', 'trace');
$traceReflector->setAccessible(true);
$traceReflector->setValue($this, $trace);
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class UndefinedFunctionException extends FatalErrorException
{
public function __construct($message, \ErrorException $previous)
{
parent::__construct(
$message,
$previous->getCode(),
$previous->getSeverity(),
$previous->getFile(),
$previous->getLine(),
null,
true,
null,
$previous->getPrevious()
);
$this->setTrace($previous->getTrace());
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class ContextErrorException extends \ErrorException
{
private $context = [];
public function __construct($message, $code, $severity, $filename, $lineno, $context = [])
{
parent::__construct($message, $code, $severity, $filename, $lineno);
$this->context = $context;
}
public function getContext()
{
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.3 and will be removed in 4.0.', __CLASS__), \E_USER_DEPRECATED);
return $this->context;
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class OutOfMemoryException extends FatalErrorException
{
}
<?php
namespace Symfony\Component\Debug\Exception;
class SilencedErrorContext implements \JsonSerializable
{
public $count = 1;
private $severity;
private $file;
private $line;
private $trace;
public function __construct($severity, $file, $line, array $trace = [], $count = 1)
{
$this->severity = $severity;
$this->file = $file;
$this->line = $line;
$this->trace = $trace;
$this->count = $count;
}
public function getSeverity()
{
return $this->severity;
}
public function getFile()
{
return $this->file;
}
public function getLine()
{
return $this->line;
}
public function getTrace()
{
return $this->trace;
}
public function jsonSerialize()
{
return [
'severity' => $this->severity,
'file' => $this->file,
'line' => $this->line,
'trace' => $this->trace,
'count' => $this->count,
];
}
}
<?php
namespace Symfony\Component\Debug\Exception;
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class FlattenException
{
private $message;
private $code;
private $previous;
private $trace;
private $class;
private $statusCode;
private $headers;
private $file;
private $line;
public static function create(\Exception $exception, $statusCode = null, array $headers = [])
{
$e = new static();
$e->setMessage($exception->getMessage());
$e->setCode($exception->getCode());
if ($exception instanceof HttpExceptionInterface) {
$statusCode = $exception->getStatusCode();
$headers = array_merge($headers, $exception->getHeaders());
} elseif ($exception instanceof RequestExceptionInterface) {
$statusCode = 400;
}
if (null === $statusCode) {
$statusCode = 500;
}
$e->setStatusCode($statusCode);
$e->setHeaders($headers);
$e->setTraceFromException($exception);
$e->setClass(\get_class($exception));
$e->setFile($exception->getFile());
$e->setLine($exception->getLine());
$previous = $exception->getPrevious();
if ($previous instanceof \Exception) {
$e->setPrevious(static::create($previous));
} elseif ($previous instanceof \Throwable) {
$e->setPrevious(static::create(new FatalThrowableError($previous)));
}
return $e;
}
public function toArray()
{
$exceptions = [];
foreach (array_merge([$this], $this->getAllPrevious()) as $exception) {
$exceptions[] = [
'message' => $exception->getMessage(),
'class' => $exception->getClass(),
'trace' => $exception->getTrace(),
];
}
return $exceptions;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setStatusCode($code)
{
$this->statusCode = $code;
}
public function getHeaders()
{
return $this->headers;
}
public function setHeaders(array $headers)
{
$this->headers = $headers;
}
public function getClass()
{
return $this->class;
}
public function setClass($class)
{
$this->class = $class;
}
public function getFile()
{
return $this->file;
}
public function setFile($file)
{
$this->file = $file;
}
public function getLine()
{
return $this->line;
}
public function setLine($line)
{
$this->line = $line;
}
public function getMessage()
{
return $this->message;
}
public function setMessage($message)
{
$this->message = $message;
}
public function getCode()
{
return $this->code;
}
public function setCode($code)
{
$this->code = $code;
}
public function getPrevious()
{
return $this->previous;
}
public function setPrevious(self $previous)
{
$this->previous = $previous;
}
public function getAllPrevious()
{
$exceptions = [];
$e = $this;
while ($e = $e->getPrevious()) {
$exceptions[] = $e;
}
return $exceptions;
}
public function getTrace()
{
return $this->trace;
}
public function setTraceFromException(\Exception $exception)
{
$this->setTrace($exception->getTrace(), $exception->getFile(), $exception->getLine());
}
public function setTrace($trace, $file, $line)
{
$this->trace = [];
$this->trace[] = [
'namespace' => '',
'short_class' => '',
'class' => '',
'type' => '',
'function' => '',
'file' => $file,
'line' => $line,
'args' => [],
];
foreach ($trace as $entry) {
$class = '';
$namespace = '';
if (isset($entry['class'])) {
$parts = explode('\\', $entry['class']);
$class = array_pop($parts);
$namespace = implode('\\', $parts);
}
$this->trace[] = [
'namespace' => $namespace,
'short_class' => $class,
'class' => isset($entry['class']) ? $entry['class'] : '',
'type' => isset($entry['type']) ? $entry['type'] : '',
'function' => isset($entry['function']) ? $entry['function'] : null,
'file' => isset($entry['file']) ? $entry['file'] : null,
'line' => isset($entry['line']) ? $entry['line'] : null,
'args' => isset($entry['args']) ? $this->flattenArgs($entry['args']) : [],
];
}
}
private function flattenArgs($args, $level = 0, &$count = 0)
{
$result = [];
foreach ($args as $key => $value) {
if (++$count > 1e4) {
return ['array', '*SKIPPED over 10000 entries*'];
}
if ($value instanceof \__PHP_Incomplete_Class) {
$result[$key] = ['incomplete-object', $this->getClassNameFromIncomplete($value)];
} elseif (\is_object($value)) {
$result[$key] = ['object', \get_class($value)];
} elseif (\is_array($value)) {
if ($level > 10) {
$result[$key] = ['array', '*DEEP NESTED ARRAY*'];
} else {
$result[$key] = ['array', $this->flattenArgs($value, $level + 1, $count)];
}
} elseif (null === $value) {
$result[$key] = ['null', null];
} elseif (\is_bool($value)) {
$result[$key] = ['boolean', $value];
} elseif (\is_int($value)) {
$result[$key] = ['integer', $value];
} elseif (\is_float($value)) {
$result[$key] = ['float', $value];
} elseif (\is_resource($value)) {
$result[$key] = ['resource', get_resource_type($value)];
} else {
$result[$key] = ['string', (string) $value];
}
}
return $result;
}
private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value)
{
$array = new \ArrayObject($value);
return $array['__PHP_Incomplete_Class_Name'];
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class FatalThrowableError extends FatalErrorException
{
public function __construct(\Throwable $e)
{
if ($e instanceof \ParseError) {
$message = 'Parse error: '.$e->getMessage();
$severity = \E_PARSE;
} elseif ($e instanceof \TypeError) {
$message = 'Type error: '.$e->getMessage();
$severity = \E_RECOVERABLE_ERROR;
} else {
$message = $e->getMessage();
$severity = \E_ERROR;
}
\ErrorException::__construct(
$message,
$e->getCode(),
$severity,
$e->getFile(),
$e->getLine(),
$e->getPrevious()
);
$this->setTrace($e->getTrace());
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class ClassNotFoundException extends FatalErrorException
{
public function __construct($message, \ErrorException $previous)
{
parent::__construct(
$message,
$previous->getCode(),
$previous->getSeverity(),
$previous->getFile(),
$previous->getLine(),
null,
true,
null,
$previous->getPrevious()
);
$this->setTrace($previous->getTrace());
}
}
<?php
namespace Symfony\Component\Debug\Exception;
class UndefinedMethodException extends FatalErrorException
{
public function __construct($message, \ErrorException $previous)
{
parent::__construct(
$message,
$previous->getCode(),
$previous->getSeverity(),
$previous->getFile(),
$previous->getLine(),
null,
true,
null,
$previous->getPrevious()
);
$this->setTrace($previous->getTrace());
}
}
<?php
namespace Symfony\Component\Debug;
use Psr\Log\AbstractLogger;
class BufferingLogger extends AbstractLogger
{
private $logs = [];
public function log($level, $message, array $context = [])
{
$this->logs[] = [$level, $message, $context];
}
public function cleanLogs()
{
$logs = $this->logs;
$this->logs = [];
return $logs;
}
}
<?php
namespace Symfony\Component\Debug;
class Debug
{
private static $enabled = false;
public static function enable($errorReportingLevel = \E_ALL, $displayErrors = true)
{
if (static::$enabled) {
return;
}
static::$enabled = true;
if (null !== $errorReportingLevel) {
error_reporting($errorReportingLevel);
} else {
error_reporting(\E_ALL);
}
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
ini_set('display_errors', 0);
ExceptionHandler::register();
} elseif ($displayErrors && (!filter_var(ini_get('log_errors'), \FILTER_VALIDATE_BOOLEAN) || ini_get('error_log'))) {
ini_set('display_errors', 1);
}
if ($displayErrors) {
ErrorHandler::register(new ErrorHandler(new BufferingLogger()));
} else {
ErrorHandler::register()->throwAt(0, true);
}
DebugClassLoader::enable();
}
}
<?php
use Symfony\Polyfill\Php72 as p;
if (PHP_VERSION_ID >= 70200) {
return;
}
if (!defined('PHP_FLOAT_DIG')) {
define('PHP_FLOAT_DIG', 15);
}
if (!defined('PHP_FLOAT_EPSILON')) {
define('PHP_FLOAT_EPSILON', 2.2204460492503E-16);
}
if (!defined('PHP_FLOAT_MIN')) {
define('PHP_FLOAT_MIN', 2.2250738585072E-308);
}
if (!defined('PHP_FLOAT_MAX')) {
define('PHP_FLOAT_MAX', 1.7976931348623157E+308);
}
if (!defined('PHP_OS_FAMILY')) {
define('PHP_OS_FAMILY', p\Php72::php_os_family());
}
if ('\\' === DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) {
function sapi_windows_vt100_support($stream, $enable = null) { return p\Php72::sapi_windows_vt100_support($stream, $enable); }
}
if (!function_exists('stream_isatty')) {
function stream_isatty($stream) { return p\Php72::stream_isatty($stream); }
}
if (!function_exists('utf8_encode')) {
function utf8_encode($string) { return p\Php72::utf8_encode($string); }
}
if (!function_exists('utf8_decode')) {
function utf8_decode($string) { return p\Php72::utf8_decode($string); }
}
if (!function_exists('spl_object_id')) {
function spl_object_id($object) { return p\Php72::spl_object_id($object); }
}
if (!function_exists('mb_ord')) {
function mb_ord($string, $encoding = null) { return p\Php72::mb_ord($string, $encoding); }
}
if (!function_exists('mb_chr')) {
function mb_chr($codepoint, $encoding = null) { return p\Php72::mb_chr($codepoint, $encoding); }
}
if (!function_exists('mb_scrub')) {
function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); }
}
<?php
namespace Symfony\Polyfill\Php72;
/**
@gmail
*/
final class Php72
{
private static $hashMask;
public static function utf8_encode($s)
{
$s .= $s;
$len = \strlen($s);
for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {
switch (true) {
case $s[$i] < "\x80": $s[$j] = $s[$i]; break;
case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break;
default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break;
}
}
return substr($s, 0, $j);
}
public static function utf8_decode($s)
{
$s = (string) $s;
$len = \strlen($s);
for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
switch ($s[$i] & "\xF0") {
case "\xC0":
case "\xD0":
$c = (\ord($s[$i] & "\x1F") << 6) | \ord($s[++$i] & "\x3F");
$s[$j] = $c < 256 ? \chr($c) : '?';
break;
case "\xF0":
++$i;
case "\xE0":
$s[$j] = '?';
$i += 2;
break;
default:
$s[$j] = $s[$i];
}
}
return substr($s, 0, $j);
}
public static function php_os_family()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
return 'Windows';
}
$map = array(
'Darwin' => 'Darwin',
'DragonFly' => 'BSD',
'FreeBSD' => 'BSD',
'NetBSD' => 'BSD',
'OpenBSD' => 'BSD',
'Linux' => 'Linux',
'SunOS' => 'Solaris',
);
return isset($map[PHP_OS]) ? $map[PHP_OS] : 'Unknown';
}
public static function spl_object_id($object)
{
if (null === self::$hashMask) {
self::initHashMask();
}
if (null === $hash = spl_object_hash($object)) {
return;
}
return self::$hashMask ^ hexdec(substr($hash, 16 - (\PHP_INT_SIZE * 2 - 1), (\PHP_INT_SIZE * 2 - 1)));
}
public static function sapi_windows_vt100_support($stream, $enable = null)
{
if (!\is_resource($stream)) {
trigger_error('sapi_windows_vt100_support() expects parameter 1 to be resource, '.\gettype($stream).' given', E_USER_WARNING);
return false;
}
$meta = stream_get_meta_data($stream);
if ('STDIO' !== $meta['stream_type']) {
trigger_error('sapi_windows_vt100_support() was not able to analyze the specified stream', E_USER_WARNING);
return false;
}
if (false === $enable || !self::stream_isatty($stream)) {
return false;
}
$meta = array_map('strtolower', $meta);
$stdin = 'php://stdin' === $meta['uri'] || 'php://fd/0' === $meta['uri'];
return !$stdin
&& (false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM')
|| 'Hyper' === getenv('TERM_PROGRAM'));
}
public static function stream_isatty($stream)
{
if (!\is_resource($stream)) {
trigger_error('stream_isatty() expects parameter 1 to be resource, '.\gettype($stream).' given', E_USER_WARNING);
return false;
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$stat = @fstat($stream);
return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
}
return \function_exists('posix_isatty') && @posix_isatty($stream);
}
private static function initHashMask()
{
$obj = (object) array();
self::$hashMask = -1;
$obFuncs = array('ob_clean', 'ob_end_clean', 'ob_flush', 'ob_end_flush', 'ob_get_contents', 'ob_get_flush');
foreach (debug_backtrace(\PHP_VERSION_ID >= 50400 ? DEBUG_BACKTRACE_IGNORE_ARGS : false) as $frame) {
if (isset($frame['function'][0]) && !isset($frame['class']) && 'o' === $frame['function'][0] && \in_array($frame['function'], $obFuncs)) {
$frame['line'] = 0;
break;
}
}
if (!empty($frame['line'])) {
ob_start();
debug_zval_dump($obj);
self::$hashMask = (int) substr(ob_get_clean(), 17);
}
self::$hashMask ^= hexdec(substr(spl_object_hash($obj), 16 - (\PHP_INT_SIZE * 2 - 1), (\PHP_INT_SIZE * 2 - 1)));
}
public static function mb_chr($code, $encoding = null)
{
if (0x80 > $code %= 0x200000) {
$s = \chr($code);
} elseif (0x800 > $code) {
$s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
} elseif (0x10000 > $code) {
$s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
} else {
$s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
}
if ('UTF-8' !== $encoding) {
$s = mb_convert_encoding($s, $encoding, 'UTF-8');
}
return $s;
}
public static function mb_ord($s, $encoding = null)
{
if (null === $encoding) {
$s = mb_convert_encoding($s, 'UTF-8');
} elseif ('UTF-8' !== $encoding) {
$s = mb_convert_encoding($s, 'UTF-8', $encoding);
}
if (1 === \strlen($s)) {
return \ord($s);
}
$code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0;
if (0xF0 <= $code) {
return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80;
}
if (0xE0 <= $code) {
return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80;
}
if (0xC0 <= $code) {
return (($code - 0xC0) << 6) + $s[2] - 0x80;
}
return $code;
}
}
<?php
use Symfony\Polyfill\Ctype as p;
if (!function_exists('ctype_alnum')) {
function ctype_alnum($input) { return p\Ctype::ctype_alnum($input); }
}
if (!function_exists('ctype_alpha')) {
function ctype_alpha($input) { return p\Ctype::ctype_alpha($input); }
}
if (!function_exists('ctype_cntrl')) {
function ctype_cntrl($input) { return p\Ctype::ctype_cntrl($input); }
}
if (!function_exists('ctype_digit')) {
function ctype_digit($input) { return p\Ctype::ctype_digit($input); }
}
if (!function_exists('ctype_graph')) {
function ctype_graph($input) { return p\Ctype::ctype_graph($input); }
}
if (!function_exists('ctype_lower')) {
function ctype_lower($input) { return p\Ctype::ctype_lower($input); }
}
if (!function_exists('ctype_print')) {
function ctype_print($input) { return p\Ctype::ctype_print($input); }
}
if (!function_exists('ctype_punct')) {
function ctype_punct($input) { return p\Ctype::ctype_punct($input); }
}
if (!function_exists('ctype_space')) {
function ctype_space($input) { return p\Ctype::ctype_space($input); }
}
if (!function_exists('ctype_upper')) {
function ctype_upper($input) { return p\Ctype::ctype_upper($input); }
}
if (!function_exists('ctype_xdigit')) {
function ctype_xdigit($input) { return p\Ctype::ctype_xdigit($input); }
}
<?php
namespace Symfony\Polyfill\Ctype;
final class Ctype
{
public static function ctype_alnum($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text);
}
public static function ctype_alpha($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text);
}
public static function ctype_cntrl($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text);
}
public static function ctype_digit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text);
}
public static function ctype_graph($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
}
public static function ctype_lower($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text);
}
public static function ctype_print($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text);
}
public static function ctype_punct($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text);
}
public static function ctype_space($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text);
}
public static function ctype_upper($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text);
}
public static function ctype_xdigit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text);
}
private static function convert_int_to_char_for_ctype($int)
{
if (!\is_int($int)) {
return $int;
}
if ($int < -128 || $int > 255) {
return (string) $int;
}
if ($int < 0) {
$int += 256;
}
return \chr($int);
}
}
<?php
use Symfony\Polyfill\Mbstring as p;
if (!function_exists('mb_convert_encoding')) {
function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); }
}
if (!function_exists('mb_decode_mimeheader')) {
function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); }
}
if (!function_exists('mb_encode_mimeheader')) {
function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = null, $indent = null) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); }
}
if (!function_exists('mb_decode_numericentity')) {
function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); }
}
if (!function_exists('mb_encode_numericentity')) {
function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); }
}
if (!function_exists('mb_convert_case')) {
function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); }
}
if (!function_exists('mb_internal_encoding')) {
function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); }
}
if (!function_exists('mb_language')) {
function mb_language($language = null) { return p\Mbstring::mb_language($language); }
}
if (!function_exists('mb_list_encodings')) {
function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); }
}
if (!function_exists('mb_encoding_aliases')) {
function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); }
}
if (!function_exists('mb_check_encoding')) {
function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); }
}
if (!function_exists('mb_detect_encoding')) {
function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); }
}
if (!function_exists('mb_detect_order')) {
function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); }
}
if (!function_exists('mb_parse_str')) {
function mb_parse_str($string, &$result = array()) { parse_str($string, $result); }
}
if (!function_exists('mb_strlen')) {
function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); }
}
if (!function_exists('mb_strpos')) {
function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strtolower')) {
function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); }
}
if (!function_exists('mb_strtoupper')) {
function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); }
}
if (!function_exists('mb_substitute_character')) {
function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); }
}
if (!function_exists('mb_substr')) {
function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); }
}
if (!function_exists('mb_stripos')) {
function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_stristr')) {
function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strrchr')) {
function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strrichr')) {
function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strripos')) {
function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strrpos')) {
function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strstr')) {
function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_get_info')) {
function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); }
}
if (!function_exists('mb_http_output')) {
function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); }
}
if (!function_exists('mb_strwidth')) {
function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); }
}
if (!function_exists('mb_substr_count')) {
function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); }
}
if (!function_exists('mb_output_handler')) {
function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); }
}
if (!function_exists('mb_http_input')) {
function mb_http_input($type = '') { return p\Mbstring::mb_http_input($type); }
}
if (PHP_VERSION_ID >= 80000) {
require_once __DIR__.'/Resources/mb_convert_variables.php8';
} elseif (!function_exists('mb_convert_variables')) {
function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null) { return p\Mbstring::mb_convert_variables($toEncoding, $fromEncoding, $a, $b, $c, $d, $e, $f); }
}
if (!function_exists('mb_ord')) {
function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); }
}
if (!function_exists('mb_chr')) {
function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); }
}
if (!function_exists('mb_scrub')) {
function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); }
}
if (!function_exists('mb_str_split')) {
function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); }
}
if (extension_loaded('mbstring')) {
return;
}
if (!defined('MB_CASE_UPPER')) {
define('MB_CASE_UPPER', 0);
}
if (!defined('MB_CASE_LOWER')) {
define('MB_CASE_LOWER', 1);
}
if (!defined('MB_CASE_TITLE')) {
define('MB_CASE_TITLE', 2);
}
<?php
namespace Symfony\Polyfill\Mbstring;
final class Mbstring
{
const MB_CASE_FOLD = PHP_INT_MAX;
private static $encodingList = array('ASCII', 'UTF-8');
private static $language = 'neutral';
private static $internalEncoding = 'UTF-8';
private static $caseFold = array(
array('µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"),
array('μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'),
);
public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null)
{
if (\is_array($fromEncoding) || false !== strpos($fromEncoding, ',')) {
$fromEncoding = self::mb_detect_encoding($s, $fromEncoding);
} else {
$fromEncoding = self::getEncoding($fromEncoding);
}
$toEncoding = self::getEncoding($toEncoding);
if ('BASE64' === $fromEncoding) {
$s = base64_decode($s);
$fromEncoding = $toEncoding;
}
if ('BASE64' === $toEncoding) {
return base64_encode($s);
}
if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) {
if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) {
$fromEncoding = 'Windows-1252';
}
if ('UTF-8' !== $fromEncoding) {
$s = iconv($fromEncoding, 'UTF-8//IGNORE', $s);
}
return preg_replace_callback('/[\x80-\xFF]+/', array(__CLASS__, 'html_encoding_callback'), $s);
}
if ('HTML-ENTITIES' === $fromEncoding) {
$s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
$fromEncoding = 'UTF-8';
}
return iconv($fromEncoding, $toEncoding.'//IGNORE', $s);
}
public static function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null)
{
$vars = array(&$a, &$b, &$c, &$d, &$e, &$f);
$ok = true;
array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) {
if (false === $v = Mbstring::mb_convert_encoding($v, $toEncoding, $fromEncoding)) {
$ok = false;
}
});
return $ok ? $fromEncoding : false;
}
public static function mb_decode_mimeheader($s)
{
return iconv_mime_decode($s, 2, self::$internalEncoding);
}
public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null)
{
trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', E_USER_WARNING);
}
public static function mb_decode_numericentity($s, $convmap, $encoding = null)
{
if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) {
trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING);
return null;
}
if (!\is_array($convmap) || !$convmap) {
return false;
}
if (null !== $encoding && !\is_scalar($encoding)) {
trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING);
return '';
}
$s = (string) $s;
if ('' === $s) {
return '';
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
$encoding = null;
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
}
} else {
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
}
$cnt = floor(\count($convmap) / 4) * 4;
for ($i = 0; $i < $cnt; $i += 4) {
$convmap[$i] += $convmap[$i + 2];
$convmap[$i + 1] += $convmap[$i + 2];
}
$s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) {
$c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1];
for ($i = 0; $i < $cnt; $i += 4) {
if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) {
return Mbstring::mb_chr($c - $convmap[$i + 2]);
}
}
return $m[0];
}, $s);
if (null === $encoding) {
return $s;
}
return iconv('UTF-8', $encoding.'//IGNORE', $s);
}
public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false)
{
if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) {
trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING);
return null;
}
if (!\is_array($convmap) || !$convmap) {
return false;
}
if (null !== $encoding && !\is_scalar($encoding)) {
trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING);
return null;
}
if (null !== $is_hex && !\is_scalar($is_hex)) {
trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', E_USER_WARNING);
return null;
}
$s = (string) $s;
if ('' === $s) {
return '';
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
$encoding = null;
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
}
} else {
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
}
static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4);
$cnt = floor(\count($convmap) / 4) * 4;
$i = 0;
$len = \strlen($s);
$result = '';
while ($i < $len) {
$ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
$uchr = substr($s, $i, $ulen);
$i += $ulen;
$c = self::mb_ord($uchr);
for ($j = 0; $j < $cnt; $j += 4) {
if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) {
$cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3];
$result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';';
continue 2;
}
}
$result .= $uchr;
}
if (null === $encoding) {
return $result;
}
return iconv('UTF-8', $encoding.'//IGNORE', $result);
}
public static function mb_convert_case($s, $mode, $encoding = null)
{
$s = (string) $s;
if ('' === $s) {
return '';
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
$encoding = null;
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
}
} else {
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
}
if (MB_CASE_TITLE == $mode) {
static $titleRegexp = null;
if (null === $titleRegexp) {
$titleRegexp = self::getData('titleCaseRegexp');
}
$s = preg_replace_callback($titleRegexp, array(__CLASS__, 'title_case'), $s);
} else {
if (MB_CASE_UPPER == $mode) {
static $upper = null;
if (null === $upper) {
$upper = self::getData('upperCase');
}
$map = $upper;
} else {
if (self::MB_CASE_FOLD === $mode) {
$s = str_replace(self::$caseFold[0], self::$caseFold[1], $s);
}
static $lower = null;
if (null === $lower) {
$lower = self::getData('lowerCase');
}
$map = $lower;
}
static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4);
$i = 0;
$len = \strlen($s);
while ($i < $len) {
$ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
$uchr = substr($s, $i, $ulen);
$i += $ulen;
if (isset($map[$uchr])) {
$uchr = $map[$uchr];
$nlen = \strlen($uchr);
if ($nlen == $ulen) {
$nlen = $i;
do {
$s[--$nlen] = $uchr[--$ulen];
} while ($ulen);
} else {
$s = substr_replace($s, $uchr, $i - $ulen, $ulen);
$len += $nlen - $ulen;
$i += $nlen - $ulen;
}
}
}
}
if (null === $encoding) {
return $s;
}
return iconv('UTF-8', $encoding.'//IGNORE', $s);
}
public static function mb_internal_encoding($encoding = null)
{
if (null === $encoding) {
return self::$internalEncoding;
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding || false !== @iconv($encoding, $encoding, ' ')) {
self::$internalEncoding = $encoding;
return true;
}
return false;
}
public static function mb_language($lang = null)
{
if (null === $lang) {
return self::$language;
}
switch ($lang = strtolower($lang)) {
case 'uni':
case 'neutral':
self::$language = $lang;
return true;
}
return false;
}
public static function mb_list_encodings()
{
return array('UTF-8');
}
public static function mb_encoding_aliases($encoding)
{
switch (strtoupper($encoding)) {
case 'UTF8':
case 'UTF-8':
return array('utf8');
}
return false;
}
public static function mb_check_encoding($var = null, $encoding = null)
{
if (null === $encoding) {
if (null === $var) {
return false;
}
$encoding = self::$internalEncoding;
}
return self::mb_detect_encoding($var, array($encoding)) || false !== @iconv($encoding, $encoding, $var);
}
public static function mb_detect_encoding($str, $encodingList = null, $strict = false)
{
if (null === $encodingList) {
$encodingList = self::$encodingList;
} else {
if (!\is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
}
$encodingList = array_map('strtoupper', $encodingList);
}
foreach ($encodingList as $enc) {
switch ($enc) {
case 'ASCII':
if (!preg_match('/[\x80-\xFF]/', $str)) {
return $enc;
}
break;
case 'UTF8':
case 'UTF-8':
if (preg_match('//u', $str)) {
return 'UTF-8';
}
break;
default:
if (0 === strncmp($enc, 'ISO-8859-', 9)) {
return $enc;
}
}
}
return false;
}
public static function mb_detect_order($encodingList = null)
{
if (null === $encodingList) {
return self::$encodingList;
}
if (!\is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
}
$encodingList = array_map('strtoupper', $encodingList);
foreach ($encodingList as $enc) {
switch ($enc) {
default:
if (strncmp($enc, 'ISO-8859-', 9)) {
return false;
}
case 'ASCII':
case 'UTF8':
case 'UTF-8':
}
}
self::$encodingList = $encodingList;
return true;
}
public static function mb_strlen($s, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return \strlen($s);
}
return @iconv_strlen($s, $encoding);
}
public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return strpos($haystack, $needle, $offset);
}
$needle = (string) $needle;
if ('' === $needle) {
trigger_error(__METHOD__.': Empty delimiter', E_USER_WARNING);
return false;
}
return iconv_strpos($haystack, $needle, $offset, $encoding);
}
public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return strrpos($haystack, $needle, $offset);
}
if ($offset != (int) $offset) {
$offset = 0;
} elseif ($offset = (int) $offset) {
if ($offset < 0) {
if (0 > $offset += self::mb_strlen($needle)) {
$haystack = self::mb_substr($haystack, 0, $offset, $encoding);
}
$offset = 0;
} else {
$haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding);
}
}
$pos = iconv_strrpos($haystack, $needle, $encoding);
return false !== $pos ? $offset + $pos : false;
}
public static function mb_str_split($string, $split_length = 1, $encoding = null)
{
if (null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) {
trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', E_USER_WARNING);
return null;
}
if (1 > $split_length = (int) $split_length) {
trigger_error('The length of each segment must be greater than zero', E_USER_WARNING);
return false;
}
if (null === $encoding) {
$encoding = mb_internal_encoding();
}
if ('UTF-8' === $encoding = self::getEncoding($encoding)) {
$rx = '/(';
while (65535 < $split_length) {
$rx .= '.{65535}';
$split_length -= 65535;
}
$rx .= '.{'.$split_length.'})/us';
return preg_split($rx, $string, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
$result = array();
$length = mb_strlen($string, $encoding);
for ($i = 0; $i < $length; $i += $split_length) {
$result[] = mb_substr($string, $i, $split_length, $encoding);
}
return $result;
}
public static function mb_strtolower($s, $encoding = null)
{
return self::mb_convert_case($s, MB_CASE_LOWER, $encoding);
}
public static function mb_strtoupper($s, $encoding = null)
{
return self::mb_convert_case($s, MB_CASE_UPPER, $encoding);
}
public static function mb_substitute_character($c = null)
{
if (0 === strcasecmp($c, 'none')) {
return true;
}
return null !== $c ? false : 'none';
}
public static function mb_substr($s, $start, $length = null, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return (string) substr($s, $start, null === $length ? 2147483647 : $length);
}
if ($start < 0) {
$start = iconv_strlen($s, $encoding) + $start;
if ($start < 0) {
$start = 0;
}
}
if (null === $length) {
$length = 2147483647;
} elseif ($length < 0) {
$length = iconv_strlen($s, $encoding) + $length - $start;
if ($length < 0) {
return '';
}
}
return (string) iconv_substr($s, $start, $length, $encoding);
}
public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null)
{
$haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding);
$needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding);
return self::mb_strpos($haystack, $needle, $offset, $encoding);
}
public static function mb_stristr($haystack, $needle, $part = false, $encoding = null)
{
$pos = self::mb_stripos($haystack, $needle, 0, $encoding);
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
$pos = strrpos($haystack, $needle);
} else {
$needle = self::mb_substr($needle, 0, 1, $encoding);
$pos = iconv_strrpos($haystack, $needle, $encoding);
}
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null)
{
$needle = self::mb_substr($needle, 0, 1, $encoding);
$pos = self::mb_strripos($haystack, $needle, $encoding);
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null)
{
$haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding);
$needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding);
return self::mb_strrpos($haystack, $needle, $offset, $encoding);
}
public static function mb_strstr($haystack, $needle, $part = false, $encoding = null)
{
$pos = strpos($haystack, $needle);
if (false === $pos) {
return false;
}
if ($part) {
return substr($haystack, 0, $pos);
}
return substr($haystack, $pos);
}
public static function mb_get_info($type = 'all')
{
$info = array(
'internal_encoding' => self::$internalEncoding,
'http_output' => 'pass',
'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)',
'func_overload' => 0,
'func_overload_list' => 'no overload',
'mail_charset' => 'UTF-8',
'mail_header_encoding' => 'BASE64',
'mail_body_encoding' => 'BASE64',
'illegal_chars' => 0,
'encoding_translation' => 'Off',
'language' => self::$language,
'detect_order' => self::$encodingList,
'substitute_character' => 'none',
'strict_detection' => 'Off',
);
if ('all' === $type) {
return $info;
}
if (isset($info[$type])) {
return $info[$type];
}
return false;
}
public static function mb_http_input($type = '')
{
return false;
}
public static function mb_http_output($encoding = null)
{
return null !== $encoding ? 'pass' === $encoding : 'pass';
}
public static function mb_strwidth($s, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('UTF-8' !== $encoding) {
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
}
$s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide);
return ($wide << 1) + iconv_strlen($s, 'UTF-8');
}
public static function mb_substr_count($haystack, $needle, $encoding = null)
{
return substr_count($haystack, $needle);
}
public static function mb_output_handler($contents, $status)
{
return $contents;
}
public static function mb_chr($code, $encoding = null)
{
if (0x80 > $code %= 0x200000) {
$s = \chr($code);
} elseif (0x800 > $code) {
$s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
} elseif (0x10000 > $code) {
$s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
} else {
$s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
}
if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
$s = mb_convert_encoding($s, $encoding, 'UTF-8');
}
return $s;
}
public static function mb_ord($s, $encoding = null)
{
if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
$s = mb_convert_encoding($s, 'UTF-8', $encoding);
}
if (1 === \strlen($s)) {
return \ord($s);
}
$code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0;
if (0xF0 <= $code) {
return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80;
}
if (0xE0 <= $code) {
return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80;
}
if (0xC0 <= $code) {
return (($code - 0xC0) << 6) + $s[2] - 0x80;
}
return $code;
}
private static function getSubpart($pos, $part, $haystack, $encoding)
{
if (false === $pos) {
return false;
}
if ($part) {
return self::mb_substr($haystack, 0, $pos, $encoding);
}
return self::mb_substr($haystack, $pos, null, $encoding);
}
private static function html_encoding_callback(array $m)
{
$i = 1;
$entities = '';
$m = unpack('C*', htmlentities($m[0], ENT_COMPAT, 'UTF-8'));
while (isset($m[$i])) {
if (0x80 > $m[$i]) {
$entities .= \chr($m[$i++]);
continue;
}
if (0xF0 <= $m[$i]) {
$c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
} elseif (0xE0 <= $m[$i]) {
$c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
} else {
$c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80;
}
$entities .= '&#'.$c.';';
}
return $entities;
}
private static function title_case(array $s)
{
return self::mb_convert_case($s[1], MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], MB_CASE_LOWER, 'UTF-8');
}
private static function getData($file)
{
if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) {
return require $file;
}
return false;
}
private static function getEncoding($encoding)
{
if (null === $encoding) {
return self::$internalEncoding;
}
if ('UTF-8' === $encoding) {
return 'UTF-8';
}
$encoding = strtoupper($encoding);
if ('8BIT' === $encoding || 'BINARY' === $encoding) {
return 'CP850';
}
if ('UTF8' === $encoding) {
return 'UTF-8';
}
return $encoding;
}
}
<?php
return array (
'a' => 'A',
'b' => 'B',
'c' => 'C',
'd' => 'D',
'e' => 'E',
'f' => 'F',
'g' => 'G',
'h' => 'H',
'i' => 'I',
'j' => 'J',
'k' => 'K',
'l' => 'L',
'm' => 'M',
'n' => 'N',
'o' => 'O',
'p' => 'P',
'q' => 'Q',
'r' => 'R',
's' => 'S',
't' => 'T',
'u' => 'U',
'v' => 'V',
'w' => 'W',
'x' => 'X',
'y' => 'Y',
'z' => 'Z',
'µ' => 'Μ',
'à' => 'À',
'á' => 'Á',
'â' => 'Â',
'ã' => 'Ã',
'ä' => 'Ä',
'å' => 'Å',
'æ' => 'Æ',
'ç' => 'Ç',
'è' => 'È',
'é' => 'É',
'ê' => 'Ê',
'ë' => 'Ë',
'ì' => 'Ì',
'í' => 'Í',
'î' => 'Î',
'ï' => 'Ï',
'ð' => 'Ð',
'ñ' => 'Ñ',
'ò' => 'Ò',
'ó' => 'Ó',
'ô' => 'Ô',
'õ' => 'Õ',
'ö' => 'Ö',
'ø' => 'Ø',
'ù' => 'Ù',
'ú' => 'Ú',
'û' => 'Û',
'ü' => 'Ü',
'ý' => 'Ý',
'þ' => 'Þ',
'ÿ' => 'Ÿ',
'ā' => 'Ā',
'ă' => 'Ă',
'ą' => 'Ą',
'ć' => 'Ć',
'ĉ' => 'Ĉ',
'ċ' => 'Ċ',
'č' => 'Č',
'ď' => 'Ď',
'đ' => 'Đ',
'ē' => 'Ē',
'ĕ' => 'Ĕ',
'ė' => 'Ė',
'ę' => 'Ę',
'ě' => 'Ě',
'ĝ' => 'Ĝ',
'ğ' => 'Ğ',
'ġ' => 'Ġ',
'ģ' => 'Ģ',
'ĥ' => 'Ĥ',
'ħ' => 'Ħ',
'ĩ' => 'Ĩ',
'ī' => 'Ī',
'ĭ' => 'Ĭ',
'į' => 'Į',
'ı' => 'I',
'ij' => 'IJ',
'ĵ' => 'Ĵ',
'ķ' => 'Ķ',
'ĺ' => 'Ĺ',
'ļ' => 'Ļ',
'ľ' => 'Ľ',
'ŀ' => 'Ŀ',
'ł' => 'Ł',
'ń' => 'Ń',
'ņ' => 'Ņ',
'ň' => 'Ň',
'ŋ' => 'Ŋ',
'ō' => 'Ō',
'ŏ' => 'Ŏ',
'ő' => 'Ő',
'œ' => 'Œ',
'ŕ' => 'Ŕ',
'ŗ' => 'Ŗ',
'ř' => 'Ř',
'ś' => 'Ś',
'ŝ' => 'Ŝ',
'ş' => 'Ş',
'š' => 'Š',
'ţ' => 'Ţ',
'ť' => 'Ť',
'ŧ' => 'Ŧ',
'ũ' => 'Ũ',
'ū' => 'Ū',
'ŭ' => 'Ŭ',
'ů' => 'Ů',
'ű' => 'Ű',
'ų' => 'Ų',
'ŵ' => 'Ŵ',
'ŷ' => 'Ŷ',
'ź' => 'Ź',
'ż' => 'Ż',
'ž' => 'Ž',
'ſ' => 'S',
'ƀ' => 'Ƀ',
'ƃ' => 'Ƃ',
'ƅ' => 'Ƅ',
'ƈ' => 'Ƈ',
'ƌ' => 'Ƌ',
'ƒ' => 'Ƒ',
'ƕ' => 'Ƕ',
'ƙ' => 'Ƙ',
'ƚ' => 'Ƚ',
'ƞ' => 'Ƞ',
'ơ' => 'Ơ',
'ƣ' => 'Ƣ',
'ƥ' => 'Ƥ',
'ƨ' => 'Ƨ',
'ƭ' => 'Ƭ',
'ư' => 'Ư',
'ƴ' => 'Ƴ',
'ƶ' => 'Ƶ',
'ƹ' => 'Ƹ',
'ƽ' => 'Ƽ',
'ƿ' => 'Ƿ',
'Dž' => 'DŽ',
'dž' => 'DŽ',
'Lj' => 'LJ',
'lj' => 'LJ',
'Nj' => 'NJ',
'nj' => 'NJ',
'ǎ' => 'Ǎ',
'ǐ' => 'Ǐ',
'ǒ' => 'Ǒ',
'ǔ' => 'Ǔ',
'ǖ' => 'Ǖ',
'ǘ' => 'Ǘ',
'ǚ' => 'Ǚ',
'ǜ' => 'Ǜ',
'ǝ' => 'Ǝ',
'ǟ' => 'Ǟ',
'ǡ' => 'Ǡ',
'ǣ' => 'Ǣ',
'ǥ' => 'Ǥ',
'ǧ' => 'Ǧ',
'ǩ' => 'Ǩ',
'ǫ' => 'Ǫ',
'ǭ' => 'Ǭ',
'ǯ' => 'Ǯ',
'Dz' => 'DZ',
'dz' => 'DZ',
'ǵ' => 'Ǵ',
'ǹ' => 'Ǹ',
'ǻ' => 'Ǻ',
'ǽ' => 'Ǽ',
'ǿ' => 'Ǿ',
'ȁ' => 'Ȁ',
'ȃ' => 'Ȃ',
'ȅ' => 'Ȅ',
'ȇ' => 'Ȇ',
'ȉ' => 'Ȉ',
'ȋ' => 'Ȋ',
'ȍ' => 'Ȍ',
'ȏ' => 'Ȏ',
'ȑ' => 'Ȑ',
'ȓ' => 'Ȓ',
'ȕ' => 'Ȕ',
'ȗ' => 'Ȗ',
'ș' => 'Ș',
'ț' => 'Ț',
'ȝ' => 'Ȝ',
'ȟ' => 'Ȟ',
'ȣ' => 'Ȣ',
'ȥ' => 'Ȥ',
'ȧ' => 'Ȧ',
'ȩ' => 'Ȩ',
'ȫ' => 'Ȫ',
'ȭ' => 'Ȭ',
'ȯ' => 'Ȯ',
'ȱ' => 'Ȱ',
'ȳ' => 'Ȳ',
'ȼ' => 'Ȼ',
'ȿ' => 'Ȿ',
'ɀ' => 'Ɀ',
'ɂ' => 'Ɂ',
'ɇ' => 'Ɇ',
'ɉ' => 'Ɉ',
'ɋ' => 'Ɋ',
'ɍ' => 'Ɍ',
'ɏ' => 'Ɏ',
'ɐ' => 'Ɐ',
'ɑ' => 'Ɑ',
'ɒ' => 'Ɒ',
'ɓ' => 'Ɓ',
'ɔ' => 'Ɔ',
'ɖ' => 'Ɖ',
'ɗ' => 'Ɗ',
'ə' => 'Ə',
'ɛ' => 'Ɛ',
'ɜ' => '',
'ɠ' => 'Ɠ',
'ɡ' => 'Ɡ',
'ɣ' => 'Ɣ',
'ɥ' => 'Ɥ',
'ɦ' => 'Ɦ',
'ɨ' => 'Ɨ',
'ɩ' => 'Ɩ',
'ɪ' => 'Ɪ',
'ɫ' => 'Ɫ',
'ɬ' => 'Ɬ',
'ɯ' => 'Ɯ',
'ɱ' => 'Ɱ',
'ɲ' => 'Ɲ',
'ɵ' => 'Ɵ',
'ɽ' => 'Ɽ',
'ʀ' => 'Ʀ',
'ʂ' => 'Ʂ',
'ʃ' => 'Ʃ',
'ʇ' => 'Ʇ',
'ʈ' => 'Ʈ',
'ʉ' => 'Ʉ',
'ʊ' => 'Ʊ',
'ʋ' => 'Ʋ',
'ʌ' => 'Ʌ',
'ʒ' => 'Ʒ',
'ʝ' => '',
'ʞ' => 'Ʞ',
'ͅ' => 'Ι',
'ͱ' => 'Ͱ',
'ͳ' => 'Ͳ',
'ͷ' => 'Ͷ',
'ͻ' => 'Ͻ',
'ͼ' => 'Ͼ',
'ͽ' => 'Ͽ',
'ά' => 'Ά',
'έ' => 'Έ',
'ή' => 'Ή',
'ί' => 'Ί',
'α' => 'Α',
'β' => 'Β',
'γ' => 'Γ',
'δ' => 'Δ',
'ε' => 'Ε',
'ζ' => 'Ζ',
'η' => 'Η',
'θ' => 'Θ',
'ι' => 'Ι',
'κ' => 'Κ',
'λ' => 'Λ',
'μ' => 'Μ',
'ν' => 'Ν',
'ξ' => 'Ξ',
'ο' => 'Ο',
'π' => 'Π',
'ρ' => 'Ρ',
'ς' => 'Σ',
'σ' => 'Σ',
'τ' => 'Τ',
'υ' => 'Υ',
'φ' => 'Φ',
'χ' => 'Χ',
'ψ' => 'Ψ',
'ω' => 'Ω',
'ϊ' => 'Ϊ',
'ϋ' => 'Ϋ',
'ό' => 'Ό',
'ύ' => 'Ύ',
'ώ' => 'Ώ',
'ϐ' => 'Β',
'ϑ' => 'Θ',
'ϕ' => 'Φ',
'ϖ' => 'Π',
'ϗ' => 'Ϗ',
'ϙ' => 'Ϙ',
'ϛ' => 'Ϛ',
'ϝ' => 'Ϝ',
'ϟ' => 'Ϟ',
'ϡ' => 'Ϡ',
'ϣ' => 'Ϣ',
'ϥ' => 'Ϥ',
'ϧ' => 'Ϧ',
'ϩ' => 'Ϩ',
'ϫ' => 'Ϫ',
'ϭ' => 'Ϭ',
'ϯ' => 'Ϯ',
'ϰ' => 'Κ',
'ϱ' => 'Ρ',
'ϲ' => 'Ϲ',
'ϳ' => 'Ϳ',
'ϵ' => 'Ε',
'ϸ' => 'Ϸ',
'ϻ' => 'Ϻ',
'а' => 'А',
'б' => 'Б',
'в' => 'В',
'г' => 'Г',
'д' => 'Д',
'е' => 'Е',
'ж' => 'Ж',
'з' => 'З',
'и' => 'И',
'й' => 'Й',
'к' => 'К',
'л' => 'Л',
'м' => 'М',
'н' => 'Н',
'о' => 'О',
'п' => 'П',
'р' => 'Р',
'с' => 'С',
'т' => 'Т',
'у' => 'У',
'ф' => 'Ф',
'х' => 'Х',
'ц' => 'Ц',
'ч' => 'Ч',
'ш' => 'Ш',
'щ' => 'Щ',
'ъ' => 'Ъ',
'ы' => 'Ы',
'ь' => 'Ь',
'э' => 'Э',
'ю' => 'Ю',
'я' => 'Я',
'ѐ' => 'Ѐ',
'ё' => 'Ё',
'ђ' => 'Ђ',
'ѓ' => 'Ѓ',
'є' => 'Є',
'ѕ' => 'Ѕ',
'і' => 'І',
'ї' => 'Ї',
'ј' => 'Ј',
'љ' => 'Љ',
'њ' => 'Њ',
'ћ' => 'Ћ',
'ќ' => 'Ќ',
'ѝ' => 'Ѝ',
'ў' => 'Ў',
'џ' => 'Џ',
'ѡ' => 'Ѡ',
'ѣ' => 'Ѣ',
'ѥ' => 'Ѥ',
'ѧ' => 'Ѧ',
'ѩ' => 'Ѩ',
'ѫ' => 'Ѫ',
'ѭ' => 'Ѭ',
'ѯ' => 'Ѯ',
'ѱ' => 'Ѱ',
'ѳ' => 'Ѳ',
'ѵ' => 'Ѵ',
'ѷ' => 'Ѷ',
'ѹ' => 'Ѹ',
'ѻ' => 'Ѻ',
'ѽ' => 'Ѽ',
'ѿ' => 'Ѿ',
'ҁ' => 'Ҁ',
'ҋ' => 'Ҋ',
'ҍ' => 'Ҍ',
'ҏ' => 'Ҏ',
'ґ' => 'Ґ',
'ғ' => 'Ғ',
'ҕ' => 'Ҕ',
'җ' => 'Җ',
'ҙ' => 'Ҙ',
'қ' => 'Қ',
'ҝ' => 'Ҝ',
'ҟ' => 'Ҟ',
'ҡ' => 'Ҡ',
'ң' => 'Ң',
'ҥ' => 'Ҥ',
'ҧ' => 'Ҧ',
'ҩ' => 'Ҩ',
'ҫ' => 'Ҫ',
'ҭ' => 'Ҭ',
'ү' => 'Ү',
'ұ' => 'Ұ',
'ҳ' => 'Ҳ',
'ҵ' => 'Ҵ',
'ҷ' => 'Ҷ',
'ҹ' => 'Ҹ',
'һ' => 'Һ',
'ҽ' => 'Ҽ',
'ҿ' => 'Ҿ',
'ӂ' => 'Ӂ',
'ӄ' => 'Ӄ',
'ӆ' => 'Ӆ',
'ӈ' => 'Ӈ',
'ӊ' => 'Ӊ',
'ӌ' => 'Ӌ',
'ӎ' => 'Ӎ',
'ӏ' => 'Ӏ',
'ӑ' => 'Ӑ',
'ӓ' => 'Ӓ',
'ӕ' => 'Ӕ',
'ӗ' => 'Ӗ',
'ә' => 'Ә',
'ӛ' => 'Ӛ',
'ӝ' => 'Ӝ',
'ӟ' => 'Ӟ',
'ӡ' => 'Ӡ',
'ӣ' => 'Ӣ',
'ӥ' => 'Ӥ',
'ӧ' => 'Ӧ',
'ө' => 'Ө',
'ӫ' => 'Ӫ',
'ӭ' => 'Ӭ',
'ӯ' => 'Ӯ',
'ӱ' => 'Ӱ',
'ӳ' => 'Ӳ',
'ӵ' => 'Ӵ',
'ӷ' => 'Ӷ',
'ӹ' => 'Ӹ',
'ӻ' => 'Ӻ',
'ӽ' => 'Ӽ',
'ӿ' => 'Ӿ',
'ԁ' => 'Ԁ',
'ԃ' => 'Ԃ',
'ԅ' => 'Ԅ',
'ԇ' => 'Ԇ',
'ԉ' => 'Ԉ',
'ԋ' => 'Ԋ',
'ԍ' => 'Ԍ',
'ԏ' => 'Ԏ',
'ԑ' => 'Ԑ',
'ԓ' => 'Ԓ',
'ԕ' => 'Ԕ',
'ԗ' => 'Ԗ',
'ԙ' => 'Ԙ',
'ԛ' => 'Ԛ',
'ԝ' => 'Ԝ',
'ԟ' => 'Ԟ',
'ԡ' => 'Ԡ',
'ԣ' => 'Ԣ',
'ԥ' => 'Ԥ',
'ԧ' => 'Ԧ',
'ԩ' => 'Ԩ',
'ԫ' => 'Ԫ',
'ԭ' => 'Ԭ',
'ԯ' => 'Ԯ',
'ա' => 'Ա',
'բ' => 'Բ',
'գ' => 'Գ',
'դ' => 'Դ',
'ե' => 'Ե',
'զ' => 'Զ',
'է' => 'Է',
'ը' => 'Ը',
'թ' => 'Թ',
'ժ' => 'Ժ',
'ի' => 'Ի',
'լ' => 'Լ',
'խ' => 'Խ',
'ծ' => 'Ծ',
'կ' => 'Կ',
'հ' => 'Հ',
'ձ' => 'Ձ',
'ղ' => 'Ղ',
'ճ' => 'Ճ',
'մ' => 'Մ',
'յ' => 'Յ',
'ն' => 'Ն',
'շ' => 'Շ',
'ո' => 'Ո',
'չ' => 'Չ',
'պ' => 'Պ',
'ջ' => 'Ջ',
'ռ' => 'Ռ',
'ս' => 'Ս',
'վ' => 'Վ',
'տ' => 'Տ',
'ր' => 'Ր',
'ց' => 'Ց',
'ւ' => 'Ւ',
'փ' => 'Փ',
'ք' => 'Ք',
'օ' => 'Օ',
'ֆ' => 'Ֆ',
'ა' => 'Ა',
'ბ' => 'Ბ',
'გ' => 'Გ',
'დ' => 'Დ',
'ე' => 'Ე',
'ვ' => 'Ვ',
'ზ' => 'Ზ',
'თ' => 'Თ',
'ი' => 'Ი',
'კ' => 'Კ',
'ლ' => 'Ლ',
'მ' => 'Მ',
'ნ' => 'Ნ',
'ო' => 'Ო',
'პ' => 'Პ',
'ჟ' => 'Ჟ',
'რ' => 'Რ',
'ს' => 'Ს',
'ტ' => 'Ტ',
'უ' => 'Უ',
'ფ' => 'Ფ',
'ქ' => 'Ქ',
'ღ' => 'Ღ',
'' => 'Ყ',
'შ' => 'Შ',
'ჩ' => 'Ჩ',
'ც' => 'Ც',
'ძ' => 'Ძ',
'წ' => 'Წ',
'ჭ' => 'Ჭ',
'ხ' => 'Ხ',
'ჯ' => 'Ჯ',
'ჰ' => 'Ჰ',
'ჱ' => 'Ჱ',
'ჲ' => 'Ჲ',
'ჳ' => 'Ჳ',
'ჴ' => 'Ჴ',
'ჵ' => 'Ჵ',
'ჶ' => 'Ჶ',
'ჷ' => 'Ჷ',
'ჸ' => 'Ჸ',
'ჹ' => 'Ჹ',
'ჺ' => 'Ჺ',
'ჽ' => 'Ჽ',
'ჾ' => 'Ჾ',
'' => 'Ჿ',
'ᏸ' => 'Ᏸ',
'ᏹ' => 'Ᏹ',
'ᏺ' => 'Ᏺ',
'ᏻ' => '',
'ᏼ' => '',
'ᏽ' => 'Ᏽ',
'ᲀ' => 'В',
'ᲁ' => 'Д',
'ᲂ' => 'О',
'ᲃ' => 'С',
'ᲄ' => 'Т',
'ᲅ' => 'Т',
'ᲆ' => 'Ъ',
'ᲇ' => 'Ѣ',
'ᲈ' => 'Ꙋ',
'ᵹ' => 'Ᵹ',
'ᵽ' => 'Ᵽ',
'ᶎ' => 'Ᶎ',
'ḁ' => 'Ḁ',
'ḃ' => 'Ḃ',
'ḅ' => 'Ḅ',
'ḇ' => 'Ḇ',
'ḉ' => 'Ḉ',
'ḋ' => 'Ḋ',
'ḍ' => 'Ḍ',
'ḏ' => 'Ḏ',
'ḑ' => 'Ḑ',
'ḓ' => 'Ḓ',
'ḕ' => 'Ḕ',
'ḗ' => 'Ḗ',
'ḙ' => 'Ḙ',
'ḛ' => 'Ḛ',
'ḝ' => 'Ḝ',
'ḟ' => 'Ḟ',
'ḡ' => 'Ḡ',
'ḣ' => 'Ḣ',
'ḥ' => 'Ḥ',
'ḧ' => 'Ḧ',
'ḩ' => 'Ḩ',
'ḫ' => 'Ḫ',
'ḭ' => 'Ḭ',
'ḯ' => 'Ḯ',
'ḱ' => 'Ḱ',
'ḳ' => 'Ḳ',
'ḵ' => 'Ḵ',
'ḷ' => 'Ḷ',
'ḹ' => 'Ḹ',
'ḻ' => 'Ḻ',
'ḽ' => 'Ḽ',
'ḿ' => 'Ḿ',
'ṁ' => 'Ṁ',
'ṃ' => 'Ṃ',
'ṅ' => 'Ṅ',
'ṇ' => 'Ṇ',
'ṉ' => 'Ṉ',
'ṋ' => 'Ṋ',
'ṍ' => 'Ṍ',
'ṏ' => 'Ṏ',
'ṑ' => 'Ṑ',
'ṓ' => 'Ṓ',
'ṕ' => 'Ṕ',
'ṗ' => 'Ṗ',
'ṙ' => 'Ṙ',
'ṛ' => 'Ṛ',
'ṝ' => 'Ṝ',
'ṟ' => 'Ṟ',
'ṡ' => 'Ṡ',
'ṣ' => 'Ṣ',
'ṥ' => 'Ṥ',
'ṧ' => 'Ṧ',
'ṩ' => 'Ṩ',
'ṫ' => 'Ṫ',
'ṭ' => 'Ṭ',
'ṯ' => 'Ṯ',
'ṱ' => 'Ṱ',
'ṳ' => 'Ṳ',
'ṵ' => 'Ṵ',
'ṷ' => 'Ṷ',
'ṹ' => 'Ṹ',
'ṻ' => 'Ṻ',
'ṽ' => 'Ṽ',
'ṿ' => 'Ṿ',
'ẁ' => 'Ẁ',
'ẃ' => 'Ẃ',
'ẅ' => 'Ẅ',
'ẇ' => 'Ẇ',
'ẉ' => 'Ẉ',
'ẋ' => 'Ẋ',
'ẍ' => 'Ẍ',
'ẏ' => 'Ẏ',
'ẑ' => 'Ẑ',
'ẓ' => 'Ẓ',
'ẕ' => 'Ẕ',
'ẛ' => 'Ṡ',
'ạ' => 'Ạ',
'ả' => 'Ả',
'ấ' => 'Ấ',
'ầ' => 'Ầ',
'ẩ' => 'Ẩ',
'ẫ' => 'Ẫ',
'ậ' => 'Ậ',
'ắ' => 'Ắ',
'ằ' => 'Ằ',
'ẳ' => 'Ẳ',
'ẵ' => 'Ẵ',
'ặ' => 'Ặ',
'ẹ' => 'Ẹ',
'ẻ' => 'Ẻ',
'ẽ' => 'Ẽ',
'ế' => 'Ế',
'ề' => 'Ề',
'ể' => 'Ể',
'ễ' => 'Ễ',
'ệ' => 'Ệ',
'ỉ' => 'Ỉ',
'ị' => 'Ị',
'ọ' => 'Ọ',
'ỏ' => 'Ỏ',
'ố' => 'Ố',
'ồ' => 'Ồ',
'ổ' => 'Ổ',
'ỗ' => 'Ỗ',
'ộ' => 'Ộ',
'ớ' => 'Ớ',
'ờ' => 'Ờ',
'ở' => 'Ở',
'ỡ' => 'Ỡ',
'ợ' => 'Ợ',
'ụ' => 'Ụ',
'ủ' => 'Ủ',
'ứ' => 'Ứ',
'ừ' => 'Ừ',
'ử' => 'Ử',
'ữ' => 'Ữ',
'ự' => 'Ự',
'ỳ' => 'Ỳ',
'ỵ' => 'Ỵ',
'ỷ' => 'Ỷ',
'ỹ' => 'Ỹ',
'ỻ' => 'Ỻ',
'ỽ' => 'Ỽ',
'ỿ' => 'Ỿ',
'ἀ' => 'Ἀ',
'ἁ' => 'Ἁ',
'ἂ' => 'Ἂ',
'ἃ' => 'Ἃ',
'ἄ' => 'Ἄ',
'ἅ' => 'Ἅ',
'ἆ' => 'Ἆ',
'ἇ' => 'Ἇ',
'ἐ' => 'Ἐ',
'ἑ' => 'Ἑ',
'ἒ' => 'Ἒ',
'ἓ' => 'Ἓ',
'ἔ' => 'Ἔ',
'ἕ' => 'Ἕ',
'ἠ' => 'Ἠ',
'ἡ' => 'Ἡ',
'ἢ' => 'Ἢ',
'ἣ' => 'Ἣ',
'ἤ' => 'Ἤ',
'ἥ' => 'Ἥ',
'ἦ' => 'Ἦ',
'ἧ' => 'Ἧ',
'ἰ' => 'Ἰ',
'ἱ' => 'Ἱ',
'ἲ' => 'Ἲ',
'ἳ' => 'Ἳ',
'ἴ' => 'Ἴ',
'ἵ' => 'Ἵ',
'ἶ' => 'Ἶ',
'ἷ' => 'Ἷ',
'ὀ' => 'Ὀ',
'ὁ' => 'Ὁ',
'ὂ' => 'Ὂ',
'ὃ' => 'Ὃ',
'ὄ' => 'Ὄ',
'ὅ' => 'Ὅ',
'ὑ' => 'Ὑ',
'ὓ' => 'Ὓ',
'ὕ' => 'Ὕ',
'ὗ' => 'Ὗ',
'ὠ' => 'Ὠ',
'ὡ' => 'Ὡ',
'ὢ' => 'Ὢ',
'ὣ' => 'Ὣ',
'ὤ' => 'Ὤ',
'ὥ' => 'Ὥ',
'ὦ' => 'Ὦ',
'ὧ' => 'Ὧ',
'ὰ' => 'Ὰ',
'ά' => 'Ά',
'ὲ' => 'Ὲ',
'έ' => 'Έ',
'ὴ' => 'Ὴ',
'ή' => 'Ή',
'ὶ' => 'Ὶ',
'ί' => 'Ί',
'ὸ' => 'Ὸ',
'ό' => 'Ό',
'ὺ' => 'Ὺ',
'ύ' => 'Ύ',
'ὼ' => 'Ὼ',
'ώ' => 'Ώ',
'ᾀ' => 'ᾈ',
'ᾁ' => 'ᾉ',
'ᾂ' => 'ᾊ',
'ᾃ' => 'ᾋ',
'ᾄ' => 'ᾌ',
'ᾅ' => 'ᾍ',
'ᾆ' => 'ᾎ',
'ᾇ' => 'ᾏ',
'ᾐ' => 'ᾘ',
'ᾑ' => 'ᾙ',
'ᾒ' => 'ᾚ',
'ᾓ' => 'ᾛ',
'ᾔ' => 'ᾜ',
'ᾕ' => 'ᾝ',
'ᾖ' => 'ᾞ',
'ᾗ' => 'ᾟ',
'ᾠ' => 'ᾨ',
'ᾡ' => 'ᾩ',
'ᾢ' => 'ᾪ',
'ᾣ' => 'ᾫ',
'ᾤ' => 'ᾬ',
'ᾥ' => 'ᾭ',
'ᾦ' => 'ᾮ',
'ᾧ' => 'ᾯ',
'ᾰ' => 'Ᾰ',
'ᾱ' => 'Ᾱ',
'ᾳ' => 'ᾼ',
'' => 'Ι',
'ῃ' => 'ῌ',
'ῐ' => 'Ῐ',
'ῑ' => 'Ῑ',
'ῠ' => 'Ῠ',
'ῡ' => 'Ῡ',
'ῥ' => 'Ῥ',
'ῳ' => 'ῼ',
'ⅎ' => 'Ⅎ',
'' => '',
'ⅱ' => 'Ⅱ',
'ⅲ' => 'Ⅲ',
'ⅳ' => 'Ⅳ',
'' => '',
'ⅵ' => 'Ⅵ',
'ⅶ' => 'Ⅶ',
'ⅷ' => 'Ⅷ',
'ⅸ' => 'Ⅸ',
'' => '',
'ⅺ' => 'Ⅺ',
'ⅻ' => 'Ⅻ',
'' => '',
'' => '',
'' => '',
'ⅿ' => '',
'ↄ' => 'Ↄ',
'ⓐ' => 'Ⓐ',
'ⓑ' => 'Ⓑ',
'ⓒ' => 'Ⓒ',
'ⓓ' => 'Ⓓ',
'ⓔ' => 'Ⓔ',
'ⓕ' => 'Ⓕ',
'ⓖ' => 'Ⓖ',
'ⓗ' => 'Ⓗ',
'ⓘ' => 'Ⓘ',
'ⓙ' => 'Ⓙ',
'ⓚ' => 'Ⓚ',
'ⓛ' => 'Ⓛ',
'ⓜ' => 'Ⓜ',
'ⓝ' => 'Ⓝ',
'ⓞ' => 'Ⓞ',
'ⓟ' => 'Ⓟ',
'ⓠ' => 'Ⓠ',
'ⓡ' => 'Ⓡ',
'ⓢ' => 'Ⓢ',
'ⓣ' => 'Ⓣ',
'ⓤ' => 'Ⓤ',
'ⓥ' => 'Ⓥ',
'ⓦ' => 'Ⓦ',
'ⓧ' => 'Ⓧ',
'ⓨ' => 'Ⓨ',
'ⓩ' => 'Ⓩ',
'ⰰ' => 'Ⰰ',
'ⰱ' => 'Ⰱ',
'ⰲ' => 'Ⰲ',
'ⰳ' => 'Ⰳ',
'ⰴ' => 'Ⰴ',
'ⰵ' => 'Ⰵ',
'ⰶ' => 'Ⰶ',
'ⰷ' => 'Ⰷ',
'ⰸ' => 'Ⰸ',
'ⰹ' => 'Ⰹ',
'ⰺ' => 'Ⰺ',
'ⰻ' => 'Ⰻ',
'ⰼ' => 'Ⰼ',
'ⰽ' => 'Ⰽ',
'ⰾ' => 'Ⰾ',
'ⰿ' => 'Ⰿ',
'ⱀ' => 'Ⱀ',
'ⱁ' => 'Ⱁ',
'ⱂ' => 'Ⱂ',
'ⱃ' => 'Ⱃ',
'ⱄ' => 'Ⱄ',
'ⱅ' => 'Ⱅ',
'ⱆ' => 'Ⱆ',
'ⱇ' => 'Ⱇ',
'ⱈ' => 'Ⱈ',
'ⱉ' => 'Ⱉ',
'ⱊ' => 'Ⱊ',
'ⱋ' => 'Ⱋ',
'ⱌ' => 'Ⱌ',
'ⱍ' => 'Ⱍ',
'ⱎ' => 'Ⱎ',
'ⱏ' => 'Ⱏ',
'ⱐ' => 'Ⱐ',
'ⱑ' => 'Ⱑ',
'ⱒ' => 'Ⱒ',
'ⱓ' => 'Ⱓ',
'ⱔ' => 'Ⱔ',
'ⱕ' => 'Ⱕ',
'ⱖ' => 'Ⱖ',
'ⱗ' => 'Ⱗ',
'ⱘ' => 'Ⱘ',
'ⱙ' => 'Ⱙ',
'ⱚ' => 'Ⱚ',
'ⱛ' => 'Ⱛ',
'ⱜ' => 'Ⱜ',
'ⱝ' => 'Ⱝ',
'ⱞ' => 'Ⱞ',
'ⱡ' => 'Ⱡ',
'ⱥ' => 'Ⱥ',
'ⱦ' => 'Ⱦ',
'ⱨ' => 'Ⱨ',
'ⱪ' => 'Ⱪ',
'ⱬ' => 'Ⱬ',
'ⱳ' => 'Ⱳ',
'ⱶ' => 'Ⱶ',
'ⲁ' => 'Ⲁ',
'ⲃ' => 'Ⲃ',
'' => 'Ⲅ',
'ⲇ' => 'Ⲇ',
'ⲉ' => 'Ⲉ',
'ⲋ' => 'Ⲋ',
'ⲍ' => 'Ⲍ',
'ⲏ' => '',
'ⲑ' => 'Ⲑ',
'ⲓ' => '',
'ⲕ' => '',
'ⲗ' => 'Ⲗ',
'ⲙ' => '',
'ⲛ' => '',
'ⲝ' => 'Ⲝ',
'' => '',
'ⲡ' => 'Ⲡ',
'' => '',
'' => '',
'ⲧ' => '',
'ⲩ' => '',
'ⲫ' => 'Ⲫ',
'ⲭ' => '',
'ⲯ' => 'Ⲯ',
'ⲱ' => 'Ⲱ',
'ⲳ' => 'Ⲳ',
'ⲵ' => 'Ⲵ',
'ⲷ' => 'Ⲷ',
'ⲹ' => 'Ⲹ',
'ⲻ' => '',
'ⲽ' => 'Ⲽ',
'ⲿ' => 'Ⲿ',
'ⳁ' => 'Ⳁ',
'ⳃ' => 'Ⳃ',
'ⳅ' => 'Ⳅ',
'ⳇ' => '',
'ⳉ' => 'Ⳉ',
'ⳋ' => '',
'ⳍ' => '',
'ⳏ' => 'Ⳏ',
'ⳑ' => '',
'ⳓ' => '',
'ⳕ' => 'Ⳕ',
'ⳗ' => 'Ⳗ',
'ⳙ' => 'Ⳙ',
'ⳛ' => 'Ⳛ',
'ⳝ' => 'Ⳝ',
'ⳟ' => 'Ⳟ',
'ⳡ' => 'Ⳡ',
'ⳣ' => 'Ⳣ',
'ⳬ' => 'Ⳬ',
'ⳮ' => 'Ⳮ',
'ⳳ' => 'Ⳳ',
'ⴀ' => 'Ⴀ',
'ⴁ' => 'Ⴁ',
'ⴂ' => 'Ⴂ',
'ⴃ' => 'Ⴃ',
'ⴄ' => 'Ⴄ',
'ⴅ' => 'Ⴅ',
'ⴆ' => 'Ⴆ',
'ⴇ' => 'Ⴇ',
'ⴈ' => 'Ⴈ',
'ⴉ' => 'Ⴉ',
'ⴊ' => 'Ⴊ',
'ⴋ' => 'Ⴋ',
'ⴌ' => 'Ⴌ',
'ⴍ' => 'Ⴍ',
'ⴎ' => 'Ⴎ',
'ⴏ' => 'Ⴏ',
'ⴐ' => 'Ⴐ',
'ⴑ' => 'Ⴑ',
'ⴒ' => 'Ⴒ',
'ⴓ' => 'Ⴓ',
'ⴔ' => 'Ⴔ',
'ⴕ' => 'Ⴕ',
'ⴖ' => 'Ⴖ',
'ⴗ' => 'Ⴗ',
'ⴘ' => 'Ⴘ',
'ⴙ' => 'Ⴙ',
'ⴚ' => 'Ⴚ',
'ⴛ' => 'Ⴛ',
'ⴜ' => 'Ⴜ',
'ⴝ' => 'Ⴝ',
'ⴞ' => 'Ⴞ',
'ⴟ' => 'Ⴟ',
'ⴠ' => 'Ⴠ',
'ⴡ' => 'Ⴡ',
'ⴢ' => 'Ⴢ',
'ⴣ' => 'Ⴣ',
'ⴤ' => 'Ⴤ',
'ⴥ' => 'Ⴥ',
'ⴧ' => 'Ⴧ',
'ⴭ' => 'Ⴭ',
'ꙁ' => 'Ꙁ',
'ꙃ' => 'Ꙃ',
'ꙅ' => '',
'' => 'Ꙇ',
'ꙉ' => 'Ꙉ',
'ꙋ' => 'Ꙋ',
'ꙍ' => 'Ꙍ',
'ꙏ' => 'Ꙏ',
'ꙑ' => 'Ꙑ',
'ꙓ' => 'Ꙓ',
'ꙕ' => 'Ꙕ',
'ꙗ' => 'Ꙗ',
'ꙙ' => 'Ꙙ',
'ꙛ' => 'Ꙛ',
'ꙝ' => 'Ꙝ',
'ꙟ' => 'Ꙟ',
'ꙡ' => 'Ꙡ',
'ꙣ' => 'Ꙣ',
'ꙥ' => 'Ꙥ',
'ꙧ' => 'Ꙧ',
'ꙩ' => 'Ꙩ',
'ꙫ' => 'Ꙫ',
'ꙭ' => 'Ꙭ',
'ꚁ' => 'Ꚁ',
'ꚃ' => 'Ꚃ',
'ꚅ' => 'Ꚅ',
'ꚇ' => 'Ꚇ',
'ꚉ' => 'Ꚉ',
'ꚋ' => 'Ꚋ',
'ꚍ' => 'Ꚍ',
'ꚏ' => 'Ꚏ',
'ꚑ' => 'Ꚑ',
'ꚓ' => 'Ꚓ',
'ꚕ' => 'Ꚕ',
'ꚗ' => 'Ꚗ',
'ꚙ' => 'Ꚙ',
'ꚛ' => 'Ꚛ',
'ꜣ' => 'Ꜣ',
'ꜥ' => 'Ꜥ',
'ꜧ' => 'Ꜧ',
'ꜩ' => 'Ꜩ',
'ꜫ' => 'Ꜫ',
'ꜭ' => 'Ꜭ',
'ꜯ' => 'Ꜯ',
'ꜳ' => 'Ꜳ',
'ꜵ' => 'Ꜵ',
'ꜷ' => 'Ꜷ',
'ꜹ' => 'Ꜹ',
'ꜻ' => 'Ꜻ',
'ꜽ' => 'Ꜽ',
'ꜿ' => 'Ꜿ',
'ꝁ' => 'Ꝁ',
'ꝃ' => 'Ꝃ',
'ꝅ' => 'Ꝅ',
'ꝇ' => 'Ꝇ',
'ꝉ' => 'Ꝉ',
'ꝋ' => 'Ꝋ',
'ꝍ' => 'Ꝍ',
'ꝏ' => 'Ꝏ',
'ꝑ' => 'Ꝑ',
'ꝓ' => 'Ꝓ',
'ꝕ' => 'Ꝕ',
'ꝗ' => 'Ꝗ',
'ꝙ' => 'Ꝙ',
'ꝛ' => '',
'ꝝ' => 'Ꝝ',
'ꝟ' => 'Ꝟ',
'ꝡ' => 'Ꝡ',
'ꝣ' => 'Ꝣ',
'ꝥ' => 'Ꝥ',
'ꝧ' => 'Ꝧ',
'ꝩ' => 'Ꝩ',
'ꝫ' => '',
'ꝭ' => 'Ꝭ',
'ꝯ' => '',
'ꝺ' => 'Ꝺ',
'ꝼ' => 'Ꝼ',
'ꝿ' => 'Ꝿ',
'ꞁ' => 'Ꞁ',
'ꞃ' => 'Ꞃ',
'ꞅ' => 'Ꞅ',
'ꞇ' => 'Ꞇ',
'' => 'Ꞌ',
'ꞑ' => 'Ꞑ',
'ꞓ' => 'Ꞓ',
'ꞔ' => 'Ꞔ',
'ꞗ' => 'Ꞗ',
'' => '',
'ꞛ' => 'Ꞛ',
'ꞝ' => 'Ꞝ',
'' => 'Ꞟ',
'ꞡ' => 'Ꞡ',
'ꞣ' => 'Ꞣ',
'ꞥ' => 'Ꞥ',
'ꞧ' => 'Ꞧ',
'ꞩ' => 'Ꞩ',
'ꞵ' => '',
'ꞷ' => 'Ꞷ',
'ꞹ' => 'Ꞹ',
'ꞻ' => 'Ꞻ',
'ꞽ' => 'Ꞽ',
'ꞿ' => 'Ꞿ',
'ꟃ' => 'Ꟃ',
'ꟈ' => 'Ꟈ',
'ꟊ' => 'Ꟊ',
'ꟶ' => 'Ꟶ',
'ꭓ' => '',
'ꭰ' => '',
'ꭱ' => '',
'ꭲ' => '',
'ꭳ' => 'Ꭳ',
'ꭴ' => 'Ꭴ',
'' => '',
'ꭶ' => 'Ꭶ',
'ꭷ' => 'Ꭷ',
'ꭸ' => 'Ꭸ',
'ꭹ' => '',
'ꭺ' => '',
'ꭻ' => '',
'ꭼ' => '',
'ꭽ' => 'Ꭽ',
'ꭾ' => '',
'ꭿ' => 'Ꭿ',
'ꮀ' => 'Ꮀ',
'' => 'Ꮁ',
'ꮂ' => 'Ꮂ',
'' => '',
'ꮄ' => 'Ꮄ',
'ꮅ' => 'Ꮅ',
'ꮆ' => 'Ꮆ',
'ꮇ' => '',
'ꮈ' => 'Ꮈ',
'ꮉ' => 'Ꮉ',
'ꮊ' => 'Ꮊ',
'ꮋ' => '',
'ꮌ' => 'Ꮌ',
'ꮍ' => '',
'ꮎ' => 'Ꮎ',
'ꮏ' => 'Ꮏ',
'ꮐ' => '',
'ꮑ' => 'Ꮑ',
'ꮒ' => '',
'' => '',
'ꮔ' => 'Ꮔ',
'ꮕ' => 'Ꮕ',
'ꮖ' => 'Ꮖ',
'ꮗ' => 'Ꮗ',
'ꮘ' => 'Ꮘ',
'ꮙ' => 'Ꮙ',
'ꮚ' => 'Ꮚ',
'ꮛ' => 'Ꮛ',
'ꮜ' => 'Ꮜ',
'ꮝ' => 'Ꮝ',
'ꮞ' => '',
'ꮟ' => '',
'ꮠ' => 'Ꮠ',
'ꮡ' => 'Ꮡ',
'ꮢ' => '',
'ꮣ' => 'Ꮣ',
'ꮤ' => '',
'ꮥ' => '',
'ꮦ' => 'Ꮦ',
'ꮧ' => 'Ꮧ',
'ꮨ' => 'Ꮨ',
'' => '',
'' => '',
'ꮫ' => 'Ꮫ',
'ꮬ' => 'Ꮬ',
'ꮭ' => 'Ꮭ',
'ꮮ' => '',
'' => '',
'ꮰ' => 'Ꮰ',
'ꮱ' => 'Ꮱ',
'ꮲ' => '',
'ꮳ' => 'Ꮳ',
'ꮴ' => 'Ꮴ',
'ꮵ' => 'Ꮵ',
'ꮶ' => '',
'ꮷ' => '',
'ꮸ' => 'Ꮸ',
'ꮹ' => 'Ꮹ',
'ꮺ' => 'Ꮺ',
'ꮻ' => 'Ꮻ',
'ꮼ' => 'Ꮼ',
'ꮽ' => 'Ꮽ',
'ꮾ' => '',
'ꮿ' => 'Ꮿ',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'𐐨' => '𐐀',
'𐐩' => '𐐁',
'𐐪' => '𐐂',
'𐐫' => '𐐃',
'𐐬' => '𐐄',
'𐐭' => '𐐅',
'𐐮' => '𐐆',
'𐐯' => '𐐇',
'𐐰' => '𐐈',
'𐐱' => '𐐉',
'𐐲' => '𐐊',
'𐐳' => '𐐋',
'𐐴' => '𐐌',
'𐐵' => '𐐍',
'𐐶' => '𐐎',
'𐐷' => '𐐏',
'𐐸' => '𐐐',
'𐐹' => '𐐑',
'𐐺' => '𐐒',
'𐐻' => '𐐓',
'𐐼' => '𐐔',
'𐐽' => '𐐕',
'𐐾' => '𐐖',
'𐐿' => '𐐗',
'𐑀' => '𐐘',
'𐑁' => '𐐙',
'𐑂' => '𐐚',
'𐑃' => '𐐛',
'𐑄' => '𐐜',
'𐑅' => '𐐝',
'𐑆' => '𐐞',
'𐑇' => '𐐟',
'𐑈' => '𐐠',
'𐑉' => '𐐡',
'𐑊' => '𐐢',
'𐑋' => '𐐣',
'𐑌' => '𐐤',
'𐑍' => '𐐥',
'𐑎' => '𐐦',
'𐑏' => '𐐧',
'𐓘' => '𐒰',
'𐓙' => '𐒱',
'𐓚' => '𐒲',
'𐓛' => '𐒳',
'𐓜' => '𐒴',
'𐓝' => '𐒵',
'𐓞' => '𐒶',
'𐓟' => '𐒷',
'𐓠' => '𐒸',
'𐓡' => '𐒹',
'𐓢' => '𐒺',
'𐓣' => '𐒻',
'𐓤' => '𐒼',
'𐓥' => '𐒽',
'𐓦' => '𐒾',
'𐓧' => '𐒿',
'𐓨' => '𐓀',
'𐓩' => '𐓁',
'𐓪' => '𐓂',
'𐓫' => '𐓃',
'𐓬' => '𐓄',
'𐓭' => '𐓅',
'𐓮' => '𐓆',
'𐓯' => '𐓇',
'𐓰' => '𐓈',
'𐓱' => '𐓉',
'𐓲' => '𐓊',
'𐓳' => '𐓋',
'𐓴' => '𐓌',
'𐓵' => '𐓍',
'𐓶' => '𐓎',
'𐓷' => '𐓏',
'𐓸' => '𐓐',
'𐓹' => '𐓑',
'𐓺' => '𐓒',
'𐓻' => '𐓓',
'𐳀' => '𐲀',
'𐳁' => '𐲁',
'𐳂' => '𐲂',
'𐳃' => '𐲃',
'𐳄' => '𐲄',
'𐳅' => '𐲅',
'𐳆' => '𐲆',
'𐳇' => '𐲇',
'𐳈' => '𐲈',
'𐳉' => '𐲉',
'𐳊' => '𐲊',
'𐳋' => '𐲋',
'𐳌' => '𐲌',
'𐳍' => '𐲍',
'𐳎' => '𐲎',
'𐳏' => '𐲏',
'𐳐' => '𐲐',
'𐳑' => '𐲑',
'𐳒' => '𐲒',
'𐳓' => '𐲓',
'𐳔' => '𐲔',
'𐳕' => '𐲕',
'𐳖' => '𐲖',
'𐳗' => '𐲗',
'𐳘' => '𐲘',
'𐳙' => '𐲙',
'𐳚' => '𐲚',
'𐳛' => '𐲛',
'𐳜' => '𐲜',
'𐳝' => '𐲝',
'𐳞' => '𐲞',
'𐳟' => '𐲟',
'𐳠' => '𐲠',
'𐳡' => '𐲡',
'𐳢' => '𐲢',
'𐳣' => '𐲣',
'𐳤' => '𐲤',
'𐳥' => '𐲥',
'𐳦' => '𐲦',
'𐳧' => '𐲧',
'𐳨' => '𐲨',
'𐳩' => '𐲩',
'𐳪' => '𐲪',
'𐳫' => '𐲫',
'𐳬' => '𐲬',
'𐳭' => '𐲭',
'𐳮' => '𐲮',
'𐳯' => '𐲯',
'𐳰' => '𐲰',
'𐳱' => '𐲱',
'𐳲' => '𐲲',
'𑣀' => '𑢠',
'𑣁' => '𑢡',
'𑣂' => '𑢢',
'𑣃' => '𑢣',
'𑣄' => '𑢤',
'𑣅' => '𑢥',
'𑣆' => '𑢦',
'𑣇' => '𑢧',
'𑣈' => '𑢨',
'𑣉' => '𑢩',
'𑣊' => '𑢪',
'𑣋' => '𑢫',
'𑣌' => '𑢬',
'𑣍' => '𑢭',
'𑣎' => '𑢮',
'𑣏' => '𑢯',
'𑣐' => '𑢰',
'𑣑' => '𑢱',
'𑣒' => '𑢲',
'𑣓' => '𑢳',
'𑣔' => '𑢴',
'𑣕' => '𑢵',
'𑣖' => '𑢶',
'𑣗' => '𑢷',
'𑣘' => '𑢸',
'𑣙' => '𑢹',
'𑣚' => '𑢺',
'𑣛' => '𑢻',
'𑣜' => '𑢼',
'𑣝' => '𑢽',
'𑣞' => '𑢾',
'𑣟' => '𑢿',
'𖹠' => '𖹀',
'𖹡' => '𖹁',
'𖹢' => '𖹂',
'𖹣' => '𖹃',
'𖹤' => '𖹄',
'𖹥' => '𖹅',
'𖹦' => '𖹆',
'𖹧' => '𖹇',
'𖹨' => '𖹈',
'𖹩' => '𖹉',
'𖹪' => '𖹊',
'𖹫' => '𖹋',
'𖹬' => '𖹌',
'𖹭' => '𖹍',
'𖹮' => '𖹎',
'𖹯' => '𖹏',
'𖹰' => '𖹐',
'𖹱' => '𖹑',
'𖹲' => '𖹒',
'𖹳' => '𖹓',
'𖹴' => '𖹔',
'𖹵' => '𖹕',
'𖹶' => '𖹖',
'𖹷' => '𖹗',
'𖹸' => '𖹘',
'𖹹' => '𖹙',
'𖹺' => '𖹚',
'𖹻' => '𖹛',
'𖹼' => '𖹜',
'𖹽' => '𖹝',
'𖹾' => '𖹞',
'𖹿' => '𖹟',
'𞤢' => '𞤀',
'𞤣' => '𞤁',
'𞤤' => '𞤂',
'𞤥' => '𞤃',
'𞤦' => '𞤄',
'𞤧' => '𞤅',
'𞤨' => '𞤆',
'𞤩' => '𞤇',
'𞤪' => '𞤈',
'𞤫' => '𞤉',
'𞤬' => '𞤊',
'𞤭' => '𞤋',
'𞤮' => '𞤌',
'𞤯' => '𞤍',
'𞤰' => '𞤎',
'𞤱' => '𞤏',
'𞤲' => '𞤐',
'𞤳' => '𞤑',
'𞤴' => '𞤒',
'𞤵' => '𞤓',
'𞤶' => '𞤔',
'𞤷' => '𞤕',
'𞤸' => '𞤖',
'𞤹' => '𞤗',
'𞤺' => '𞤘',
'𞤻' => '𞤙',
'𞤼' => '𞤚',
'𞤽' => '𞤛',
'𞤾' => '𞤜',
'𞤿' => '𞤝',
'𞥀' => '𞤞',
'𞥁' => '𞤟',
'𞥂' => '𞤠',
'𞥃' => '𞤡',
);
<?php
return '/(?<![\x{0027}\x{002E}\x{003A}\x{005E}\x{0060}\x{00A8}\x{00AD}\x{00AF}\x{00B4}\x{00B7}\x{00B8}\x{02B0}-\x{02C1}\x{02C2}-\x{02C5}\x{02C6}-\x{02D1}\x{02D2}-\x{02DF}\x{02E0}-\x{02E4}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EE}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037A}\x{0384}-\x{0385}\x{0387}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0559}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{05F4}\x{0600}-\x{0605}\x{0610}-\x{061A}\x{061C}\x{0640}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DD}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{070F}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07FA}\x{07FD}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0971}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CBF}\x{0CC6}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E46}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EB9}\x{0EBB}-\x{0EBC}\x{0EC6}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{10FC}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17D7}\x{17DD}\x{180B}-\x{180D}\x{180E}\x{1843}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AA7}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1C78}-\x{1C7D}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1D2C}-\x{1D6A}\x{1D78}\x{1D9B}-\x{1DBF}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{200B}-\x{200F}\x{2018}\x{2019}\x{2024}\x{2027}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{2066}-\x{206F}\x{2071}\x{207F}\x{2090}-\x{209C}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2C7C}-\x{2C7D}\x{2CEF}-\x{2CF1}\x{2D6F}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E2F}\x{3005}\x{302A}-\x{302D}\x{3031}-\x{3035}\x{303B}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{309D}-\x{309E}\x{30FC}-\x{30FE}\x{A015}\x{A4F8}-\x{A4FD}\x{A60C}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A67F}\x{A69C}-\x{A69D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A770}\x{A788}\x{A789}-\x{A78A}\x{A7F8}-\x{A7F9}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}\x{A9CF}\x{A9E5}\x{A9E6}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA70}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AADD}\x{AAEC}-\x{AAED}\x{AAF3}-\x{AAF4}\x{AAF6}\x{AB5B}\x{AB5C}-\x{AB5F}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FBB2}-\x{FBC1}\x{FE00}-\x{FE0F}\x{FE13}\x{FE20}-\x{FE2F}\x{FE52}\x{FE55}\x{FEFF}\x{FF07}\x{FF0E}\x{FF1A}\x{FF3E}\x{FF40}\x{FF70}\x{FF9E}-\x{FF9F}\x{FFE3}\x{FFF9}-\x{FFFB}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{110BD}\x{110CD}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16B40}-\x{16B43}\x{16F8F}-\x{16F92}\x{16F93}-\x{16F9F}\x{16FE0}-\x{16FE1}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{1F3FB}-\x{1F3FF}\x{E0001}\x{E0020}-\x{E007F}\x{E0100}-\x{E01EF}])(\pL)(\pL*+)/u';
<?php
return array (
'A' => 'a',
'B' => 'b',
'C' => 'c',
'D' => 'd',
'E' => 'e',
'F' => 'f',
'G' => 'g',
'H' => 'h',
'I' => 'i',
'J' => 'j',
'K' => 'k',
'L' => 'l',
'M' => 'm',
'N' => 'n',
'O' => 'o',
'P' => 'p',
'Q' => 'q',
'R' => 'r',
'S' => 's',
'T' => 't',
'U' => 'u',
'V' => 'v',
'W' => 'w',
'X' => 'x',
'Y' => 'y',
'Z' => 'z',
'À' => 'à',
'Á' => 'á',
'Â' => 'â',
'Ã' => 'ã',
'Ä' => 'ä',
'Å' => 'å',
'Æ' => 'æ',
'Ç' => 'ç',
'È' => 'è',
'É' => 'é',
'Ê' => 'ê',
'Ë' => 'ë',
'Ì' => 'ì',
'Í' => 'í',
'Î' => 'î',
'Ï' => 'ï',
'Ð' => 'ð',
'Ñ' => 'ñ',
'Ò' => 'ò',
'Ó' => 'ó',
'Ô' => 'ô',
'Õ' => 'õ',
'Ö' => 'ö',
'Ø' => 'ø',
'Ù' => 'ù',
'Ú' => 'ú',
'Û' => 'û',
'Ü' => 'ü',
'Ý' => 'ý',
'Þ' => 'þ',
'Ā' => 'ā',
'Ă' => 'ă',
'Ą' => 'ą',
'Ć' => 'ć',
'Ĉ' => 'ĉ',
'Ċ' => 'ċ',
'Č' => 'č',
'Ď' => 'ď',
'Đ' => 'đ',
'Ē' => 'ē',
'Ĕ' => 'ĕ',
'Ė' => 'ė',
'Ę' => 'ę',
'Ě' => 'ě',
'Ĝ' => 'ĝ',
'Ğ' => 'ğ',
'Ġ' => 'ġ',
'Ģ' => 'ģ',
'Ĥ' => 'ĥ',
'Ħ' => 'ħ',
'Ĩ' => 'ĩ',
'Ī' => 'ī',
'Ĭ' => 'ĭ',
'Į' => 'į',
'İ' => 'i',
'IJ' => 'ij',
'Ĵ' => 'ĵ',
'Ķ' => 'ķ',
'Ĺ' => 'ĺ',
'Ļ' => 'ļ',
'Ľ' => 'ľ',
'Ŀ' => 'ŀ',
'Ł' => 'ł',
'Ń' => 'ń',
'Ņ' => 'ņ',
'Ň' => 'ň',
'Ŋ' => 'ŋ',
'Ō' => 'ō',
'Ŏ' => 'ŏ',
'Ő' => 'ő',
'Œ' => 'œ',
'Ŕ' => 'ŕ',
'Ŗ' => 'ŗ',
'Ř' => 'ř',
'Ś' => 'ś',
'Ŝ' => 'ŝ',
'Ş' => 'ş',
'Š' => 'š',
'Ţ' => 'ţ',
'Ť' => 'ť',
'Ŧ' => 'ŧ',
'Ũ' => 'ũ',
'Ū' => 'ū',
'Ŭ' => 'ŭ',
'Ů' => 'ů',
'Ű' => 'ű',
'Ų' => 'ų',
'Ŵ' => 'ŵ',
'Ŷ' => 'ŷ',
'Ÿ' => 'ÿ',
'Ź' => 'ź',
'Ż' => 'ż',
'Ž' => 'ž',
'Ɓ' => 'ɓ',
'Ƃ' => 'ƃ',
'Ƅ' => 'ƅ',
'Ɔ' => 'ɔ',
'Ƈ' => 'ƈ',
'Ɖ' => 'ɖ',
'Ɗ' => 'ɗ',
'Ƌ' => 'ƌ',
'Ǝ' => 'ǝ',
'Ə' => 'ə',
'Ɛ' => 'ɛ',
'Ƒ' => 'ƒ',
'Ɠ' => 'ɠ',
'Ɣ' => 'ɣ',
'Ɩ' => 'ɩ',
'Ɨ' => 'ɨ',
'Ƙ' => 'ƙ',
'Ɯ' => 'ɯ',
'Ɲ' => 'ɲ',
'Ɵ' => 'ɵ',
'Ơ' => 'ơ',
'Ƣ' => 'ƣ',
'Ƥ' => 'ƥ',
'Ʀ' => 'ʀ',
'Ƨ' => 'ƨ',
'Ʃ' => 'ʃ',
'Ƭ' => 'ƭ',
'Ʈ' => 'ʈ',
'Ư' => 'ư',
'Ʊ' => 'ʊ',
'Ʋ' => 'ʋ',
'Ƴ' => 'ƴ',
'Ƶ' => 'ƶ',
'Ʒ' => 'ʒ',
'Ƹ' => 'ƹ',
'Ƽ' => 'ƽ',
'DŽ' => 'dž',
'Dž' => 'dž',
'LJ' => 'lj',
'Lj' => 'lj',
'NJ' => 'nj',
'Nj' => 'nj',
'Ǎ' => 'ǎ',
'Ǐ' => 'ǐ',
'Ǒ' => 'ǒ',
'Ǔ' => 'ǔ',
'Ǖ' => 'ǖ',
'Ǘ' => 'ǘ',
'Ǚ' => 'ǚ',
'Ǜ' => 'ǜ',
'Ǟ' => 'ǟ',
'Ǡ' => 'ǡ',
'Ǣ' => 'ǣ',
'Ǥ' => 'ǥ',
'Ǧ' => 'ǧ',
'Ǩ' => 'ǩ',
'Ǫ' => 'ǫ',
'Ǭ' => 'ǭ',
'Ǯ' => 'ǯ',
'DZ' => 'dz',
'Dz' => 'dz',
'Ǵ' => 'ǵ',
'Ƕ' => 'ƕ',
'Ƿ' => 'ƿ',
'Ǹ' => 'ǹ',
'Ǻ' => 'ǻ',
'Ǽ' => 'ǽ',
'Ǿ' => 'ǿ',
'Ȁ' => 'ȁ',
'Ȃ' => 'ȃ',
'Ȅ' => 'ȅ',
'Ȇ' => 'ȇ',
'Ȉ' => 'ȉ',
'Ȋ' => 'ȋ',
'Ȍ' => 'ȍ',
'Ȏ' => 'ȏ',
'Ȑ' => 'ȑ',
'Ȓ' => 'ȓ',
'Ȕ' => 'ȕ',
'Ȗ' => 'ȗ',
'Ș' => 'ș',
'Ț' => 'ț',
'Ȝ' => 'ȝ',
'Ȟ' => 'ȟ',
'Ƞ' => 'ƞ',
'Ȣ' => 'ȣ',
'Ȥ' => 'ȥ',
'Ȧ' => 'ȧ',
'Ȩ' => 'ȩ',
'Ȫ' => 'ȫ',
'Ȭ' => 'ȭ',
'Ȯ' => 'ȯ',
'Ȱ' => 'ȱ',
'Ȳ' => 'ȳ',
'Ⱥ' => 'ⱥ',
'Ȼ' => 'ȼ',
'Ƚ' => 'ƚ',
'Ⱦ' => 'ⱦ',
'Ɂ' => 'ɂ',
'Ƀ' => 'ƀ',
'Ʉ' => 'ʉ',
'Ʌ' => 'ʌ',
'Ɇ' => 'ɇ',
'Ɉ' => 'ɉ',
'Ɋ' => 'ɋ',
'Ɍ' => 'ɍ',
'Ɏ' => 'ɏ',
'Ͱ' => 'ͱ',
'Ͳ' => 'ͳ',
'Ͷ' => 'ͷ',
'Ϳ' => 'ϳ',
'Ά' => 'ά',
'Έ' => 'έ',
'Ή' => 'ή',
'Ί' => 'ί',
'Ό' => 'ό',
'Ύ' => 'ύ',
'Ώ' => 'ώ',
'Α' => 'α',
'Β' => 'β',
'Γ' => 'γ',
'Δ' => 'δ',
'Ε' => 'ε',
'Ζ' => 'ζ',
'Η' => 'η',
'Θ' => 'θ',
'Ι' => 'ι',
'Κ' => 'κ',
'Λ' => 'λ',
'Μ' => 'μ',
'Ν' => 'ν',
'Ξ' => 'ξ',
'Ο' => 'ο',
'Π' => 'π',
'Ρ' => 'ρ',
'Σ' => 'σ',
'Τ' => 'τ',
'Υ' => 'υ',
'Φ' => 'φ',
'Χ' => 'χ',
'Ψ' => 'ψ',
'Ω' => 'ω',
'Ϊ' => 'ϊ',
'Ϋ' => 'ϋ',
'Ϗ' => 'ϗ',
'Ϙ' => 'ϙ',
'Ϛ' => 'ϛ',
'Ϝ' => 'ϝ',
'Ϟ' => 'ϟ',
'Ϡ' => 'ϡ',
'Ϣ' => 'ϣ',
'Ϥ' => 'ϥ',
'Ϧ' => 'ϧ',
'Ϩ' => 'ϩ',
'Ϫ' => 'ϫ',
'Ϭ' => 'ϭ',
'Ϯ' => 'ϯ',
'ϴ' => 'θ',
'Ϸ' => 'ϸ',
'Ϲ' => 'ϲ',
'Ϻ' => 'ϻ',
'Ͻ' => 'ͻ',
'Ͼ' => 'ͼ',
'Ͽ' => 'ͽ',
'Ѐ' => 'ѐ',
'Ё' => 'ё',
'Ђ' => 'ђ',
'Ѓ' => 'ѓ',
'Є' => 'є',
'Ѕ' => 'ѕ',
'І' => 'і',
'Ї' => 'ї',
'Ј' => 'ј',
'Љ' => 'љ',
'Њ' => 'њ',
'Ћ' => 'ћ',
'Ќ' => 'ќ',
'Ѝ' => 'ѝ',
'Ў' => 'ў',
'Џ' => 'џ',
'А' => 'а',
'Б' => 'б',
'В' => 'в',
'Г' => 'г',
'Д' => 'д',
'Е' => 'е',
'Ж' => 'ж',
'З' => 'з',
'И' => 'и',
'Й' => 'й',
'К' => 'к',
'Л' => 'л',
'М' => 'м',
'Н' => 'н',
'О' => 'о',
'П' => 'п',
'Р' => 'р',
'С' => 'с',
'Т' => 'т',
'У' => 'у',
'Ф' => 'ф',
'Х' => 'х',
'Ц' => 'ц',
'Ч' => 'ч',
'Ш' => 'ш',
'Щ' => 'щ',
'Ъ' => 'ъ',
'Ы' => 'ы',
'Ь' => 'ь',
'Э' => 'э',
'Ю' => 'ю',
'Я' => 'я',
'Ѡ' => 'ѡ',
'Ѣ' => 'ѣ',
'Ѥ' => 'ѥ',
'Ѧ' => 'ѧ',
'Ѩ' => 'ѩ',
'Ѫ' => 'ѫ',
'Ѭ' => 'ѭ',
'Ѯ' => 'ѯ',
'Ѱ' => 'ѱ',
'Ѳ' => 'ѳ',
'Ѵ' => 'ѵ',
'Ѷ' => 'ѷ',
'Ѹ' => 'ѹ',
'Ѻ' => 'ѻ',
'Ѽ' => 'ѽ',
'Ѿ' => 'ѿ',
'Ҁ' => 'ҁ',
'Ҋ' => 'ҋ',
'Ҍ' => 'ҍ',
'Ҏ' => 'ҏ',
'Ґ' => 'ґ',
'Ғ' => 'ғ',
'Ҕ' => 'ҕ',
'Җ' => 'җ',
'Ҙ' => 'ҙ',
'Қ' => 'қ',
'Ҝ' => 'ҝ',
'Ҟ' => 'ҟ',
'Ҡ' => 'ҡ',
'Ң' => 'ң',
'Ҥ' => 'ҥ',
'Ҧ' => 'ҧ',
'Ҩ' => 'ҩ',
'Ҫ' => 'ҫ',
'Ҭ' => 'ҭ',
'Ү' => 'ү',
'Ұ' => 'ұ',
'Ҳ' => 'ҳ',
'Ҵ' => 'ҵ',
'Ҷ' => 'ҷ',
'Ҹ' => 'ҹ',
'Һ' => 'һ',
'Ҽ' => 'ҽ',
'Ҿ' => 'ҿ',
'Ӏ' => 'ӏ',
'Ӂ' => 'ӂ',
'Ӄ' => 'ӄ',
'Ӆ' => 'ӆ',
'Ӈ' => 'ӈ',
'Ӊ' => 'ӊ',
'Ӌ' => 'ӌ',
'Ӎ' => 'ӎ',
'Ӑ' => 'ӑ',
'Ӓ' => 'ӓ',
'Ӕ' => 'ӕ',
'Ӗ' => 'ӗ',
'Ә' => 'ә',
'Ӛ' => 'ӛ',
'Ӝ' => 'ӝ',
'Ӟ' => 'ӟ',
'Ӡ' => 'ӡ',
'Ӣ' => 'ӣ',
'Ӥ' => 'ӥ',
'Ӧ' => 'ӧ',
'Ө' => 'ө',
'Ӫ' => 'ӫ',
'Ӭ' => 'ӭ',
'Ӯ' => 'ӯ',
'Ӱ' => 'ӱ',
'Ӳ' => 'ӳ',
'Ӵ' => 'ӵ',
'Ӷ' => 'ӷ',
'Ӹ' => 'ӹ',
'Ӻ' => 'ӻ',
'Ӽ' => 'ӽ',
'Ӿ' => 'ӿ',
'Ԁ' => 'ԁ',
'Ԃ' => 'ԃ',
'Ԅ' => 'ԅ',
'Ԇ' => 'ԇ',
'Ԉ' => 'ԉ',
'Ԋ' => 'ԋ',
'Ԍ' => 'ԍ',
'Ԏ' => 'ԏ',
'Ԑ' => 'ԑ',
'Ԓ' => 'ԓ',
'Ԕ' => 'ԕ',
'Ԗ' => 'ԗ',
'Ԙ' => 'ԙ',
'Ԛ' => 'ԛ',
'Ԝ' => 'ԝ',
'Ԟ' => 'ԟ',
'Ԡ' => 'ԡ',
'Ԣ' => 'ԣ',
'Ԥ' => 'ԥ',
'Ԧ' => 'ԧ',
'Ԩ' => 'ԩ',
'Ԫ' => 'ԫ',
'Ԭ' => 'ԭ',
'Ԯ' => 'ԯ',
'Ա' => 'ա',
'Բ' => 'բ',
'Գ' => 'գ',
'Դ' => 'դ',
'Ե' => 'ե',
'Զ' => 'զ',
'Է' => 'է',
'Ը' => 'ը',
'Թ' => 'թ',
'Ժ' => 'ժ',
'Ի' => 'ի',
'Լ' => 'լ',
'Խ' => 'խ',
'Ծ' => 'ծ',
'Կ' => 'կ',
'Հ' => 'հ',
'Ձ' => 'ձ',
'Ղ' => 'ղ',
'Ճ' => 'ճ',
'Մ' => 'մ',
'Յ' => 'յ',
'Ն' => 'ն',
'Շ' => 'շ',
'Ո' => 'ո',
'Չ' => 'չ',
'Պ' => 'պ',
'Ջ' => 'ջ',
'Ռ' => 'ռ',
'Ս' => 'ս',
'Վ' => 'վ',
'Տ' => 'տ',
'Ր' => 'ր',
'Ց' => 'ց',
'Ւ' => 'ւ',
'Փ' => 'փ',
'Ք' => 'ք',
'Օ' => 'օ',
'Ֆ' => 'ֆ',
'Ⴀ' => 'ⴀ',
'Ⴁ' => 'ⴁ',
'Ⴂ' => 'ⴂ',
'Ⴃ' => 'ⴃ',
'Ⴄ' => 'ⴄ',
'Ⴅ' => 'ⴅ',
'Ⴆ' => 'ⴆ',
'Ⴇ' => 'ⴇ',
'Ⴈ' => 'ⴈ',
'Ⴉ' => 'ⴉ',
'Ⴊ' => 'ⴊ',
'Ⴋ' => 'ⴋ',
'Ⴌ' => 'ⴌ',
'Ⴍ' => 'ⴍ',
'Ⴎ' => 'ⴎ',
'Ⴏ' => 'ⴏ',
'Ⴐ' => 'ⴐ',
'Ⴑ' => 'ⴑ',
'Ⴒ' => 'ⴒ',
'Ⴓ' => 'ⴓ',
'Ⴔ' => 'ⴔ',
'Ⴕ' => 'ⴕ',
'Ⴖ' => 'ⴖ',
'Ⴗ' => 'ⴗ',
'Ⴘ' => 'ⴘ',
'Ⴙ' => 'ⴙ',
'Ⴚ' => 'ⴚ',
'Ⴛ' => 'ⴛ',
'Ⴜ' => 'ⴜ',
'Ⴝ' => 'ⴝ',
'Ⴞ' => 'ⴞ',
'Ⴟ' => 'ⴟ',
'Ⴠ' => 'ⴠ',
'Ⴡ' => 'ⴡ',
'Ⴢ' => 'ⴢ',
'Ⴣ' => 'ⴣ',
'Ⴤ' => 'ⴤ',
'Ⴥ' => 'ⴥ',
'Ⴧ' => 'ⴧ',
'Ⴭ' => 'ⴭ',
'' => 'ꭰ',
'' => 'ꭱ',
'' => 'ꭲ',
'Ꭳ' => 'ꭳ',
'Ꭴ' => 'ꭴ',
'' => '',
'Ꭶ' => 'ꭶ',
'Ꭷ' => 'ꭷ',
'Ꭸ' => 'ꭸ',
'' => 'ꭹ',
'' => 'ꭺ',
'' => 'ꭻ',
'' => 'ꭼ',
'Ꭽ' => 'ꭽ',
'' => 'ꭾ',
'Ꭿ' => 'ꭿ',
'Ꮀ' => 'ꮀ',
'Ꮁ' => '',
'Ꮂ' => 'ꮂ',
'' => '',
'Ꮄ' => 'ꮄ',
'Ꮅ' => 'ꮅ',
'Ꮆ' => 'ꮆ',
'' => 'ꮇ',
'Ꮈ' => 'ꮈ',
'Ꮉ' => 'ꮉ',
'Ꮊ' => 'ꮊ',
'' => 'ꮋ',
'Ꮌ' => 'ꮌ',
'' => 'ꮍ',
'Ꮎ' => 'ꮎ',
'Ꮏ' => 'ꮏ',
'' => 'ꮐ',
'Ꮑ' => 'ꮑ',
'' => 'ꮒ',
'' => '',
'Ꮔ' => 'ꮔ',
'Ꮕ' => 'ꮕ',
'Ꮖ' => 'ꮖ',
'Ꮗ' => 'ꮗ',
'Ꮘ' => 'ꮘ',
'Ꮙ' => 'ꮙ',
'Ꮚ' => 'ꮚ',
'Ꮛ' => 'ꮛ',
'Ꮜ' => 'ꮜ',
'Ꮝ' => 'ꮝ',
'' => 'ꮞ',
'' => 'ꮟ',
'Ꮠ' => 'ꮠ',
'Ꮡ' => 'ꮡ',
'' => 'ꮢ',
'Ꮣ' => 'ꮣ',
'' => 'ꮤ',
'' => 'ꮥ',
'Ꮦ' => 'ꮦ',
'Ꮧ' => 'ꮧ',
'Ꮨ' => 'ꮨ',
'' => '',
'' => '',
'Ꮫ' => 'ꮫ',
'Ꮬ' => 'ꮬ',
'Ꮭ' => 'ꮭ',
'' => 'ꮮ',
'' => '',
'Ꮰ' => 'ꮰ',
'Ꮱ' => 'ꮱ',
'' => 'ꮲ',
'Ꮳ' => 'ꮳ',
'Ꮴ' => 'ꮴ',
'Ꮵ' => 'ꮵ',
'' => 'ꮶ',
'' => 'ꮷ',
'Ꮸ' => 'ꮸ',
'Ꮹ' => 'ꮹ',
'Ꮺ' => 'ꮺ',
'Ꮻ' => 'ꮻ',
'Ꮼ' => 'ꮼ',
'Ꮽ' => 'ꮽ',
'' => 'ꮾ',
'Ꮿ' => 'ꮿ',
'Ᏸ' => 'ᏸ',
'Ᏹ' => 'ᏹ',
'Ᏺ' => 'ᏺ',
'' => 'ᏻ',
'' => 'ᏼ',
'Ᏽ' => 'ᏽ',
'Ა' => 'ა',
'Ბ' => 'ბ',
'Გ' => 'გ',
'Დ' => 'დ',
'Ე' => 'ე',
'Ვ' => 'ვ',
'Ზ' => 'ზ',
'Თ' => 'თ',
'Ი' => 'ი',
'Კ' => 'კ',
'Ლ' => 'ლ',
'Მ' => 'მ',
'Ნ' => 'ნ',
'Ო' => 'ო',
'Პ' => 'პ',
'Ჟ' => 'ჟ',
'Რ' => 'რ',
'Ს' => 'ს',
'Ტ' => 'ტ',
'Უ' => 'უ',
'Ფ' => 'ფ',
'Ქ' => 'ქ',
'Ღ' => 'ღ',
'Ყ' => '',
'Შ' => 'შ',
'Ჩ' => 'ჩ',
'Ც' => 'ც',
'Ძ' => 'ძ',
'Წ' => 'წ',
'Ჭ' => 'ჭ',
'Ხ' => 'ხ',
'Ჯ' => 'ჯ',
'Ჰ' => 'ჰ',
'Ჱ' => 'ჱ',
'Ჲ' => 'ჲ',
'Ჳ' => 'ჳ',
'Ჴ' => 'ჴ',
'Ჵ' => 'ჵ',
'Ჶ' => 'ჶ',
'Ჷ' => 'ჷ',
'Ჸ' => 'ჸ',
'Ჹ' => 'ჹ',
'Ჺ' => 'ჺ',
'Ჽ' => 'ჽ',
'Ჾ' => 'ჾ',
'Ჿ' => '',
'Ḁ' => 'ḁ',
'Ḃ' => 'ḃ',
'Ḅ' => 'ḅ',
'Ḇ' => 'ḇ',
'Ḉ' => 'ḉ',
'Ḋ' => 'ḋ',
'Ḍ' => 'ḍ',
'Ḏ' => 'ḏ',
'Ḑ' => 'ḑ',
'Ḓ' => 'ḓ',
'Ḕ' => 'ḕ',
'Ḗ' => 'ḗ',
'Ḙ' => 'ḙ',
'Ḛ' => 'ḛ',
'Ḝ' => 'ḝ',
'Ḟ' => 'ḟ',
'Ḡ' => 'ḡ',
'Ḣ' => 'ḣ',
'Ḥ' => 'ḥ',
'Ḧ' => 'ḧ',
'Ḩ' => 'ḩ',
'Ḫ' => 'ḫ',
'Ḭ' => 'ḭ',
'Ḯ' => 'ḯ',
'Ḱ' => 'ḱ',
'Ḳ' => 'ḳ',
'Ḵ' => 'ḵ',
'Ḷ' => 'ḷ',
'Ḹ' => 'ḹ',
'Ḻ' => 'ḻ',
'Ḽ' => 'ḽ',
'Ḿ' => 'ḿ',
'Ṁ' => 'ṁ',
'Ṃ' => 'ṃ',
'Ṅ' => 'ṅ',
'Ṇ' => 'ṇ',
'Ṉ' => 'ṉ',
'Ṋ' => 'ṋ',
'Ṍ' => 'ṍ',
'Ṏ' => 'ṏ',
'Ṑ' => 'ṑ',
'Ṓ' => 'ṓ',
'Ṕ' => 'ṕ',
'Ṗ' => 'ṗ',
'Ṙ' => 'ṙ',
'Ṛ' => 'ṛ',
'Ṝ' => 'ṝ',
'Ṟ' => 'ṟ',
'Ṡ' => 'ṡ',
'Ṣ' => 'ṣ',
'Ṥ' => 'ṥ',
'Ṧ' => 'ṧ',
'Ṩ' => 'ṩ',
'Ṫ' => 'ṫ',
'Ṭ' => 'ṭ',
'Ṯ' => 'ṯ',
'Ṱ' => 'ṱ',
'Ṳ' => 'ṳ',
'Ṵ' => 'ṵ',
'Ṷ' => 'ṷ',
'Ṹ' => 'ṹ',
'Ṻ' => 'ṻ',
'Ṽ' => 'ṽ',
'Ṿ' => 'ṿ',
'Ẁ' => 'ẁ',
'Ẃ' => 'ẃ',
'Ẅ' => 'ẅ',
'Ẇ' => 'ẇ',
'Ẉ' => 'ẉ',
'Ẋ' => 'ẋ',
'Ẍ' => 'ẍ',
'Ẏ' => 'ẏ',
'Ẑ' => 'ẑ',
'Ẓ' => 'ẓ',
'Ẕ' => 'ẕ',
'ẞ' => 'ß',
'Ạ' => 'ạ',
'Ả' => 'ả',
'Ấ' => 'ấ',
'Ầ' => 'ầ',
'Ẩ' => 'ẩ',
'Ẫ' => 'ẫ',
'Ậ' => 'ậ',
'Ắ' => 'ắ',
'Ằ' => 'ằ',
'Ẳ' => 'ẳ',
'Ẵ' => 'ẵ',
'Ặ' => 'ặ',
'Ẹ' => 'ẹ',
'Ẻ' => 'ẻ',
'Ẽ' => 'ẽ',
'Ế' => 'ế',
'Ề' => 'ề',
'Ể' => 'ể',
'Ễ' => 'ễ',
'Ệ' => 'ệ',
'Ỉ' => 'ỉ',
'Ị' => 'ị',
'Ọ' => 'ọ',
'Ỏ' => 'ỏ',
'Ố' => 'ố',
'Ồ' => 'ồ',
'Ổ' => 'ổ',
'Ỗ' => 'ỗ',
'Ộ' => 'ộ',
'Ớ' => 'ớ',
'Ờ' => 'ờ',
'Ở' => 'ở',
'Ỡ' => 'ỡ',
'Ợ' => 'ợ',
'Ụ' => 'ụ',
'Ủ' => 'ủ',
'Ứ' => 'ứ',
'Ừ' => 'ừ',
'Ử' => 'ử',
'Ữ' => 'ữ',
'Ự' => 'ự',
'Ỳ' => 'ỳ',
'Ỵ' => 'ỵ',
'Ỷ' => 'ỷ',
'Ỹ' => 'ỹ',
'Ỻ' => 'ỻ',
'Ỽ' => 'ỽ',
'Ỿ' => 'ỿ',
'Ἀ' => 'ἀ',
'Ἁ' => 'ἁ',
'Ἂ' => 'ἂ',
'Ἃ' => 'ἃ',
'Ἄ' => 'ἄ',
'Ἅ' => 'ἅ',
'Ἆ' => 'ἆ',
'Ἇ' => 'ἇ',
'Ἐ' => 'ἐ',
'Ἑ' => 'ἑ',
'Ἒ' => 'ἒ',
'Ἓ' => 'ἓ',
'Ἔ' => 'ἔ',
'Ἕ' => 'ἕ',
'Ἠ' => 'ἠ',
'Ἡ' => 'ἡ',
'Ἢ' => 'ἢ',
'Ἣ' => 'ἣ',
'Ἤ' => 'ἤ',
'Ἥ' => 'ἥ',
'Ἦ' => 'ἦ',
'Ἧ' => 'ἧ',
'Ἰ' => 'ἰ',
'Ἱ' => 'ἱ',
'Ἲ' => 'ἲ',
'Ἳ' => 'ἳ',
'Ἴ' => 'ἴ',
'Ἵ' => 'ἵ',
'Ἶ' => 'ἶ',
'Ἷ' => 'ἷ',
'Ὀ' => 'ὀ',
'Ὁ' => 'ὁ',
'Ὂ' => 'ὂ',
'Ὃ' => 'ὃ',
'Ὄ' => 'ὄ',
'Ὅ' => 'ὅ',
'Ὑ' => 'ὑ',
'Ὓ' => 'ὓ',
'Ὕ' => 'ὕ',
'Ὗ' => 'ὗ',
'Ὠ' => 'ὠ',
'Ὡ' => 'ὡ',
'Ὢ' => 'ὢ',
'Ὣ' => 'ὣ',
'Ὤ' => 'ὤ',
'Ὥ' => 'ὥ',
'Ὦ' => 'ὦ',
'Ὧ' => 'ὧ',
'ᾈ' => 'ᾀ',
'ᾉ' => 'ᾁ',
'ᾊ' => 'ᾂ',
'ᾋ' => 'ᾃ',
'ᾌ' => 'ᾄ',
'ᾍ' => 'ᾅ',
'ᾎ' => 'ᾆ',
'ᾏ' => 'ᾇ',
'ᾘ' => 'ᾐ',
'ᾙ' => 'ᾑ',
'ᾚ' => 'ᾒ',
'ᾛ' => 'ᾓ',
'ᾜ' => 'ᾔ',
'ᾝ' => 'ᾕ',
'ᾞ' => 'ᾖ',
'ᾟ' => 'ᾗ',
'ᾨ' => 'ᾠ',
'ᾩ' => 'ᾡ',
'ᾪ' => 'ᾢ',
'ᾫ' => 'ᾣ',
'ᾬ' => 'ᾤ',
'ᾭ' => 'ᾥ',
'ᾮ' => 'ᾦ',
'ᾯ' => 'ᾧ',
'Ᾰ' => 'ᾰ',
'Ᾱ' => 'ᾱ',
'Ὰ' => 'ὰ',
'Ά' => 'ά',
'ᾼ' => 'ᾳ',
'Ὲ' => 'ὲ',
'Έ' => 'έ',
'Ὴ' => 'ὴ',
'Ή' => 'ή',
'ῌ' => 'ῃ',
'Ῐ' => 'ῐ',
'Ῑ' => 'ῑ',
'Ὶ' => 'ὶ',
'Ί' => 'ί',
'Ῠ' => 'ῠ',
'Ῡ' => 'ῡ',
'Ὺ' => 'ὺ',
'Ύ' => 'ύ',
'Ῥ' => 'ῥ',
'Ὸ' => 'ὸ',
'Ό' => 'ό',
'Ὼ' => 'ὼ',
'Ώ' => 'ώ',
'ῼ' => 'ῳ',
'Ω' => 'ω',
'' => 'k',
'Å' => 'å',
'Ⅎ' => 'ⅎ',
'' => '',
'Ⅱ' => 'ⅱ',
'Ⅲ' => 'ⅲ',
'Ⅳ' => 'ⅳ',
'' => '',
'Ⅵ' => 'ⅵ',
'Ⅶ' => 'ⅶ',
'Ⅷ' => 'ⅷ',
'Ⅸ' => 'ⅸ',
'' => '',
'Ⅺ' => 'ⅺ',
'Ⅻ' => 'ⅻ',
'' => '',
'' => '',
'' => '',
'' => 'ⅿ',
'Ↄ' => 'ↄ',
'Ⓐ' => 'ⓐ',
'Ⓑ' => 'ⓑ',
'Ⓒ' => 'ⓒ',
'Ⓓ' => 'ⓓ',
'Ⓔ' => 'ⓔ',
'Ⓕ' => 'ⓕ',
'Ⓖ' => 'ⓖ',
'Ⓗ' => 'ⓗ',
'Ⓘ' => 'ⓘ',
'Ⓙ' => 'ⓙ',
'Ⓚ' => 'ⓚ',
'Ⓛ' => 'ⓛ',
'Ⓜ' => 'ⓜ',
'Ⓝ' => 'ⓝ',
'Ⓞ' => 'ⓞ',
'Ⓟ' => 'ⓟ',
'Ⓠ' => 'ⓠ',
'Ⓡ' => 'ⓡ',
'Ⓢ' => 'ⓢ',
'Ⓣ' => 'ⓣ',
'Ⓤ' => 'ⓤ',
'Ⓥ' => 'ⓥ',
'Ⓦ' => 'ⓦ',
'Ⓧ' => 'ⓧ',
'Ⓨ' => 'ⓨ',
'Ⓩ' => 'ⓩ',
'Ⰰ' => 'ⰰ',
'Ⰱ' => 'ⰱ',
'Ⰲ' => 'ⰲ',
'Ⰳ' => 'ⰳ',
'Ⰴ' => 'ⰴ',
'Ⰵ' => 'ⰵ',
'Ⰶ' => 'ⰶ',
'Ⰷ' => 'ⰷ',
'Ⰸ' => 'ⰸ',
'Ⰹ' => 'ⰹ',
'Ⰺ' => 'ⰺ',
'Ⰻ' => 'ⰻ',
'Ⰼ' => 'ⰼ',
'Ⰽ' => 'ⰽ',
'Ⰾ' => 'ⰾ',
'Ⰿ' => 'ⰿ',
'Ⱀ' => 'ⱀ',
'Ⱁ' => 'ⱁ',
'Ⱂ' => 'ⱂ',
'Ⱃ' => 'ⱃ',
'Ⱄ' => 'ⱄ',
'Ⱅ' => 'ⱅ',
'Ⱆ' => 'ⱆ',
'Ⱇ' => 'ⱇ',
'Ⱈ' => 'ⱈ',
'Ⱉ' => 'ⱉ',
'Ⱊ' => 'ⱊ',
'Ⱋ' => 'ⱋ',
'Ⱌ' => 'ⱌ',
'Ⱍ' => 'ⱍ',
'Ⱎ' => 'ⱎ',
'Ⱏ' => 'ⱏ',
'Ⱐ' => 'ⱐ',
'Ⱑ' => 'ⱑ',
'Ⱒ' => 'ⱒ',
'Ⱓ' => 'ⱓ',
'Ⱔ' => 'ⱔ',
'Ⱕ' => 'ⱕ',
'Ⱖ' => 'ⱖ',
'Ⱗ' => 'ⱗ',
'Ⱘ' => 'ⱘ',
'Ⱙ' => 'ⱙ',
'Ⱚ' => 'ⱚ',
'Ⱛ' => 'ⱛ',
'Ⱜ' => 'ⱜ',
'Ⱝ' => 'ⱝ',
'Ⱞ' => 'ⱞ',
'Ⱡ' => 'ⱡ',
'Ɫ' => 'ɫ',
'Ᵽ' => 'ᵽ',
'Ɽ' => 'ɽ',
'Ⱨ' => 'ⱨ',
'Ⱪ' => 'ⱪ',
'Ⱬ' => 'ⱬ',
'Ɑ' => 'ɑ',
'Ɱ' => 'ɱ',
'Ɐ' => 'ɐ',
'Ɒ' => 'ɒ',
'Ⱳ' => 'ⱳ',
'Ⱶ' => 'ⱶ',
'Ȿ' => 'ȿ',
'Ɀ' => 'ɀ',
'Ⲁ' => 'ⲁ',
'Ⲃ' => 'ⲃ',
'Ⲅ' => '',
'Ⲇ' => 'ⲇ',
'Ⲉ' => 'ⲉ',
'Ⲋ' => 'ⲋ',
'Ⲍ' => 'ⲍ',
'' => 'ⲏ',
'Ⲑ' => 'ⲑ',
'' => 'ⲓ',
'' => 'ⲕ',
'Ⲗ' => 'ⲗ',
'' => 'ⲙ',
'' => 'ⲛ',
'Ⲝ' => 'ⲝ',
'' => '',
'Ⲡ' => 'ⲡ',
'' => '',
'' => '',
'' => 'ⲧ',
'' => 'ⲩ',
'Ⲫ' => 'ⲫ',
'' => 'ⲭ',
'Ⲯ' => 'ⲯ',
'Ⲱ' => 'ⲱ',
'Ⲳ' => 'ⲳ',
'Ⲵ' => 'ⲵ',
'Ⲷ' => 'ⲷ',
'Ⲹ' => 'ⲹ',
'' => 'ⲻ',
'Ⲽ' => 'ⲽ',
'Ⲿ' => 'ⲿ',
'Ⳁ' => 'ⳁ',
'Ⳃ' => 'ⳃ',
'Ⳅ' => 'ⳅ',
'' => 'ⳇ',
'Ⳉ' => 'ⳉ',
'' => 'ⳋ',
'' => 'ⳍ',
'Ⳏ' => 'ⳏ',
'' => 'ⳑ',
'' => 'ⳓ',
'Ⳕ' => 'ⳕ',
'Ⳗ' => 'ⳗ',
'Ⳙ' => 'ⳙ',
'Ⳛ' => 'ⳛ',
'Ⳝ' => 'ⳝ',
'Ⳟ' => 'ⳟ',
'Ⳡ' => 'ⳡ',
'Ⳣ' => 'ⳣ',
'Ⳬ' => 'ⳬ',
'Ⳮ' => 'ⳮ',
'Ⳳ' => 'ⳳ',
'Ꙁ' => 'ꙁ',
'Ꙃ' => 'ꙃ',
'' => 'ꙅ',
'Ꙇ' => '',
'Ꙉ' => 'ꙉ',
'Ꙋ' => 'ꙋ',
'Ꙍ' => 'ꙍ',
'Ꙏ' => 'ꙏ',
'Ꙑ' => 'ꙑ',
'Ꙓ' => 'ꙓ',
'Ꙕ' => 'ꙕ',
'Ꙗ' => 'ꙗ',
'Ꙙ' => 'ꙙ',
'Ꙛ' => 'ꙛ',
'Ꙝ' => 'ꙝ',
'Ꙟ' => 'ꙟ',
'Ꙡ' => 'ꙡ',
'Ꙣ' => 'ꙣ',
'Ꙥ' => 'ꙥ',
'Ꙧ' => 'ꙧ',
'Ꙩ' => 'ꙩ',
'Ꙫ' => 'ꙫ',
'Ꙭ' => 'ꙭ',
'Ꚁ' => 'ꚁ',
'Ꚃ' => 'ꚃ',
'Ꚅ' => 'ꚅ',
'Ꚇ' => 'ꚇ',
'Ꚉ' => 'ꚉ',
'Ꚋ' => 'ꚋ',
'Ꚍ' => 'ꚍ',
'Ꚏ' => 'ꚏ',
'Ꚑ' => 'ꚑ',
'Ꚓ' => 'ꚓ',
'Ꚕ' => 'ꚕ',
'Ꚗ' => 'ꚗ',
'Ꚙ' => 'ꚙ',
'Ꚛ' => 'ꚛ',
'Ꜣ' => 'ꜣ',
'Ꜥ' => 'ꜥ',
'Ꜧ' => 'ꜧ',
'Ꜩ' => 'ꜩ',
'Ꜫ' => 'ꜫ',
'Ꜭ' => 'ꜭ',
'Ꜯ' => 'ꜯ',
'Ꜳ' => 'ꜳ',
'Ꜵ' => 'ꜵ',
'Ꜷ' => 'ꜷ',
'Ꜹ' => 'ꜹ',
'Ꜻ' => 'ꜻ',
'Ꜽ' => 'ꜽ',
'Ꜿ' => 'ꜿ',
'Ꝁ' => 'ꝁ',
'Ꝃ' => 'ꝃ',
'Ꝅ' => 'ꝅ',
'Ꝇ' => 'ꝇ',
'Ꝉ' => 'ꝉ',
'Ꝋ' => 'ꝋ',
'Ꝍ' => 'ꝍ',
'Ꝏ' => 'ꝏ',
'Ꝑ' => 'ꝑ',
'Ꝓ' => 'ꝓ',
'Ꝕ' => 'ꝕ',
'Ꝗ' => 'ꝗ',
'Ꝙ' => 'ꝙ',
'' => 'ꝛ',
'Ꝝ' => 'ꝝ',
'Ꝟ' => 'ꝟ',
'Ꝡ' => 'ꝡ',
'Ꝣ' => 'ꝣ',
'Ꝥ' => 'ꝥ',
'Ꝧ' => 'ꝧ',
'Ꝩ' => 'ꝩ',
'' => 'ꝫ',
'Ꝭ' => 'ꝭ',
'' => 'ꝯ',
'Ꝺ' => 'ꝺ',
'Ꝼ' => 'ꝼ',
'Ᵹ' => 'ᵹ',
'Ꝿ' => 'ꝿ',
'Ꞁ' => 'ꞁ',
'Ꞃ' => 'ꞃ',
'Ꞅ' => 'ꞅ',
'Ꞇ' => 'ꞇ',
'Ꞌ' => '',
'Ɥ' => 'ɥ',
'Ꞑ' => 'ꞑ',
'Ꞓ' => 'ꞓ',
'Ꞗ' => 'ꞗ',
'' => '',
'Ꞛ' => 'ꞛ',
'Ꞝ' => 'ꞝ',
'Ꞟ' => '',
'Ꞡ' => 'ꞡ',
'Ꞣ' => 'ꞣ',
'Ꞥ' => 'ꞥ',
'Ꞧ' => 'ꞧ',
'Ꞩ' => 'ꞩ',
'Ɦ' => 'ɦ',
'' => 'ɜ',
'Ɡ' => 'ɡ',
'Ɬ' => 'ɬ',
'Ɪ' => 'ɪ',
'Ʞ' => 'ʞ',
'Ʇ' => 'ʇ',
'' => 'ʝ',
'' => 'ꭓ',
'' => 'ꞵ',
'Ꞷ' => 'ꞷ',
'Ꞹ' => 'ꞹ',
'Ꞻ' => 'ꞻ',
'Ꞽ' => 'ꞽ',
'Ꞿ' => 'ꞿ',
'Ꟃ' => 'ꟃ',
'Ꞔ' => 'ꞔ',
'Ʂ' => 'ʂ',
'Ᶎ' => 'ᶎ',
'Ꟈ' => 'ꟈ',
'Ꟊ' => 'ꟊ',
'Ꟶ' => 'ꟶ',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'𐐀' => '𐐨',
'𐐁' => '𐐩',
'𐐂' => '𐐪',
'𐐃' => '𐐫',
'𐐄' => '𐐬',
'𐐅' => '𐐭',
'𐐆' => '𐐮',
'𐐇' => '𐐯',
'𐐈' => '𐐰',
'𐐉' => '𐐱',
'𐐊' => '𐐲',
'𐐋' => '𐐳',
'𐐌' => '𐐴',
'𐐍' => '𐐵',
'𐐎' => '𐐶',
'𐐏' => '𐐷',
'𐐐' => '𐐸',
'𐐑' => '𐐹',
'𐐒' => '𐐺',
'𐐓' => '𐐻',
'𐐔' => '𐐼',
'𐐕' => '𐐽',
'𐐖' => '𐐾',
'𐐗' => '𐐿',
'𐐘' => '𐑀',
'𐐙' => '𐑁',
'𐐚' => '𐑂',
'𐐛' => '𐑃',
'𐐜' => '𐑄',
'𐐝' => '𐑅',
'𐐞' => '𐑆',
'𐐟' => '𐑇',
'𐐠' => '𐑈',
'𐐡' => '𐑉',
'𐐢' => '𐑊',
'𐐣' => '𐑋',
'𐐤' => '𐑌',
'𐐥' => '𐑍',
'𐐦' => '𐑎',
'𐐧' => '𐑏',
'𐒰' => '𐓘',
'𐒱' => '𐓙',
'𐒲' => '𐓚',
'𐒳' => '𐓛',
'𐒴' => '𐓜',
'𐒵' => '𐓝',
'𐒶' => '𐓞',
'𐒷' => '𐓟',
'𐒸' => '𐓠',
'𐒹' => '𐓡',
'𐒺' => '𐓢',
'𐒻' => '𐓣',
'𐒼' => '𐓤',
'𐒽' => '𐓥',
'𐒾' => '𐓦',
'𐒿' => '𐓧',
'𐓀' => '𐓨',
'𐓁' => '𐓩',
'𐓂' => '𐓪',
'𐓃' => '𐓫',
'𐓄' => '𐓬',
'𐓅' => '𐓭',
'𐓆' => '𐓮',
'𐓇' => '𐓯',
'𐓈' => '𐓰',
'𐓉' => '𐓱',
'𐓊' => '𐓲',
'𐓋' => '𐓳',
'𐓌' => '𐓴',
'𐓍' => '𐓵',
'𐓎' => '𐓶',
'𐓏' => '𐓷',
'𐓐' => '𐓸',
'𐓑' => '𐓹',
'𐓒' => '𐓺',
'𐓓' => '𐓻',
'𐲀' => '𐳀',
'𐲁' => '𐳁',
'𐲂' => '𐳂',
'𐲃' => '𐳃',
'𐲄' => '𐳄',
'𐲅' => '𐳅',
'𐲆' => '𐳆',
'𐲇' => '𐳇',
'𐲈' => '𐳈',
'𐲉' => '𐳉',
'𐲊' => '𐳊',
'𐲋' => '𐳋',
'𐲌' => '𐳌',
'𐲍' => '𐳍',
'𐲎' => '𐳎',
'𐲏' => '𐳏',
'𐲐' => '𐳐',
'𐲑' => '𐳑',
'𐲒' => '𐳒',
'𐲓' => '𐳓',
'𐲔' => '𐳔',
'𐲕' => '𐳕',
'𐲖' => '𐳖',
'𐲗' => '𐳗',
'𐲘' => '𐳘',
'𐲙' => '𐳙',
'𐲚' => '𐳚',
'𐲛' => '𐳛',
'𐲜' => '𐳜',
'𐲝' => '𐳝',
'𐲞' => '𐳞',
'𐲟' => '𐳟',
'𐲠' => '𐳠',
'𐲡' => '𐳡',
'𐲢' => '𐳢',
'𐲣' => '𐳣',
'𐲤' => '𐳤',
'𐲥' => '𐳥',
'𐲦' => '𐳦',
'𐲧' => '𐳧',
'𐲨' => '𐳨',
'𐲩' => '𐳩',
'𐲪' => '𐳪',
'𐲫' => '𐳫',
'𐲬' => '𐳬',
'𐲭' => '𐳭',
'𐲮' => '𐳮',
'𐲯' => '𐳯',
'𐲰' => '𐳰',
'𐲱' => '𐳱',
'𐲲' => '𐳲',
'𑢠' => '𑣀',
'𑢡' => '𑣁',
'𑢢' => '𑣂',
'𑢣' => '𑣃',
'𑢤' => '𑣄',
'𑢥' => '𑣅',
'𑢦' => '𑣆',
'𑢧' => '𑣇',
'𑢨' => '𑣈',
'𑢩' => '𑣉',
'𑢪' => '𑣊',
'𑢫' => '𑣋',
'𑢬' => '𑣌',
'𑢭' => '𑣍',
'𑢮' => '𑣎',
'𑢯' => '𑣏',
'𑢰' => '𑣐',
'𑢱' => '𑣑',
'𑢲' => '𑣒',
'𑢳' => '𑣓',
'𑢴' => '𑣔',
'𑢵' => '𑣕',
'𑢶' => '𑣖',
'𑢷' => '𑣗',
'𑢸' => '𑣘',
'𑢹' => '𑣙',
'𑢺' => '𑣚',
'𑢻' => '𑣛',
'𑢼' => '𑣜',
'𑢽' => '𑣝',
'𑢾' => '𑣞',
'𑢿' => '𑣟',
'𖹀' => '𖹠',
'𖹁' => '𖹡',
'𖹂' => '𖹢',
'𖹃' => '𖹣',
'𖹄' => '𖹤',
'𖹅' => '𖹥',
'𖹆' => '𖹦',
'𖹇' => '𖹧',
'𖹈' => '𖹨',
'𖹉' => '𖹩',
'𖹊' => '𖹪',
'𖹋' => '𖹫',
'𖹌' => '𖹬',
'𖹍' => '𖹭',
'𖹎' => '𖹮',
'𖹏' => '𖹯',
'𖹐' => '𖹰',
'𖹑' => '𖹱',
'𖹒' => '𖹲',
'𖹓' => '𖹳',
'𖹔' => '𖹴',
'𖹕' => '𖹵',
'𖹖' => '𖹶',
'𖹗' => '𖹷',
'𖹘' => '𖹸',
'𖹙' => '𖹹',
'𖹚' => '𖹺',
'𖹛' => '𖹻',
'𖹜' => '𖹼',
'𖹝' => '𖹽',
'𖹞' => '𖹾',
'𖹟' => '𖹿',
'𞤀' => '𞤢',
'𞤁' => '𞤣',
'𞤂' => '𞤤',
'𞤃' => '𞤥',
'𞤄' => '𞤦',
'𞤅' => '𞤧',
'𞤆' => '𞤨',
'𞤇' => '𞤩',
'𞤈' => '𞤪',
'𞤉' => '𞤫',
'𞤊' => '𞤬',
'𞤋' => '𞤭',
'𞤌' => '𞤮',
'𞤍' => '𞤯',
'𞤎' => '𞤰',
'𞤏' => '𞤱',
'𞤐' => '𞤲',
'𞤑' => '𞤳',
'𞤒' => '𞤴',
'𞤓' => '𞤵',
'𞤔' => '𞤶',
'𞤕' => '𞤷',
'𞤖' => '𞤸',
'𞤗' => '𞤹',
'𞤘' => '𞤺',
'𞤙' => '𞤻',
'𞤚' => '𞤼',
'𞤛' => '𞤽',
'𞤜' => '𞤾',
'𞤝' => '𞤿',
'𞤞' => '𞥀',
'𞤟' => '𞥁',
'𞤠' => '𞥂',
'𞤡' => '𞥃',
);
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Mbstring as p;
if (!function_exists('mb_convert_variables')) {
/**
* Convert character code in variable(s)
*/
function mb_convert_variables($to_encoding, $from_encoding, &$var, &...$vars)
{
$vars = [&$var, ...$vars];
$ok = true;
array_walk_recursive($vars, function (&$v) use (&$ok, $to_encoding, $from_encoding) {
if (false === $v = p\Mbstring::mb_convert_encoding($v, $to_encoding, $from_encoding)) {
$ok = false;
}
});
return $ok ? $from_encoding : false;
}
}
<?php
namespace Symfony\Component\OptionsResolver;
use Symfony\Component\OptionsResolver\Exception\AccessException;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\Exception\NoSuchOptionException;
use Symfony\Component\OptionsResolver\Exception\OptionDefinitionException;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
class OptionsResolver implements Options
{
private $defined = [];
private $defaults = [];
private $required = [];
private $resolved = [];
private $normalizers = [];
private $allowedValues = [];
private $allowedTypes = [];
private $lazy = [];
private $calling = [];
private $locked = false;
private static $typeAliases = [
'boolean' => 'bool',
'integer' => 'int',
'double' => 'float',
];
public function setDefault($option, $value)
{
if ($this->locked) {
throw new AccessException('Default values cannot be set from a lazy option or normalizer.');
}
if ($value instanceof \Closure) {
$reflClosure = new \ReflectionFunction($value);
$params = $reflClosure->getParameters();
if (isset($params[0]) && Options::class === $this->getParameterClassName($params[0])) {
if (!isset($this->defaults[$option])) {
$this->defaults[$option] = null;
}
if (!isset($this->lazy[$option]) || !isset($params[1])) {
$this->lazy[$option] = [];
}
$this->lazy[$option][] = $value;
$this->defined[$option] = true;
unset($this->resolved[$option]);
return $this;
}
}
unset($this->lazy[$option]);
if (!isset($this->defined[$option]) || \array_key_exists($option, $this->resolved)) {
$this->resolved[$option] = $value;
}
$this->defaults[$option] = $value;
$this->defined[$option] = true;
return $this;
}
public function setDefaults(array $defaults)
{
foreach ($defaults as $option => $value) {
$this->setDefault($option, $value);
}
return $this;
}
public function hasDefault($option)
{
return \array_key_exists($option, $this->defaults);
}
public function setRequired($optionNames)
{
if ($this->locked) {
throw new AccessException('Options cannot be made required from a lazy option or normalizer.');
}
foreach ((array) $optionNames as $option) {
$this->defined[$option] = true;
$this->required[$option] = true;
}
return $this;
}
public function isRequired($option)
{
return isset($this->required[$option]);
}
public function getRequiredOptions()
{
return array_keys($this->required);
}
public function isMissing($option)
{
return isset($this->required[$option]) && !\array_key_exists($option, $this->defaults);
}
public function getMissingOptions()
{
return array_keys(array_diff_key($this->required, $this->defaults));
}
public function setDefined($optionNames)
{
if ($this->locked) {
throw new AccessException('Options cannot be defined from a lazy option or normalizer.');
}
foreach ((array) $optionNames as $option) {
$this->defined[$option] = true;
}
return $this;
}
public function isDefined($option)
{
return isset($this->defined[$option]);
}
public function getDefinedOptions()
{
return array_keys($this->defined);
}
public function setNormalizer($option, \Closure $normalizer)
{
if ($this->locked) {
throw new AccessException('Normalizers cannot be set from a lazy option or normalizer.');
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->normalizers[$option] = $normalizer;
unset($this->resolved[$option]);
return $this;
}
public function setAllowedValues($option, $allowedValues)
{
if ($this->locked) {
throw new AccessException('Allowed values cannot be set from a lazy option or normalizer.');
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : [$allowedValues];
unset($this->resolved[$option]);
return $this;
}
public function addAllowedValues($option, $allowedValues)
{
if ($this->locked) {
throw new AccessException('Allowed values cannot be added from a lazy option or normalizer.');
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
if (!\is_array($allowedValues)) {
$allowedValues = [$allowedValues];
}
if (!isset($this->allowedValues[$option])) {
$this->allowedValues[$option] = $allowedValues;
} else {
$this->allowedValues[$option] = array_merge($this->allowedValues[$option], $allowedValues);
}
unset($this->resolved[$option]);
return $this;
}
public function setAllowedTypes($option, $allowedTypes)
{
if ($this->locked) {
throw new AccessException('Allowed types cannot be set from a lazy option or normalizer.');
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
$this->allowedTypes[$option] = (array) $allowedTypes;
unset($this->resolved[$option]);
return $this;
}
public function addAllowedTypes($option, $allowedTypes)
{
if ($this->locked) {
throw new AccessException('Allowed types cannot be added from a lazy option or normalizer.');
}
if (!isset($this->defined[$option])) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
if (!isset($this->allowedTypes[$option])) {
$this->allowedTypes[$option] = (array) $allowedTypes;
} else {
$this->allowedTypes[$option] = array_merge($this->allowedTypes[$option], (array) $allowedTypes);
}
unset($this->resolved[$option]);
return $this;
}
public function remove($optionNames)
{
if ($this->locked) {
throw new AccessException('Options cannot be removed from a lazy option or normalizer.');
}
foreach ((array) $optionNames as $option) {
unset($this->defined[$option], $this->defaults[$option], $this->required[$option], $this->resolved[$option]);
unset($this->lazy[$option], $this->normalizers[$option], $this->allowedTypes[$option], $this->allowedValues[$option]);
}
return $this;
}
public function clear()
{
if ($this->locked) {
throw new AccessException('Options cannot be cleared from a lazy option or normalizer.');
}
$this->defined = [];
$this->defaults = [];
$this->required = [];
$this->resolved = [];
$this->lazy = [];
$this->normalizers = [];
$this->allowedTypes = [];
$this->allowedValues = [];
return $this;
}
public function resolve(array $options = [])
{
if ($this->locked) {
throw new AccessException('Options cannot be resolved from a lazy option or normalizer.');
}
$clone = clone $this;
$diff = array_diff_key($options, $clone->defined);
if (\count($diff) > 0) {
ksort($clone->defined);
ksort($diff);
throw new UndefinedOptionsException(sprintf((\count($diff) > 1 ? 'The options "%s" do not exist.' : 'The option "%s" does not exist.').' Defined options are: "%s".', implode('", "', array_keys($diff)), implode('", "', array_keys($clone->defined))));
}
foreach ($options as $option => $value) {
$clone->defaults[$option] = $value;
unset($clone->resolved[$option], $clone->lazy[$option]);
}
$diff = array_diff_key($clone->required, $clone->defaults);
if (\count($diff) > 0) {
ksort($diff);
throw new MissingOptionsException(sprintf(\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.', implode('", "', array_keys($diff))));
}
$clone->locked = true;
foreach ($clone->defaults as $option => $_) {
$clone->offsetGet($option);
}
return $clone->resolved;
}
public function offsetGet($option)
{
if (!$this->locked) {
throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
}
if (\array_key_exists($option, $this->resolved)) {
return $this->resolved[$option];
}
if (!\array_key_exists($option, $this->defaults)) {
if (!isset($this->defined[$option])) {
throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined))));
}
throw new NoSuchOptionException(sprintf('The optional option "%s" has no value set. You should make sure it is set with "isset" before reading it.', $option));
}
$value = $this->defaults[$option];
if (isset($this->lazy[$option])) {
if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
}
$this->calling[$option] = true;
try {
foreach ($this->lazy[$option] as $closure) {
$value = $closure($this, $value);
}
} finally {
unset($this->calling[$option]);
}
}
if (isset($this->allowedTypes[$option])) {
$valid = true;
$invalidTypes = [];
foreach ($this->allowedTypes[$option] as $type) {
$type = isset(self::$typeAliases[$type]) ? self::$typeAliases[$type] : $type;
if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) {
break;
}
}
if (!$valid) {
$fmtActualValue = $this->formatValue($value);
$fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]);
$fmtProvidedTypes = implode('|', array_keys($invalidTypes));
$allowedContainsArrayType = \count(array_filter(
$this->allowedTypes[$option],
function ($item) {
return '[]' === substr(isset(self::$typeAliases[$item]) ? self::$typeAliases[$item] : $item, -2);
}
)) > 0;
if (\is_array($value) && $allowedContainsArrayType) {
throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but one of the elements is of type "%s".', $option, $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
}
throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but is of type "%s".', $option, $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
}
}
if (isset($this->allowedValues[$option])) {
$success = false;
$printableAllowedValues = [];
foreach ($this->allowedValues[$option] as $allowedValue) {
if ($allowedValue instanceof \Closure) {
if ($allowedValue($value)) {
$success = true;
break;
}
continue;
}
if ($value === $allowedValue) {
$success = true;
break;
}
$printableAllowedValues[] = $allowedValue;
}
if (!$success) {
$message = sprintf(
'The option "%s" with value %s is invalid.',
$option,
$this->formatValue($value)
);
if (\count($printableAllowedValues) > 0) {
$message .= sprintf(
' Accepted values are: %s.',
$this->formatValues($printableAllowedValues)
);
}
throw new InvalidOptionsException($message);
}
}
if (isset($this->normalizers[$option])) {
if (isset($this->calling[$option])) {
throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
}
$normalizer = $this->normalizers[$option];
$this->calling[$option] = true;
try {
$value = $normalizer($this, $value);
} finally {
unset($this->calling[$option]);
}
}
$this->resolved[$option] = $value;
return $value;
}
private function verifyTypes($type, $value, array &$invalidTypes)
{
if (\is_array($value) && '[]' === substr($type, -2)) {
return $this->verifyArrayType($type, $value, $invalidTypes);
}
if (self::isValueValidType($type, $value)) {
return true;
}
if (!$invalidTypes) {
$invalidTypes[$this->formatTypeOf($value, null)] = true;
}
return false;
}
private function verifyArrayType($type, array $value, array &$invalidTypes, $level = 0)
{
$type = substr($type, 0, -2);
if ('[]' === substr($type, -2)) {
$success = true;
foreach ($value as $item) {
if (!\is_array($item)) {
$invalidTypes[$this->formatTypeOf($item, null)] = true;
$success = false;
} elseif (!$this->verifyArrayType($type, $item, $invalidTypes, $level + 1)) {
$success = false;
}
}
return $success;
}
$valid = true;
foreach ($value as $item) {
if (!self::isValueValidType($type, $item)) {
$invalidTypes[$this->formatTypeOf($item, $type)] = $value;
$valid = false;
}
}
return $valid;
}
public function offsetExists($option)
{
if (!$this->locked) {
throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
}
return \array_key_exists($option, $this->defaults);
}
public function offsetSet($option, $value)
{
throw new AccessException('Setting options via array access is not supported. Use setDefault() instead.');
}
public function offsetUnset($option)
{
throw new AccessException('Removing options via array access is not supported. Use remove() instead.');
}
public function count()
{
if (!$this->locked) {
throw new AccessException('Counting is only supported within closures of lazy options and normalizers.');
}
return \count($this->defaults);
}
private function formatTypeOf($value, $type)
{
$suffix = '';
if ('[]' === substr($type, -2)) {
$suffix = '[]';
$type = substr($type, 0, -2);
while ('[]' === substr($type, -2)) {
$type = substr($type, 0, -2);
$value = array_shift($value);
if (!\is_array($value)) {
break;
}
$suffix .= '[]';
}
if (\is_array($value)) {
$subTypes = [];
foreach ($value as $val) {
$subTypes[$this->formatTypeOf($val, null)] = true;
}
return implode('|', array_keys($subTypes)).$suffix;
}
}
return (\is_object($value) ? \get_class($value) : \gettype($value)).$suffix;
}
private function formatValue($value)
{
if (\is_object($value)) {
return \get_class($value);
}
if (\is_array($value)) {
return 'array';
}
if (\is_string($value)) {
return '"'.$value.'"';
}
if (\is_resource($value)) {
return 'resource';
}
if (null === $value) {
return 'null';
}
if (false === $value) {
return 'false';
}
if (true === $value) {
return 'true';
}
return (string) $value;
}
private function formatValues(array $values)
{
foreach ($values as $key => $value) {
$values[$key] = $this->formatValue($value);
}
return implode(', ', $values);
}
private static function isValueValidType($type, $value)
{
return (\function_exists($isFunction = 'is_'.$type) && $isFunction($value)) || $value instanceof $type;
}
private function getParameterClassName(\ReflectionParameter $parameter)
{
if (!method_exists($parameter, 'getType')) {
return ($class = $parameter->getClass()) ? $class->name : null;
}
if (!($type = $parameter->getType()) || $type->isBuiltin()) {
return null;
}
return $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
}
}
<?php
namespace Symfony\Component\OptionsResolver\Debug;
use Symfony\Component\OptionsResolver\Exception\NoConfigurationException;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OptionsResolverIntrospector
{
private $get;
public function __construct(OptionsResolver $optionsResolver)
{
$this->get = \Closure::bind(function ($property, $option, $message) {
if (!$this->isDefined($option)) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist.', $option));
}
if (!\array_key_exists($option, $this->{$property})) {
throw new NoConfigurationException($message);
}
return $this->{$property}[$option];
}, $optionsResolver, $optionsResolver);
}
public function getDefault($option)
{
return \call_user_func($this->get, 'defaults', $option, sprintf('No default value was set for the "%s" option.', $option));
}
public function getLazyClosures($option)
{
return \call_user_func($this->get, 'lazy', $option, sprintf('No lazy closures were set for the "%s" option.', $option));
}
public function getAllowedTypes($option)
{
return \call_user_func($this->get, 'allowedTypes', $option, sprintf('No allowed types were set for the "%s" option.', $option));
}
public function getAllowedValues($option)
{
return \call_user_func($this->get, 'allowedValues', $option, sprintf('No allowed values were set for the "%s" option.', $option));
}
public function getNormalizer($option)
{
return \call_user_func($this->get, 'normalizers', $option, sprintf('No normalizer was set for the "%s" option.', $option));
}
}
<?php
namespace Symfony\Component\OptionsResolver;
interface Options extends \ArrayAccess, \Countable
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class MissingOptionsException extends InvalidArgumentException
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class AccessException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class OptionDefinitionException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
use Symfony\Component\OptionsResolver\Debug\OptionsResolverIntrospector;
class NoConfigurationException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class UndefinedOptionsException extends InvalidArgumentException
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class InvalidOptionsException extends InvalidArgumentException
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class NoSuchOptionException extends \OutOfBoundsException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\OptionsResolver\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\VarDumper\Caster\ClassStub;
class WrappedListener
{
private $listener;
private $name;
private $called;
private $stoppedPropagation;
private $stopwatch;
private $dispatcher;
private $pretty;
private $stub;
private $priority;
private static $hasClassStub;
public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
{
$this->listener = $listener;
$this->stopwatch = $stopwatch;
$this->dispatcher = $dispatcher;
$this->called = false;
$this->stoppedPropagation = false;
if (\is_array($listener)) {
$this->name = \is_object($listener[0]) ? \get_class($listener[0]) : $listener[0];
$this->pretty = $this->name.'::'.$listener[1];
} elseif ($listener instanceof \Closure) {
$r = new \ReflectionFunction($listener);
if (false !== strpos($r->name, '{closure}')) {
$this->pretty = $this->name = 'closure';
} elseif ($class = $r->getClosureScopeClass()) {
$this->name = $class->name;
$this->pretty = $this->name.'::'.$r->name;
} else {
$this->pretty = $this->name = $r->name;
}
} elseif (\is_string($listener)) {
$this->pretty = $this->name = $listener;
} else {
$this->name = \get_class($listener);
$this->pretty = $this->name.'::__invoke';
}
if (null !== $name) {
$this->name = $name;
}
if (null === self::$hasClassStub) {
self::$hasClassStub = class_exists(ClassStub::class);
}
}
public function getWrappedListener()
{
return $this->listener;
}
public function wasCalled()
{
return $this->called;
}
public function stoppedPropagation()
{
return $this->stoppedPropagation;
}
public function getPretty()
{
return $this->pretty;
}
public function getInfo($eventName)
{
if (null === $this->stub) {
$this->stub = self::$hasClassStub ? new ClassStub($this->pretty.'()', $this->listener) : $this->pretty.'()';
}
return [
'event' => $eventName,
'priority' => null !== $this->priority ? $this->priority : (null !== $this->dispatcher ? $this->dispatcher->getListenerPriority($eventName, $this->listener) : null),
'pretty' => $this->pretty,
'stub' => $this->stub,
];
}
public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher)
{
$dispatcher = $this->dispatcher ?: $dispatcher;
$this->called = true;
$this->priority = $dispatcher->getListenerPriority($eventName, $this->listener);
$e = $this->stopwatch->start($this->name, 'event_listener');
\call_user_func($this->listener, $event, $eventName, $dispatcher);
if ($e->isStarted()) {
$e->stop();
}
if ($event->isPropagationStopped()) {
$this->stoppedPropagation = true;
}
}
}
<?php
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
interface TraceableEventDispatcherInterface extends EventDispatcherInterface
{
public function getCalledListeners();
public function getNotCalledListeners();
}
<?php
namespace Symfony\Component\EventDispatcher\Debug;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Stopwatch\Stopwatch;
class TraceableEventDispatcher implements TraceableEventDispatcherInterface
{
protected $logger;
protected $stopwatch;
private $callStack;
private $dispatcher;
private $wrappedListeners;
public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null)
{
$this->dispatcher = $dispatcher;
$this->stopwatch = $stopwatch;
$this->logger = $logger;
$this->wrappedListeners = [];
}
public function addListener($eventName, $listener, $priority = 0)
{
$this->dispatcher->addListener($eventName, $listener, $priority);
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->dispatcher->addSubscriber($subscriber);
}
public function removeListener($eventName, $listener)
{
if (isset($this->wrappedListeners[$eventName])) {
foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
if ($wrappedListener->getWrappedListener() === $listener) {
$listener = $wrappedListener;
unset($this->wrappedListeners[$eventName][$index]);
break;
}
}
}
return $this->dispatcher->removeListener($eventName, $listener);
}
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
return $this->dispatcher->removeSubscriber($subscriber);
}
public function getListeners($eventName = null)
{
return $this->dispatcher->getListeners($eventName);
}
public function getListenerPriority($eventName, $listener)
{
if (isset($this->wrappedListeners[$eventName])) {
foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
if ($wrappedListener->getWrappedListener() === $listener) {
return $this->dispatcher->getListenerPriority($eventName, $wrappedListener);
}
}
}
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
public function hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}
public function dispatch($eventName, Event $event = null)
{
if (null === $this->callStack) {
$this->callStack = new \SplObjectStorage();
}
if (null === $event) {
$event = new Event();
}
if (null !== $this->logger && $event->isPropagationStopped()) {
$this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
}
$this->preProcess($eventName);
try {
$this->preDispatch($eventName, $event);
try {
$e = $this->stopwatch->start($eventName, 'section');
try {
$this->dispatcher->dispatch($eventName, $event);
} finally {
if ($e->isStarted()) {
$e->stop();
}
}
} finally {
$this->postDispatch($eventName, $event);
}
} finally {
$this->postProcess($eventName);
}
return $event;
}
public function getCalledListeners()
{
if (null === $this->callStack) {
return [];
}
$called = [];
foreach ($this->callStack as $listener) {
list($eventName) = $this->callStack->getInfo();
$called[] = $listener->getInfo($eventName);
}
return $called;
}
public function getNotCalledListeners()
{
try {
$allListeners = $this->getListeners();
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
}
return [];
}
$calledListeners = [];
if (null !== $this->callStack) {
foreach ($this->callStack as $calledListener) {
$calledListeners[] = $calledListener->getWrappedListener();
}
}
$notCalled = [];
foreach ($allListeners as $eventName => $listeners) {
foreach ($listeners as $listener) {
if (!\in_array($listener, $calledListeners, true)) {
if (!$listener instanceof WrappedListener) {
$listener = new WrappedListener($listener, null, $this->stopwatch, $this);
}
$notCalled[] = $listener->getInfo($eventName);
}
}
}
uasort($notCalled, [$this, 'sortNotCalledListeners']);
return $notCalled;
}
public function reset()
{
$this->callStack = null;
}
public function __call($method, $arguments)
{
return \call_user_func_array([$this->dispatcher, $method], $arguments);
}
protected function preDispatch($eventName, Event $event)
{
}
protected function postDispatch($eventName, Event $event)
{
}
private function preProcess($eventName)
{
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
$priority = $this->getListenerPriority($eventName, $listener);
$wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $this->stopwatch, $this);
$this->wrappedListeners[$eventName][] = $wrappedListener;
$this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $wrappedListener, $priority);
$this->callStack->attach($wrappedListener, [$eventName]);
}
}
private function postProcess($eventName)
{
unset($this->wrappedListeners[$eventName]);
$skipped = false;
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
if (!$listener instanceof WrappedListener) {
continue;
}
$priority = $this->getListenerPriority($eventName, $listener);
$this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);
if (null !== $this->logger) {
$context = ['event' => $eventName, 'listener' => $listener->getPretty()];
}
if ($listener->wasCalled()) {
if (null !== $this->logger) {
$this->logger->debug('Notified event "{event}" to listener "{listener}".', $context);
}
} else {
$this->callStack->detach($listener);
}
if (null !== $this->logger && $skipped) {
$this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context);
}
if ($listener->stoppedPropagation()) {
if (null !== $this->logger) {
$this->logger->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);
}
$skipped = true;
}
}
}
private function sortNotCalledListeners(array $a, array $b)
{
if (0 !== $cmp = strcmp($a['event'], $b['event'])) {
return $cmp;
}
if (\is_int($a['priority']) && !\is_int($b['priority'])) {
return 1;
}
if (!\is_int($a['priority']) && \is_int($b['priority'])) {
return -1;
}
if ($a['priority'] === $b['priority']) {
return 0;
}
if ($a['priority'] > $b['priority']) {
return -1;
}
return 1;
}
}
<?php
namespace Symfony\Component\EventDispatcher\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RegisterListenersPass implements CompilerPassInterface
{
protected $dispatcherService;
protected $listenerTag;
protected $subscriberTag;
private $hotPathEvents = [];
private $hotPathTagName;
public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber')
{
$this->dispatcherService = $dispatcherService;
$this->listenerTag = $listenerTag;
$this->subscriberTag = $subscriberTag;
}
public function setHotPathEvents(array $hotPathEvents, $tagName = 'container.hot_path')
{
$this->hotPathEvents = array_flip($hotPathEvents);
$this->hotPathTagName = $tagName;
return $this;
}
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) {
return;
}
$definition = $container->findDefinition($this->dispatcherService);
foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;
if (!isset($event['event'])) {
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
}
if (!isset($event['method'])) {
$event['method'] = 'on'.preg_replace_callback([
'/(?<=\b)[a-z]/i',
'/[^a-z0-9]/i',
], function ($matches) { return strtoupper($matches[0]); }, $event['event']);
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
}
$definition->addMethodCall('addListener', [$event['event'], [new ServiceClosureArgument(new Reference($id)), $event['method']], $priority]);
if (isset($this->hotPathEvents[$event['event']])) {
$container->getDefinition($id)->addTag($this->hotPathTagName);
}
}
}
$extractingDispatcher = new ExtractingEventDispatcher();
foreach ($container->findTaggedServiceIds($this->subscriberTag, true) as $id => $attributes) {
$def = $container->getDefinition($id);
$class = $def->getClass();
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(EventSubscriberInterface::class)) {
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EventSubscriberInterface::class));
}
$class = $r->name;
ExtractingEventDispatcher::$subscriber = $class;
$extractingDispatcher->addSubscriber($extractingDispatcher);
foreach ($extractingDispatcher->listeners as $args) {
$args[1] = [new ServiceClosureArgument(new Reference($id)), $args[1]];
$definition->addMethodCall('addListener', $args);
if (isset($this->hotPathEvents[$args[0]])) {
$container->getDefinition($id)->addTag($this->hotPathTagName);
}
}
$extractingDispatcher->listeners = [];
}
}
}
class ExtractingEventDispatcher extends EventDispatcher implements EventSubscriberInterface
{
public $listeners = [];
public static $subscriber;
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[] = [$eventName, $listener[1], $priority];
}
public static function getSubscribedEvents()
{
$callback = [self::$subscriber, 'getSubscribedEvents'];
return $callback();
}
}
<?php
namespace Symfony\Component\EventDispatcher;
interface EventDispatcherInterface
{
public function dispatch($eventName, Event $event = null);
public function addListener($eventName, $listener, $priority = 0);
public function addSubscriber(EventSubscriberInterface $subscriber);
public function removeListener($eventName, $listener);
public function removeSubscriber(EventSubscriberInterface $subscriber);
public function getListeners($eventName = null);
public function getListenerPriority($eventName, $listener);
public function hasListeners($eventName = null);
}
<?php
namespace Symfony\Component\EventDispatcher;
class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
{
protected $subject;
protected $arguments;
public function __construct($subject = null, array $arguments = [])
{
$this->subject = $subject;
$this->arguments = $arguments;
}
public function getSubject()
{
return $this->subject;
}
public function getArgument($key)
{
if ($this->hasArgument($key)) {
return $this->arguments[$key];
}
throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key));
}
public function setArgument($key, $value)
{
$this->arguments[$key] = $value;
return $this;
}
public function getArguments()
{
return $this->arguments;
}
public function setArguments(array $args = [])
{
$this->arguments = $args;
return $this;
}
public function hasArgument($key)
{
return \array_key_exists($key, $this->arguments);
}
public function offsetGet($key)
{
return $this->getArgument($key);
}
public function offsetSet($key, $value)
{
$this->setArgument($key, $value);
}
public function offsetUnset($key)
{
if ($this->hasArgument($key)) {
unset($this->arguments[$key]);
}
}
public function offsetExists($key)
{
return $this->hasArgument($key);
}
public function getIterator()
{
return new \ArrayIterator($this->arguments);
}
}
<?php
namespace Symfony\Component\EventDispatcher;
/**
@gmail
@gmail
@symfony
@seld
@gmail
@tchwork
*/
class EventDispatcher implements EventDispatcherInterface
{
private $listeners = [];
private $sorted = [];
public function dispatch($eventName, Event $event = null)
{
if (null === $event) {
$event = new Event();
}
if ($listeners = $this->getListeners($eventName)) {
$this->doDispatch($listeners, $eventName, $event);
}
return $event;
}
public function getListeners($eventName = null)
{
if (null !== $eventName) {
if (empty($this->listeners[$eventName])) {
return [];
}
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
return $this->sorted[$eventName];
}
foreach ($this->listeners as $eventName => $eventListeners) {
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
}
return array_filter($this->sorted);
}
public function getListenerPriority($eventName, $listener)
{
if (empty($this->listeners[$eventName])) {
return null;
}
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
foreach ($listeners as $k => $v) {
if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
$v[0] = $v[0]();
$this->listeners[$eventName][$priority][$k] = $v;
}
if ($v === $listener) {
return $priority;
}
}
}
return null;
}
public function hasListeners($eventName = null)
{
if (null !== $eventName) {
return !empty($this->listeners[$eventName]);
}
foreach ($this->listeners as $eventListeners) {
if ($eventListeners) {
return true;
}
}
return false;
}
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[$eventName][$priority][] = $listener;
unset($this->sorted[$eventName]);
}
public function removeListener($eventName, $listener)
{
if (empty($this->listeners[$eventName])) {
return;
}
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
foreach ($listeners as $k => $v) {
if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
$v[0] = $v[0]();
}
if ($v === $listener) {
unset($listeners[$k], $this->sorted[$eventName]);
} else {
$listeners[$k] = $v;
}
}
if ($listeners) {
$this->listeners[$eventName][$priority] = $listeners;
} else {
unset($this->listeners[$eventName][$priority]);
}
}
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$this->addListener($eventName, [$subscriber, $params]);
} elseif (\is_string($params[0])) {
$this->addListener($eventName, [$subscriber, $params[0]], isset($params[1]) ? $params[1] : 0);
} else {
foreach ($params as $listener) {
$this->addListener($eventName, [$subscriber, $listener[0]], isset($listener[1]) ? $listener[1] : 0);
}
}
}
}
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_array($params) && \is_array($params[0])) {
foreach ($params as $listener) {
$this->removeListener($eventName, [$subscriber, $listener[0]]);
}
} else {
$this->removeListener($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]);
}
}
}
protected function doDispatch($listeners, $eventName, Event $event)
{
foreach ($listeners as $listener) {
if ($event->isPropagationStopped()) {
break;
}
\call_user_func($listener, $event, $eventName, $this);
}
}
private function sortListeners($eventName)
{
krsort($this->listeners[$eventName]);
$this->sorted[$eventName] = [];
foreach ($this->listeners[$eventName] as $priority => $listeners) {
foreach ($listeners as $k => $listener) {
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
$this->listeners[$eventName][$priority][$k] = $listener;
}
$this->sorted[$eventName][] = $listener;
}
}
}
}
<?php
namespace Symfony\Component\EventDispatcher;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@gmail
@gmail
*/
class ContainerAwareEventDispatcher extends EventDispatcher
{
private $container;
private $listenerIds = [];
private $listeners = [];
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$class = static::class;
if ($this instanceof \PHPUnit_Framework_MockObject_MockObject || $this instanceof MockObject || $this instanceof \Prophecy\Doubler\DoubleInterface) {
$class = get_parent_class($class);
}
if (__CLASS__ !== $class) {
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), \E_USER_DEPRECATED);
}
}
public function addListenerService($eventName, $callback, $priority = 0)
{
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), \E_USER_DEPRECATED);
if (!\is_array($callback) || 2 !== \count($callback)) {
throw new \InvalidArgumentException('Expected an ["service", "method"] argument.');
}
$this->listenerIds[$eventName][] = [$callback[0], $callback[1], $priority];
}
public function removeListener($eventName, $listener)
{
$this->lazyLoad($eventName);
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as $i => list($serviceId, $method)) {
$key = $serviceId.'.'.$method;
if (isset($this->listeners[$eventName][$key]) && $listener === [$this->listeners[$eventName][$key], $method]) {
unset($this->listeners[$eventName][$key]);
if (empty($this->listeners[$eventName])) {
unset($this->listeners[$eventName]);
}
unset($this->listenerIds[$eventName][$i]);
if (empty($this->listenerIds[$eventName])) {
unset($this->listenerIds[$eventName]);
}
}
}
}
parent::removeListener($eventName, $listener);
}
public function hasListeners($eventName = null)
{
if (null === $eventName) {
return $this->listenerIds || $this->listeners || parent::hasListeners();
}
if (isset($this->listenerIds[$eventName])) {
return true;
}
return parent::hasListeners($eventName);
}
public function getListeners($eventName = null)
{
if (null === $eventName) {
foreach ($this->listenerIds as $serviceEventName => $args) {
$this->lazyLoad($serviceEventName);
}
} else {
$this->lazyLoad($eventName);
}
return parent::getListeners($eventName);
}
public function getListenerPriority($eventName, $listener)
{
$this->lazyLoad($eventName);
return parent::getListenerPriority($eventName, $listener);
}
public function addSubscriberService($serviceId, $class)
{
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), \E_USER_DEPRECATED);
foreach ($class::getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$this->listenerIds[$eventName][] = [$serviceId, $params, 0];
} elseif (\is_string($params[0])) {
$this->listenerIds[$eventName][] = [$serviceId, $params[0], isset($params[1]) ? $params[1] : 0];
} else {
foreach ($params as $listener) {
$this->listenerIds[$eventName][] = [$serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0];
}
}
}
}
public function getContainer()
{
@trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 as its class will be removed in 4.0. Inject the container or the services you need in your listeners/subscribers instead.', \E_USER_DEPRECATED);
return $this->container;
}
protected function lazyLoad($eventName)
{
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as list($serviceId, $method, $priority)) {
$listener = $this->container->get($serviceId);
$key = $serviceId.'.'.$method;
if (!isset($this->listeners[$eventName][$key])) {
$this->addListener($eventName, [$listener, $method], $priority);
} elseif ($this->listeners[$eventName][$key] !== $listener) {
parent::removeListener($eventName, [$this->listeners[$eventName][$key], $method]);
$this->addListener($eventName, [$listener, $method], $priority);
}
$this->listeners[$eventName][$key] = $listener;
}
}
}
}
<?php
namespace Symfony\Component\EventDispatcher;
/**
@gmail
@gmail
*/
class Event
{
private $propagationStopped = false;
public function isPropagationStopped()
{
return $this->propagationStopped;
}
public function stopPropagation()
{
$this->propagationStopped = true;
}
}
<?php
namespace Symfony\Component\EventDispatcher;
class ImmutableEventDispatcher implements EventDispatcherInterface
{
private $dispatcher;
public function __construct(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function dispatch($eventName, Event $event = null)
{
return $this->dispatcher->dispatch($eventName, $event);
}
public function addListener($eventName, $listener, $priority = 0)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function removeListener($eventName, $listener)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function getListeners($eventName = null)
{
return $this->dispatcher->getListeners($eventName);
}
public function getListenerPriority($eventName, $listener)
{
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
public function hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}
}
<?php
namespace Symfony\Component\EventDispatcher;
/**
@gmail
@gmail
*/
interface EventSubscriberInterface
{
public static function getSubscribedEvents();
}
<?php
namespace Symfony\Component\Stopwatch;
class StopwatchPeriod
{
private $start;
private $end;
private $memory;
public function __construct($start, $end, $morePrecision = false)
{
$this->start = $morePrecision ? (float) $start : (int) $start;
$this->end = $morePrecision ? (float) $end : (int) $end;
$this->memory = memory_get_usage(true);
}
public function getStartTime()
{
return $this->start;
}
public function getEndTime()
{
return $this->end;
}
public function getDuration()
{
return $this->end - $this->start;
}
public function getMemory()
{
return $this->memory;
}
}
<?php
namespace Symfony\Component\Stopwatch;
class Stopwatch
{
private $morePrecision;
private $sections;
private $activeSections;
public function __construct($morePrecision = false)
{
$this->morePrecision = $morePrecision;
$this->reset();
}
public function getSections()
{
return $this->sections;
}
public function openSection($id = null)
{
$current = end($this->activeSections);
if (null !== $id && null === $current->get($id)) {
throw new \LogicException(sprintf('The section "%s" has been started at an other level and can not be opened.', $id));
}
$this->start('__section__.child', 'section');
$this->activeSections[] = $current->open($id);
$this->start('__section__');
}
public function stopSection($id)
{
$this->stop('__section__');
if (1 == \count($this->activeSections)) {
throw new \LogicException('There is no started section to stop.');
}
$this->sections[$id] = array_pop($this->activeSections)->setId($id);
$this->stop('__section__.child');
}
public function start($name, $category = null)
{
return end($this->activeSections)->startEvent($name, $category);
}
public function isStarted($name)
{
return end($this->activeSections)->isEventStarted($name);
}
public function stop($name)
{
return end($this->activeSections)->stopEvent($name);
}
public function lap($name)
{
return end($this->activeSections)->stopEvent($name)->start();
}
public function getEvent($name)
{
return end($this->activeSections)->getEvent($name);
}
public function getSectionEvents($id)
{
return isset($this->sections[$id]) ? $this->sections[$id]->getEvents() : [];
}
public function reset()
{
$this->sections = $this->activeSections = ['__root__' => new Section(null, $this->morePrecision)];
}
}
<?php
namespace Symfony\Component\Stopwatch;
class StopwatchEvent
{
private $periods = [];
private $origin;
private $category;
private $morePrecision;
private $started = [];
public function __construct($origin, $category = null, $morePrecision = false)
{
$this->origin = $this->formatTime($origin);
$this->category = \is_string($category) ? $category : 'default';
$this->morePrecision = $morePrecision;
}
public function getCategory()
{
return $this->category;
}
public function getOrigin()
{
return $this->origin;
}
public function start()
{
$this->started[] = $this->getNow();
return $this;
}
public function stop()
{
if (!\count($this->started)) {
throw new \LogicException('stop() called but start() has not been called before.');
}
$this->periods[] = new StopwatchPeriod(array_pop($this->started), $this->getNow(), $this->morePrecision);
return $this;
}
public function isStarted()
{
return !empty($this->started);
}
public function lap()
{
return $this->stop()->start();
}
public function ensureStopped()
{
while (\count($this->started)) {
$this->stop();
}
}
public function getPeriods()
{
return $this->periods;
}
public function getStartTime()
{
if (isset($this->periods[0])) {
return $this->periods[0]->getStartTime();
}
if ($this->started) {
return $this->started[0];
}
return 0;
}
public function getEndTime()
{
$count = \count($this->periods);
return $count ? $this->periods[$count - 1]->getEndTime() : 0;
}
public function getDuration()
{
$periods = $this->periods;
$left = \count($this->started);
for ($i = $left - 1; $i >= 0; --$i) {
$periods[] = new StopwatchPeriod($this->started[$i], $this->getNow(), $this->morePrecision);
}
$total = 0;
foreach ($periods as $period) {
$total += $period->getDuration();
}
return $total;
}
public function getMemory()
{
$memory = 0;
foreach ($this->periods as $period) {
if ($period->getMemory() > $memory) {
$memory = $period->getMemory();
}
}
return $memory;
}
protected function getNow()
{
return $this->formatTime(microtime(true) * 1000 - $this->origin);
}
private function formatTime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('The time must be a numerical value.');
}
return round($time, 1);
}
public function __toString()
{
return sprintf('%s: %.2F MiB - %d ms', $this->getCategory(), $this->getMemory() / 1024 / 1024, $this->getDuration());
}
}
<?php
namespace Symfony\Component\Stopwatch;
class Section
{
private $events = [];
private $origin;
private $morePrecision;
private $id;
private $children = [];
public function __construct($origin = null, $morePrecision = false)
{
$this->origin = is_numeric($origin) ? $origin : null;
$this->morePrecision = $morePrecision;
}
public function get($id)
{
foreach ($this->children as $child) {
if ($id === $child->getId()) {
return $child;
}
}
return null;
}
public function open($id)
{
if (null === $session = $this->get($id)) {
$session = $this->children[] = new self(microtime(true) * 1000, $this->morePrecision);
}
return $session;
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function startEvent($name, $category)
{
if (!isset($this->events[$name])) {
$this->events[$name] = new StopwatchEvent($this->origin ?: microtime(true) * 1000, $category, $this->morePrecision);
}
return $this->events[$name]->start();
}
public function isEventStarted($name)
{
return isset($this->events[$name]) && $this->events[$name]->isStarted();
}
public function stopEvent($name)
{
if (!isset($this->events[$name])) {
throw new \LogicException(sprintf('Event "%s" is not started.', $name));
}
return $this->events[$name]->stop();
}
public function lap($name)
{
return $this->stopEvent($name)->start();
}
public function getEvent($name)
{
if (!isset($this->events[$name])) {
throw new \LogicException(sprintf('Event "%s" is not known.', $name));
}
return $this->events[$name];
}
public function getEvents()
{
return $this->events;
}
}
<?php
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit9f0dd14c94ce02dc34a0e91e293e3b6e::getLoader();
<?php
namespace Composer\Autoload;
class ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e
{
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'5255c38a0faeba867671b61dfda6d864' => __DIR__ . '/..' . '/paragonie/random_compat/lib/random.php',
'023d27dca8066ef29e6739335ea73bad' => __DIR__ . '/..' . '/symfony/polyfill-php70/bootstrap.php',
'25072dd6e2470089de65ae7bf11d3109' => __DIR__ . '/..' . '/symfony/polyfill-php72/bootstrap.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php72\\' => 23,
'Symfony\\Polyfill\\Php70\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
'Symfony\\Component\\Stopwatch\\' => 28,
'Symfony\\Component\\Process\\' => 26,
'Symfony\\Component\\OptionsResolver\\' => 34,
'Symfony\\Component\\Finder\\' => 25,
'Symfony\\Component\\Filesystem\\' => 29,
'Symfony\\Component\\EventDispatcher\\' => 34,
'Symfony\\Component\\Debug\\' => 24,
'Symfony\\Component\\Console\\' => 26,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'PhpCsFixer\\' => 11,
),
'D' =>
array (
'Doctrine\\Common\\Lexer\\' => 22,
'Doctrine\\Common\\Annotations\\' => 28,
),
'C' =>
array (
'Composer\\XdebugHandler\\' => 23,
'Composer\\Semver\\' => 16,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Php72\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php72',
),
'Symfony\\Polyfill\\Php70\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php70',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Symfony\\Component\\Stopwatch\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/stopwatch',
),
'Symfony\\Component\\Process\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/process',
),
'Symfony\\Component\\OptionsResolver\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/options-resolver',
),
'Symfony\\Component\\Finder\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/finder',
),
'Symfony\\Component\\Filesystem\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/filesystem',
),
'Symfony\\Component\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher',
),
'Symfony\\Component\\Debug\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/debug',
),
'Symfony\\Component\\Console\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'PhpCsFixer\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
'Doctrine\\Common\\Lexer\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/lexer/lib/Doctrine/Common/Lexer',
),
'Doctrine\\Common\\Annotations\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations',
),
'Composer\\XdebugHandler\\' =>
array (
0 => __DIR__ . '/..' . '/composer/xdebug-handler/src',
),
'Composer\\Semver\\' =>
array (
0 => __DIR__ . '/..' . '/composer/semver/src',
),
);
public static $classMap = array (
'ArithmeticError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php',
'AssertionError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/AssertionError.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'Composer\\Semver\\Comparator' => __DIR__ . '/..' . '/composer/semver/src/Comparator.php',
'Composer\\Semver\\CompilingMatcher' => __DIR__ . '/..' . '/composer/semver/src/CompilingMatcher.php',
'Composer\\Semver\\Constraint\\Bound' => __DIR__ . '/..' . '/composer/semver/src/Constraint/Bound.php',
'Composer\\Semver\\Constraint\\Constraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/Constraint.php',
'Composer\\Semver\\Constraint\\ConstraintInterface' => __DIR__ . '/..' . '/composer/semver/src/Constraint/ConstraintInterface.php',
'Composer\\Semver\\Constraint\\MatchAllConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MatchAllConstraint.php',
'Composer\\Semver\\Constraint\\MatchNoneConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MatchNoneConstraint.php',
'Composer\\Semver\\Constraint\\MultiConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MultiConstraint.php',
'Composer\\Semver\\Interval' => __DIR__ . '/..' . '/composer/semver/src/Interval.php',
'Composer\\Semver\\Intervals' => __DIR__ . '/..' . '/composer/semver/src/Intervals.php',
'Composer\\Semver\\Semver' => __DIR__ . '/..' . '/composer/semver/src/Semver.php',
'Composer\\Semver\\VersionParser' => __DIR__ . '/..' . '/composer/semver/src/VersionParser.php',
'Composer\\XdebugHandler\\PhpConfig' => __DIR__ . '/..' . '/composer/xdebug-handler/src/PhpConfig.php',
'Composer\\XdebugHandler\\Process' => __DIR__ . '/..' . '/composer/xdebug-handler/src/Process.php',
'Composer\\XdebugHandler\\Status' => __DIR__ . '/..' . '/composer/xdebug-handler/src/Status.php',
'Composer\\XdebugHandler\\XdebugHandler' => __DIR__ . '/..' . '/composer/xdebug-handler/src/XdebugHandler.php',
'DivisionByZeroError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php',
'Doctrine\\Common\\Annotations\\Annotation' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php',
'Doctrine\\Common\\Annotations\\AnnotationException' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php',
'Doctrine\\Common\\Annotations\\AnnotationReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php',
'Doctrine\\Common\\Annotations\\AnnotationRegistry' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php',
'Doctrine\\Common\\Annotations\\Annotation\\Attribute' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php',
'Doctrine\\Common\\Annotations\\Annotation\\Attributes' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php',
'Doctrine\\Common\\Annotations\\Annotation\\Enum' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php',
'Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php',
'Doctrine\\Common\\Annotations\\Annotation\\Required' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.php',
'Doctrine\\Common\\Annotations\\Annotation\\Target' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php',
'Doctrine\\Common\\Annotations\\CachedReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/CachedReader.php',
'Doctrine\\Common\\Annotations\\DocLexer' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.php',
'Doctrine\\Common\\Annotations\\DocParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php',
'Doctrine\\Common\\Annotations\\FileCacheReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/FileCacheReader.php',
'Doctrine\\Common\\Annotations\\IndexedReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php',
'Doctrine\\Common\\Annotations\\PhpParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php',
'Doctrine\\Common\\Annotations\\Reader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php',
'Doctrine\\Common\\Annotations\\SimpleAnnotationReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/SimpleAnnotationReader.php',
'Doctrine\\Common\\Annotations\\TokenParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php',
'Doctrine\\Common\\Lexer\\AbstractLexer' => __DIR__ . '/..' . '/doctrine/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php',
'Error' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/Error.php',
'ParseError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/ParseError.php',
'PhpCsFixer\\AbstractAlignFixerHelper' => __DIR__ . '/../..' . '/src/AbstractAlignFixerHelper.php',
'PhpCsFixer\\AbstractDoctrineAnnotationFixer' => __DIR__ . '/../..' . '/src/AbstractDoctrineAnnotationFixer.php',
'PhpCsFixer\\AbstractFixer' => __DIR__ . '/../..' . '/src/AbstractFixer.php',
'PhpCsFixer\\AbstractFopenFlagFixer' => __DIR__ . '/../..' . '/src/AbstractFopenFlagFixer.php',
'PhpCsFixer\\AbstractFunctionReferenceFixer' => __DIR__ . '/../..' . '/src/AbstractFunctionReferenceFixer.php',
'PhpCsFixer\\AbstractLinesBeforeNamespaceFixer' => __DIR__ . '/../..' . '/src/AbstractLinesBeforeNamespaceFixer.php',
'PhpCsFixer\\AbstractNoUselessElseFixer' => __DIR__ . '/../..' . '/src/AbstractNoUselessElseFixer.php',
'PhpCsFixer\\AbstractPhpdocToTypeDeclarationFixer' => __DIR__ . '/../..' . '/src/AbstractPhpdocToTypeDeclarationFixer.php',
'PhpCsFixer\\AbstractPhpdocTypesFixer' => __DIR__ . '/../..' . '/src/AbstractPhpdocTypesFixer.php',
'PhpCsFixer\\AbstractProxyFixer' => __DIR__ . '/../..' . '/src/AbstractProxyFixer.php',
'PhpCsFixer\\Cache\\Cache' => __DIR__ . '/../..' . '/src/Cache/Cache.php',
'PhpCsFixer\\Cache\\CacheInterface' => __DIR__ . '/../..' . '/src/Cache/CacheInterface.php',
'PhpCsFixer\\Cache\\CacheManagerInterface' => __DIR__ . '/../..' . '/src/Cache/CacheManagerInterface.php',
'PhpCsFixer\\Cache\\Directory' => __DIR__ . '/../..' . '/src/Cache/Directory.php',
'PhpCsFixer\\Cache\\DirectoryInterface' => __DIR__ . '/../..' . '/src/Cache/DirectoryInterface.php',
'PhpCsFixer\\Cache\\FileCacheManager' => __DIR__ . '/../..' . '/src/Cache/FileCacheManager.php',
'PhpCsFixer\\Cache\\FileHandler' => __DIR__ . '/../..' . '/src/Cache/FileHandler.php',
'PhpCsFixer\\Cache\\FileHandlerInterface' => __DIR__ . '/../..' . '/src/Cache/FileHandlerInterface.php',
'PhpCsFixer\\Cache\\NullCacheManager' => __DIR__ . '/../..' . '/src/Cache/NullCacheManager.php',
'PhpCsFixer\\Cache\\Signature' => __DIR__ . '/../..' . '/src/Cache/Signature.php',
'PhpCsFixer\\Cache\\SignatureInterface' => __DIR__ . '/../..' . '/src/Cache/SignatureInterface.php',
'PhpCsFixer\\Config' => __DIR__ . '/../..' . '/src/Config.php',
'PhpCsFixer\\ConfigInterface' => __DIR__ . '/../..' . '/src/ConfigInterface.php',
'PhpCsFixer\\ConfigurationException\\InvalidConfigurationException' => __DIR__ . '/../..' . '/src/ConfigurationException/InvalidConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\InvalidFixerConfigurationException' => __DIR__ . '/../..' . '/src/ConfigurationException/InvalidFixerConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\InvalidForEnvFixerConfigurationException' => __DIR__ . '/../..' . '/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\RequiredFixerConfigurationException' => __DIR__ . '/../..' . '/src/ConfigurationException/RequiredFixerConfigurationException.php',
'PhpCsFixer\\Console\\Application' => __DIR__ . '/../..' . '/src/Console/Application.php',
'PhpCsFixer\\Console\\Command\\DescribeCommand' => __DIR__ . '/../..' . '/src/Console/Command/DescribeCommand.php',
'PhpCsFixer\\Console\\Command\\DescribeNameNotFoundException' => __DIR__ . '/../..' . '/src/Console/Command/DescribeNameNotFoundException.php',
'PhpCsFixer\\Console\\Command\\DocumentationCommand' => __DIR__ . '/../..' . '/src/Console/Command/DocumentationCommand.php',
'PhpCsFixer\\Console\\Command\\FixCommand' => __DIR__ . '/../..' . '/src/Console/Command/FixCommand.php',
'PhpCsFixer\\Console\\Command\\FixCommandExitStatusCalculator' => __DIR__ . '/../..' . '/src/Console/Command/FixCommandExitStatusCalculator.php',
'PhpCsFixer\\Console\\Command\\HelpCommand' => __DIR__ . '/../..' . '/src/Console/Command/HelpCommand.php',
'PhpCsFixer\\Console\\Command\\SelfUpdateCommand' => __DIR__ . '/../..' . '/src/Console/Command/SelfUpdateCommand.php',
'PhpCsFixer\\Console\\ConfigurationResolver' => __DIR__ . '/../..' . '/src/Console/ConfigurationResolver.php',
'PhpCsFixer\\Console\\Output\\ErrorOutput' => __DIR__ . '/../..' . '/src/Console/Output/ErrorOutput.php',
'PhpCsFixer\\Console\\Output\\NullOutput' => __DIR__ . '/../..' . '/src/Console/Output/NullOutput.php',
'PhpCsFixer\\Console\\Output\\ProcessOutput' => __DIR__ . '/../..' . '/src/Console/Output/ProcessOutput.php',
'PhpCsFixer\\Console\\Output\\ProcessOutputInterface' => __DIR__ . '/../..' . '/src/Console/Output/ProcessOutputInterface.php',
'PhpCsFixer\\Console\\SelfUpdate\\GithubClient' => __DIR__ . '/../..' . '/src/Console/SelfUpdate/GithubClient.php',
'PhpCsFixer\\Console\\SelfUpdate\\GithubClientInterface' => __DIR__ . '/../..' . '/src/Console/SelfUpdate/GithubClientInterface.php',
'PhpCsFixer\\Console\\SelfUpdate\\NewVersionChecker' => __DIR__ . '/../..' . '/src/Console/SelfUpdate/NewVersionChecker.php',
'PhpCsFixer\\Console\\SelfUpdate\\NewVersionCheckerInterface' => __DIR__ . '/../..' . '/src/Console/SelfUpdate/NewVersionCheckerInterface.php',
'PhpCsFixer\\Console\\WarningsDetector' => __DIR__ . '/../..' . '/src/Console/WarningsDetector.php',
'PhpCsFixer\\Diff\\GeckoPackages\\DiffOutputBuilder\\ConfigurationException' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/ConfigurationException.php',
'PhpCsFixer\\Diff\\GeckoPackages\\DiffOutputBuilder\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v1_4\\Chunk' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/Chunk.php',
'PhpCsFixer\\Diff\\v1_4\\Diff' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/Diff.php',
'PhpCsFixer\\Diff\\v1_4\\Differ' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/Differ.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\LongestCommonSubsequence' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/LCS/LongestCommonSubsequence.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\MemoryEfficientImplementation' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\TimeEfficientImplementation' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php',
'PhpCsFixer\\Diff\\v1_4\\Line' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/Line.php',
'PhpCsFixer\\Diff\\v1_4\\Parser' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v1_4/Parser.php',
'PhpCsFixer\\Diff\\v2_0\\Chunk' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Chunk.php',
'PhpCsFixer\\Diff\\v2_0\\Diff' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Diff.php',
'PhpCsFixer\\Diff\\v2_0\\Differ' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Differ.php',
'PhpCsFixer\\Diff\\v2_0\\Exception' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Exception/Exception.php',
'PhpCsFixer\\Diff\\v2_0\\InvalidArgumentException' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Exception/InvalidArgumentException.php',
'PhpCsFixer\\Diff\\v2_0\\Line' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Line.php',
'PhpCsFixer\\Diff\\v2_0\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/LongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v2_0\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/MemoryEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Output/AbstractChunkOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Output/DiffOnlyOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Output/DiffOutputBuilderInterface.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Output/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Parser' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/Parser.php',
'PhpCsFixer\\Diff\\v2_0\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v2_0/TimeEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\Chunk' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Chunk.php',
'PhpCsFixer\\Diff\\v3_0\\ConfigurationException' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Exception/ConfigurationException.php',
'PhpCsFixer\\Diff\\v3_0\\Diff' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Diff.php',
'PhpCsFixer\\Diff\\v3_0\\Differ' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Differ.php',
'PhpCsFixer\\Diff\\v3_0\\Exception' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Exception/Exception.php',
'PhpCsFixer\\Diff\\v3_0\\InvalidArgumentException' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Exception/InvalidArgumentException.php',
'PhpCsFixer\\Diff\\v3_0\\Line' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Line.php',
'PhpCsFixer\\Diff\\v3_0\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/LongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/MemoryEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Output/AbstractChunkOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Output/DiffOnlyOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Output/DiffOutputBuilderInterface.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\StrictUnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Output/StrictUnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Output/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Parser' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/Parser.php',
'PhpCsFixer\\Diff\\v3_0\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/php-cs-fixer/diff/src/v3_0/TimeEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Differ\\DiffConsoleFormatter' => __DIR__ . '/../..' . '/src/Differ/DiffConsoleFormatter.php',
'PhpCsFixer\\Differ\\DifferInterface' => __DIR__ . '/../..' . '/src/Differ/DifferInterface.php',
'PhpCsFixer\\Differ\\FullDiffer' => __DIR__ . '/../..' . '/src/Differ/FullDiffer.php',
'PhpCsFixer\\Differ\\NullDiffer' => __DIR__ . '/../..' . '/src/Differ/NullDiffer.php',
'PhpCsFixer\\Differ\\SebastianBergmannDiffer' => __DIR__ . '/../..' . '/src/Differ/SebastianBergmannDiffer.php',
'PhpCsFixer\\Differ\\SebastianBergmannShortDiffer' => __DIR__ . '/../..' . '/src/Differ/SebastianBergmannShortDiffer.php',
'PhpCsFixer\\Differ\\UnifiedDiffer' => __DIR__ . '/../..' . '/src/Differ/UnifiedDiffer.php',
'PhpCsFixer\\DocBlock\\Annotation' => __DIR__ . '/../..' . '/src/DocBlock/Annotation.php',
'PhpCsFixer\\DocBlock\\DocBlock' => __DIR__ . '/../..' . '/src/DocBlock/DocBlock.php',
'PhpCsFixer\\DocBlock\\Line' => __DIR__ . '/../..' . '/src/DocBlock/Line.php',
'PhpCsFixer\\DocBlock\\ShortDescription' => __DIR__ . '/../..' . '/src/DocBlock/ShortDescription.php',
'PhpCsFixer\\DocBlock\\Tag' => __DIR__ . '/../..' . '/src/DocBlock/Tag.php',
'PhpCsFixer\\DocBlock\\TagComparator' => __DIR__ . '/../..' . '/src/DocBlock/TagComparator.php',
'PhpCsFixer\\Doctrine\\Annotation\\Token' => __DIR__ . '/../..' . '/src/Doctrine/Annotation/Token.php',
'PhpCsFixer\\Doctrine\\Annotation\\Tokens' => __DIR__ . '/../..' . '/src/Doctrine/Annotation/Tokens.php',
'PhpCsFixer\\Documentation\\DocumentationGenerator' => __DIR__ . '/../..' . '/src/Documentation/DocumentationGenerator.php',
'PhpCsFixer\\Error\\Error' => __DIR__ . '/../..' . '/src/Error/Error.php',
'PhpCsFixer\\Error\\ErrorsManager' => __DIR__ . '/../..' . '/src/Error/ErrorsManager.php',
'PhpCsFixer\\Event\\Event' => __DIR__ . '/../..' . '/src/Event/Event.php',
'PhpCsFixer\\FileReader' => __DIR__ . '/../..' . '/src/FileReader.php',
'PhpCsFixer\\FileRemoval' => __DIR__ . '/../..' . '/src/FileRemoval.php',
'PhpCsFixer\\Finder' => __DIR__ . '/../..' . '/src/Finder.php',
'PhpCsFixer\\FixerConfiguration\\AliasedFixerOption' => __DIR__ . '/../..' . '/src/FixerConfiguration/AliasedFixerOption.php',
'PhpCsFixer\\FixerConfiguration\\AliasedFixerOptionBuilder' => __DIR__ . '/../..' . '/src/FixerConfiguration/AliasedFixerOptionBuilder.php',
'PhpCsFixer\\FixerConfiguration\\AllowedValueSubset' => __DIR__ . '/../..' . '/src/FixerConfiguration/AllowedValueSubset.php',
'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOption' => __DIR__ . '/../..' . '/src/FixerConfiguration/DeprecatedFixerOption.php',
'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOptionInterface' => __DIR__ . '/../..' . '/src/FixerConfiguration/DeprecatedFixerOptionInterface.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolver' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerConfigurationResolver.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverInterface' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerConfigurationResolverInterface.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverRootless' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerConfigurationResolverRootless.php',
'PhpCsFixer\\FixerConfiguration\\FixerOption' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerOption.php',
'PhpCsFixer\\FixerConfiguration\\FixerOptionBuilder' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerOptionBuilder.php',
'PhpCsFixer\\FixerConfiguration\\FixerOptionInterface' => __DIR__ . '/../..' . '/src/FixerConfiguration/FixerOptionInterface.php',
'PhpCsFixer\\FixerConfiguration\\InvalidOptionsForEnvException' => __DIR__ . '/../..' . '/src/FixerConfiguration/InvalidOptionsForEnvException.php',
'PhpCsFixer\\FixerDefinition\\CodeSample' => __DIR__ . '/../..' . '/src/FixerDefinition/CodeSample.php',
'PhpCsFixer\\FixerDefinition\\CodeSampleInterface' => __DIR__ . '/../..' . '/src/FixerDefinition/CodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSample' => __DIR__ . '/../..' . '/src/FixerDefinition/FileSpecificCodeSample.php',
'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSampleInterface' => __DIR__ . '/../..' . '/src/FixerDefinition/FileSpecificCodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\FixerDefinition' => __DIR__ . '/../..' . '/src/FixerDefinition/FixerDefinition.php',
'PhpCsFixer\\FixerDefinition\\FixerDefinitionInterface' => __DIR__ . '/../..' . '/src/FixerDefinition/FixerDefinitionInterface.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSample' => __DIR__ . '/../..' . '/src/FixerDefinition/VersionSpecificCodeSample.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSampleInterface' => __DIR__ . '/../..' . '/src/FixerDefinition/VersionSpecificCodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecification' => __DIR__ . '/../..' . '/src/FixerDefinition/VersionSpecification.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificationInterface' => __DIR__ . '/../..' . '/src/FixerDefinition/VersionSpecificationInterface.php',
'PhpCsFixer\\FixerFactory' => __DIR__ . '/../..' . '/src/FixerFactory.php',
'PhpCsFixer\\FixerFileProcessedEvent' => __DIR__ . '/../..' . '/src/FixerFileProcessedEvent.php',
'PhpCsFixer\\FixerNameValidator' => __DIR__ . '/../..' . '/src/FixerNameValidator.php',
'PhpCsFixer\\Fixer\\AbstractIncrementOperatorFixer' => __DIR__ . '/../..' . '/src/Fixer/AbstractIncrementOperatorFixer.php',
'PhpCsFixer\\Fixer\\AbstractPhpUnitFixer' => __DIR__ . '/../..' . '/src/Fixer/AbstractPhpUnitFixer.php',
'PhpCsFixer\\Fixer\\Alias\\ArrayPushFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/ArrayPushFixer.php',
'PhpCsFixer\\Fixer\\Alias\\BacktickToShellExecFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/BacktickToShellExecFixer.php',
'PhpCsFixer\\Fixer\\Alias\\EregToPregFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/EregToPregFixer.php',
'PhpCsFixer\\Fixer\\Alias\\MbStrFunctionsFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/MbStrFunctionsFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoAliasFunctionsFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/NoAliasFunctionsFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoAliasLanguageConstructCallFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoMixedEchoPrintFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/NoMixedEchoPrintFixer.php',
'PhpCsFixer\\Fixer\\Alias\\PowToExponentiationFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/PowToExponentiationFixer.php',
'PhpCsFixer\\Fixer\\Alias\\RandomApiMigrationFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/RandomApiMigrationFixer.php',
'PhpCsFixer\\Fixer\\Alias\\SetTypeToCastFixer' => __DIR__ . '/../..' . '/src/Fixer/Alias/SetTypeToCastFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\ArraySyntaxFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/ArraySyntaxFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoMultilineWhitespaceAroundDoubleArrowFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoTrailingCommaInSinglelineArrayFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoWhitespaceBeforeCommaInArrayFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NormalizeIndexBraceFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\TrailingCommaInMultilineArrayFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/TrailingCommaInMultilineArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\TrimArraySpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\WhitespaceAfterCommaInArrayFixer' => __DIR__ . '/../..' . '/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php',
'PhpCsFixer\\Fixer\\Basic\\BracesFixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/BracesFixer.php',
'PhpCsFixer\\Fixer\\Basic\\EncodingFixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/EncodingFixer.php',
'PhpCsFixer\\Fixer\\Basic\\NonPrintableCharacterFixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/NonPrintableCharacterFixer.php',
'PhpCsFixer\\Fixer\\Basic\\Psr0Fixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/Psr0Fixer.php',
'PhpCsFixer\\Fixer\\Basic\\Psr4Fixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/Psr4Fixer.php',
'PhpCsFixer\\Fixer\\Basic\\PsrAutoloadingFixer' => __DIR__ . '/../..' . '/src/Fixer/Basic/PsrAutoloadingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\ConstantCaseFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/ConstantCaseFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseConstantsFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/LowercaseConstantsFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseKeywordsFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/LowercaseKeywordsFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseStaticReferenceFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/LowercaseStaticReferenceFixer.php',
'PhpCsFixer\\Fixer\\Casing\\MagicConstantCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/MagicConstantCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\MagicMethodCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/MagicMethodCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\NativeFunctionCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/NativeFunctionCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\NativeFunctionTypeDeclarationCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\CastSpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/CastSpacesFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\LowercaseCastFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/LowercaseCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\ModernizeTypesCastingFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\NoShortBoolCastFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/NoShortBoolCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\NoUnsetCastFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/NoUnsetCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\ShortScalarCastFixer' => __DIR__ . '/../..' . '/src/Fixer/CastNotation/ShortScalarCastFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ClassAttributesSeparationFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ClassDefinitionFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/ClassDefinitionFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalClassFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/FinalClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalInternalClassFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/FinalInternalClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalPublicMethodForAbstractClassFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalStaticAccessFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/FinalStaticAccessFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\MethodSeparationFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/MethodSeparationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoBlankLinesAfterClassOpeningFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoNullPropertyInitializationFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoPhp4ConstructorFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoUnneededFinalMethodFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedClassElementsFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/OrderedClassElementsFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedInterfacesFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/OrderedInterfacesFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTraitsFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/OrderedTraitsFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ProtectedToPrivateFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SelfAccessorFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/SelfAccessorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SelfStaticAccessorFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SingleClassElementPerStatementFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SingleTraitInsertPerStatementFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\VisibilityRequiredFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassNotation/VisibilityRequiredFixer.php',
'PhpCsFixer\\Fixer\\ClassUsage\\DateTimeImmutableFixer' => __DIR__ . '/../..' . '/src/Fixer/ClassUsage/DateTimeImmutableFixer.php',
'PhpCsFixer\\Fixer\\Comment\\CommentToPhpdocFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/CommentToPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Comment\\HashToSlashCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/HashToSlashCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\HeaderCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/HeaderCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\MultilineCommentOpeningClosingFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php',
'PhpCsFixer\\Fixer\\Comment\\NoEmptyCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/NoEmptyCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\NoTrailingWhitespaceInCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentStyleFixer' => __DIR__ . '/../..' . '/src/Fixer/Comment/SingleLineCommentStyleFixer.php',
'PhpCsFixer\\Fixer\\ConfigurableFixerInterface' => __DIR__ . '/../..' . '/src/Fixer/ConfigurableFixerInterface.php',
'PhpCsFixer\\Fixer\\ConfigurationDefinitionFixerInterface' => __DIR__ . '/../..' . '/src/Fixer/ConfigurationDefinitionFixerInterface.php',
'PhpCsFixer\\Fixer\\ConstantNotation\\NativeConstantInvocationFixer' => __DIR__ . '/../..' . '/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\ElseifFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/ElseifFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\IncludeFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/IncludeFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoAlternativeSyntaxFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoBreakCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoBreakCommentFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoSuperfluousElseifFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoTrailingCommaInListCallFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededControlParenthesesFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededCurlyBracesFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUselessElseFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/NoUselessElseFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SimplifiedIfReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSemicolonToColonFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchContinueToBreakFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\YodaStyleFixer' => __DIR__ . '/../..' . '/src/Fixer/ControlStructure/YodaStyleFixer.php',
'PhpCsFixer\\Fixer\\DefinedFixerInterface' => __DIR__ . '/../..' . '/src/Fixer/DefinedFixerInterface.php',
'PhpCsFixer\\Fixer\\DeprecatedFixerInterface' => __DIR__ . '/../..' . '/src/Fixer/DeprecatedFixerInterface.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationArrayAssignmentFixer' => __DIR__ . '/../..' . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationBracesFixer' => __DIR__ . '/../..' . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationIndentationFixer' => __DIR__ . '/../..' . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationSpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php',
'PhpCsFixer\\Fixer\\FixerInterface' => __DIR__ . '/../..' . '/src/Fixer/FixerInterface.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\CombineNestedDirnameFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagOrderFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagsFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/FopenFlagsFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionDeclarationFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionTypehintSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\ImplodeCallFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/ImplodeCallFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\LambdaNotUsedImportFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\MethodArgumentSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NativeFunctionInvocationFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoSpacesAfterFunctionNameFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoUnreachableDefaultArgumentValueFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoUselessSprintfFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NullableTypeDeclarationForDefaultNullValueFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToParamTypeFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToReturnTypeFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\RegularCallableCallFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/RegularCallableCallFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\ReturnTypeDeclarationFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\SingleLineThrowFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/SingleLineThrowFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\StaticLambdaFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/StaticLambdaFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\UseArrowFunctionsFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\VoidReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/FunctionNotation/VoidReturnFixer.php',
'PhpCsFixer\\Fixer\\Import\\FullyQualifiedStrictTypesFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php',
'PhpCsFixer\\Fixer\\Import\\GlobalNamespaceImportFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/GlobalNamespaceImportFixer.php',
'PhpCsFixer\\Fixer\\Import\\GroupImportFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/GroupImportFixer.php',
'PhpCsFixer\\Fixer\\Import\\NoLeadingImportSlashFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/NoLeadingImportSlashFixer.php',
'PhpCsFixer\\Fixer\\Import\\NoUnusedImportsFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/NoUnusedImportsFixer.php',
'PhpCsFixer\\Fixer\\Import\\OrderedImportsFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/OrderedImportsFixer.php',
'PhpCsFixer\\Fixer\\Import\\SingleImportPerStatementFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/SingleImportPerStatementFixer.php',
'PhpCsFixer\\Fixer\\Import\\SingleLineAfterImportsFixer' => __DIR__ . '/../..' . '/src/Fixer/Import/SingleLineAfterImportsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ClassKeywordRemoveFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveIssetsFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveUnsetsFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareEqualNormalizeFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\DirConstantFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/DirConstantFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ErrorSuppressionFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ExplicitIndirectVariableFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\FunctionToConstantFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\IsNullFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/IsNullFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\NoUnsetOnPropertyFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\SilencedDeprecationErrorFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/SilencedDeprecationErrorFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAfterConstructFixer' => __DIR__ . '/../..' . '/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php',
'PhpCsFixer\\Fixer\\ListNotation\\ListSyntaxFixer' => __DIR__ . '/../..' . '/src/Fixer/ListNotation/ListSyntaxFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLineAfterNamespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\CleanNamespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\NoBlankLinesBeforeNamespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\NoLeadingNamespaceWhitespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\SingleBlankLineBeforeNamespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php',
'PhpCsFixer\\Fixer\\Naming\\NoHomoglyphNamesFixer' => __DIR__ . '/../..' . '/src/Fixer/Naming/NoHomoglyphNamesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\AlignDoubleArrowFixerHelper' => __DIR__ . '/../..' . '/src/Fixer/Operator/AlignDoubleArrowFixerHelper.php',
'PhpCsFixer\\Fixer\\Operator\\AlignEqualsFixerHelper' => __DIR__ . '/../..' . '/src/Fixer/Operator/AlignEqualsFixerHelper.php',
'PhpCsFixer\\Fixer\\Operator\\BinaryOperatorSpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/BinaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\ConcatSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/ConcatSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\IncrementStyleFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/IncrementStyleFixer.php',
'PhpCsFixer\\Fixer\\Operator\\LogicalOperatorsFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/LogicalOperatorsFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NewWithBracesFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/NewWithBracesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/NotOperatorWithSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSuccessorSpaceFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\ObjectOperatorWithoutWhitespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\OperatorLinebreakFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/OperatorLinebreakFixer.php',
'PhpCsFixer\\Fixer\\Operator\\PreIncrementFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/PreIncrementFixer.php',
'PhpCsFixer\\Fixer\\Operator\\StandardizeIncrementFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/StandardizeIncrementFixer.php',
'PhpCsFixer\\Fixer\\Operator\\StandardizeNotEqualsFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/StandardizeNotEqualsFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryOperatorSpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/TernaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryToElvisOperatorFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/TernaryToElvisOperatorFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryToNullCoalescingFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/TernaryToNullCoalescingFixer.php',
'PhpCsFixer\\Fixer\\Operator\\UnaryOperatorSpacesFixer' => __DIR__ . '/../..' . '/src/Fixer/Operator/UnaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\BlankLineAfterOpeningTagFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\EchoTagSyntaxFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/EchoTagSyntaxFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\FullOpeningTagFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/FullOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\LinebreakAfterOpeningTagFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\NoClosingTagFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/NoClosingTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\NoShortEchoTagFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpTag/NoShortEchoTagFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitConstructFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitConstructFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertInternalTypeFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitExpectationFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitFqcnAnnotationFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitInternalClassFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMethodCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitMockFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockShortWillReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNamespacedFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNoExpectationAnnotationFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitOrderedCoversFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitOrderedCoversFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSetUpTearDownVisibilityFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSizeClassFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitStrictFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitStrictFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTargetVersion' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitTargetVersion.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestAnnotationFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestCaseStaticMethodCallsFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestClassRequiresCoversFixer' => __DIR__ . '/../..' . '/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\AlignMultilineCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocAnnotationRemoveFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocTagRenameFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoBlankLinesAfterPhpdocFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoEmptyPhpdocFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoSuperfluousPhpdocTagsFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAddMissingParamAnnotationFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAlignFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocAlignFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAnnotationWithoutDotFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocIndentFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocIndentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocInlineTagFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagNormalizerFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocLineSpanFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAccessFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAliasTagFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoEmptyReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoPackageFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoUselessInheritdocFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderByValueFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocReturnSelfReferenceFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocScalarFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocScalarFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSeparationFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocSeparationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSingleLineVarSpacingFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSummaryFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocSummaryFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagCasingFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagTypeFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocToCommentFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocToCommentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimConsecutiveBlankLineSeparationFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTrimFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTypesFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesOrderFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarAnnotationCorrectOrderFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarWithoutNameFixer' => __DIR__ . '/../..' . '/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\BlankLineBeforeReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/ReturnNotation/BlankLineBeforeReturnFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\NoUselessReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/ReturnNotation/NoUselessReturnFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\ReturnAssignmentFixer' => __DIR__ . '/../..' . '/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\SimplifiedNullReturnFixer' => __DIR__ . '/../..' . '/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\MultilineWhitespaceBeforeSemicolonsFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoEmptyStatementFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/NoEmptyStatementFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoMultilineWhitespaceBeforeSemicolonsFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/NoMultilineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoSinglelineWhitespaceBeforeSemicolonsFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\SemicolonAfterInstructionFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\SpaceAfterSemicolonFixer' => __DIR__ . '/../..' . '/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php',
'PhpCsFixer\\Fixer\\Strict\\DeclareStrictTypesFixer' => __DIR__ . '/../..' . '/src/Fixer/Strict/DeclareStrictTypesFixer.php',
'PhpCsFixer\\Fixer\\Strict\\StrictComparisonFixer' => __DIR__ . '/../..' . '/src/Fixer/Strict/StrictComparisonFixer.php',
'PhpCsFixer\\Fixer\\Strict\\StrictParamFixer' => __DIR__ . '/../..' . '/src/Fixer/Strict/StrictParamFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\EscapeImplicitBackslashesFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\ExplicitStringVariableFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/ExplicitStringVariableFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\HeredocToNowdocFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/HeredocToNowdocFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\NoBinaryStringFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/NoBinaryStringFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\NoTrailingWhitespaceInStringFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\SimpleToComplexStringVariableFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\SingleQuoteFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/SingleQuoteFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\StringLineEndingFixer' => __DIR__ . '/../..' . '/src/Fixer/StringNotation/StringLineEndingFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\ArrayIndentationFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/ArrayIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBeforeStatementFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\CompactNullableTypehintFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/CompactNullableTypehintFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\HeredocIndentationFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/HeredocIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\IndentationTypeFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/IndentationTypeFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\LineEndingFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/LineEndingFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\MethodChainingIndentationFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/MethodChainingIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoExtraBlankLinesFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoExtraConsecutiveBlankLinesFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoExtraConsecutiveBlankLinesFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesAroundOffsetFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesInsideParenthesisFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoTrailingWhitespaceFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoWhitespaceInBlankLineFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\SingleBlankLineAtEofFixer' => __DIR__ . '/../..' . '/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php',
'PhpCsFixer\\Fixer\\WhitespacesAwareFixerInterface' => __DIR__ . '/../..' . '/src/Fixer/WhitespacesAwareFixerInterface.php',
'PhpCsFixer\\Indicator\\PhpUnitTestCaseIndicator' => __DIR__ . '/../..' . '/src/Indicator/PhpUnitTestCaseIndicator.php',
'PhpCsFixer\\Linter\\CachingLinter' => __DIR__ . '/../..' . '/src/Linter/CachingLinter.php',
'PhpCsFixer\\Linter\\Linter' => __DIR__ . '/../..' . '/src/Linter/Linter.php',
'PhpCsFixer\\Linter\\LinterInterface' => __DIR__ . '/../..' . '/src/Linter/LinterInterface.php',
'PhpCsFixer\\Linter\\LintingException' => __DIR__ . '/../..' . '/src/Linter/LintingException.php',
'PhpCsFixer\\Linter\\LintingResultInterface' => __DIR__ . '/../..' . '/src/Linter/LintingResultInterface.php',
'PhpCsFixer\\Linter\\ProcessLinter' => __DIR__ . '/../..' . '/src/Linter/ProcessLinter.php',
'PhpCsFixer\\Linter\\ProcessLinterProcessBuilder' => __DIR__ . '/../..' . '/src/Linter/ProcessLinterProcessBuilder.php',
'PhpCsFixer\\Linter\\ProcessLintingResult' => __DIR__ . '/../..' . '/src/Linter/ProcessLintingResult.php',
'PhpCsFixer\\Linter\\TokenizerLinter' => __DIR__ . '/../..' . '/src/Linter/TokenizerLinter.php',
'PhpCsFixer\\Linter\\TokenizerLintingResult' => __DIR__ . '/../..' . '/src/Linter/TokenizerLintingResult.php',
'PhpCsFixer\\Linter\\UnavailableLinterException' => __DIR__ . '/../..' . '/src/Linter/UnavailableLinterException.php',
'PhpCsFixer\\PharChecker' => __DIR__ . '/../..' . '/src/PharChecker.php',
'PhpCsFixer\\PharCheckerInterface' => __DIR__ . '/../..' . '/src/PharCheckerInterface.php',
'PhpCsFixer\\Preg' => __DIR__ . '/../..' . '/src/Preg.php',
'PhpCsFixer\\PregException' => __DIR__ . '/../..' . '/src/PregException.php',
'PhpCsFixer\\Report\\CheckstyleReporter' => __DIR__ . '/../..' . '/src/Report/CheckstyleReporter.php',
'PhpCsFixer\\Report\\GitlabReporter' => __DIR__ . '/../..' . '/src/Report/GitlabReporter.php',
'PhpCsFixer\\Report\\JsonReporter' => __DIR__ . '/../..' . '/src/Report/JsonReporter.php',
'PhpCsFixer\\Report\\JunitReporter' => __DIR__ . '/../..' . '/src/Report/JunitReporter.php',
'PhpCsFixer\\Report\\ReportSummary' => __DIR__ . '/../..' . '/src/Report/ReportSummary.php',
'PhpCsFixer\\Report\\ReporterFactory' => __DIR__ . '/../..' . '/src/Report/ReporterFactory.php',
'PhpCsFixer\\Report\\ReporterInterface' => __DIR__ . '/../..' . '/src/Report/ReporterInterface.php',
'PhpCsFixer\\Report\\TextReporter' => __DIR__ . '/../..' . '/src/Report/TextReporter.php',
'PhpCsFixer\\Report\\XmlReporter' => __DIR__ . '/../..' . '/src/Report/XmlReporter.php',
'PhpCsFixer\\RuleSet' => __DIR__ . '/../..' . '/src/RuleSet.php',
'PhpCsFixer\\RuleSetInterface' => __DIR__ . '/../..' . '/src/RuleSetInterface.php',
'PhpCsFixer\\RuleSet\\AbstractRuleSetDescription' => __DIR__ . '/../..' . '/src/RuleSet/AbstractRuleSetDescription.php',
'PhpCsFixer\\RuleSet\\RuleSet' => __DIR__ . '/../..' . '/src/RuleSet/RuleSet.php',
'PhpCsFixer\\RuleSet\\RuleSetDescriptionInterface' => __DIR__ . '/../..' . '/src/RuleSet/RuleSetDescriptionInterface.php',
'PhpCsFixer\\RuleSet\\RuleSetInterface' => __DIR__ . '/../..' . '/src/RuleSet/RuleSetInterface.php',
'PhpCsFixer\\RuleSet\\RuleSets' => __DIR__ . '/../..' . '/src/RuleSet/RuleSets.php',
'PhpCsFixer\\RuleSet\\Sets\\DoctrineAnnotationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/DoctrineAnnotationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP54MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP54MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP56MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP56MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP70MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP70MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP71MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP71MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP73MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP73MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP74MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP74MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP80MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHP80MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit30MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit32MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit35MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit43MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit48MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit50MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit52MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit54MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit55MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit56MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit57MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit60MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit75MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit84MigrationRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR12RiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PSR12RiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR12Set' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PSR12Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR1Set' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PSR1Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR2Set' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PSR2Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PhpCsFixerRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerSet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/PhpCsFixerSet.php',
'PhpCsFixer\\RuleSet\\Sets\\SymfonyRiskySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/SymfonyRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\SymfonySet' => __DIR__ . '/../..' . '/src/RuleSet/Sets/SymfonySet.php',
'PhpCsFixer\\Runner\\FileCachingLintingIterator' => __DIR__ . '/../..' . '/src/Runner/FileCachingLintingIterator.php',
'PhpCsFixer\\Runner\\FileFilterIterator' => __DIR__ . '/../..' . '/src/Runner/FileFilterIterator.php',
'PhpCsFixer\\Runner\\FileLintingIterator' => __DIR__ . '/../..' . '/src/Runner/FileLintingIterator.php',
'PhpCsFixer\\Runner\\Runner' => __DIR__ . '/../..' . '/src/Runner/Runner.php',
'PhpCsFixer\\StdinFileInfo' => __DIR__ . '/../..' . '/src/StdinFileInfo.php',
'PhpCsFixer\\Test\\AbstractFixerTestCase' => __DIR__ . '/../..' . '/src/Test/AbstractFixerTestCase.php',
'PhpCsFixer\\Test\\AbstractIntegrationTestCase' => __DIR__ . '/../..' . '/src/Test/AbstractIntegrationTestCase.php',
'PhpCsFixer\\Test\\AccessibleObject' => __DIR__ . '/../..' . '/src/Test/AccessibleObject.php',
'PhpCsFixer\\Test\\IntegrationCase' => __DIR__ . '/../..' . '/src/Test/IntegrationCase.php',
'PhpCsFixer\\Tests\\InterimTestCase' => __DIR__ . '/../..' . '/tests/TestCase.php',
'PhpCsFixer\\Tests\\TestCase' => __DIR__ . '/../..' . '/tests/TestCase.php',
'PhpCsFixer\\Tests\\Test\\AbstractFixerTestCase' => __DIR__ . '/../..' . '/tests/Test/AbstractFixerTestCase.php',
'PhpCsFixer\\Tests\\Test\\AbstractIntegrationCaseFactory' => __DIR__ . '/../..' . '/tests/Test/AbstractIntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\AbstractIntegrationTestCase' => __DIR__ . '/../..' . '/tests/Test/AbstractIntegrationTestCase.php',
'PhpCsFixer\\Tests\\Test\\Assert\\AssertTokensTrait' => __DIR__ . '/../..' . '/tests/Test/Assert/AssertTokensTrait.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCase' => __DIR__ . '/../..' . '/tests/Test/IntegrationCase.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCaseFactory' => __DIR__ . '/../..' . '/tests/Test/IntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCaseFactoryInterface' => __DIR__ . '/../..' . '/tests/Test/IntegrationCaseFactoryInterface.php',
'PhpCsFixer\\Tests\\Test\\InternalIntegrationCaseFactory' => __DIR__ . '/../..' . '/tests/Test/InternalIntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\IsIdenticalConstraint' => __DIR__ . '/../..' . '/tests/Test/IsIdenticalConstraint.php',
'PhpCsFixer\\Tokenizer\\AbstractTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/AbstractTransformer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\ArgumentAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\CaseAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceUseAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\StartEndTokenAwareAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\SwitchAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\TypeAnalysis' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ArgumentsAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\BlocksAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/BlocksAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ClassyAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/ClassyAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\CommentsAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/CommentsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\FunctionsAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/FunctionsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\GotoLabelAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\NamespaceUsesAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\NamespacesAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/NamespacesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ReferenceAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/ReferenceAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\SwitchAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/SwitchAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\WhitespacesAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\CT' => __DIR__ . '/../..' . '/src/Tokenizer/CT.php',
'PhpCsFixer\\Tokenizer\\CodeHasher' => __DIR__ . '/../..' . '/src/Tokenizer/CodeHasher.php',
'PhpCsFixer\\Tokenizer\\Generator\\NamespacedStringTokenGenerator' => __DIR__ . '/../..' . '/src/Tokenizer/Generator/NamespacedStringTokenGenerator.php',
'PhpCsFixer\\Tokenizer\\Resolver\\TypeShortNameResolver' => __DIR__ . '/../..' . '/src/Tokenizer/Resolver/TypeShortNameResolver.php',
'PhpCsFixer\\Tokenizer\\Token' => __DIR__ . '/../..' . '/src/Tokenizer/Token.php',
'PhpCsFixer\\Tokenizer\\Tokens' => __DIR__ . '/../..' . '/src/Tokenizer/Tokens.php',
'PhpCsFixer\\Tokenizer\\TokensAnalyzer' => __DIR__ . '/../..' . '/src/Tokenizer/TokensAnalyzer.php',
'PhpCsFixer\\Tokenizer\\TransformerInterface' => __DIR__ . '/../..' . '/src/Tokenizer/TransformerInterface.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ArrayTypehintTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/ArrayTypehintTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\AttributeTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/AttributeTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\BraceClassInstantiationTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ClassConstantTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/ClassConstantTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ConstructorPromotionTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\CurlyBraceTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/CurlyBraceTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ImportTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/ImportTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NameQualifiedTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/NameQualifiedTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NamedArgumentTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/NamedArgumentTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NamespaceOperatorTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NullableTypeTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/NullableTypeTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ReturnRefTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/ReturnRefTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\SquareBraceTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/SquareBraceTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\TypeAlternationTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/TypeAlternationTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\TypeColonTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/TypeColonTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\UseTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/UseTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\WhitespacyCommentTransformer' => __DIR__ . '/../..' . '/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformers' => __DIR__ . '/../..' . '/src/Tokenizer/Transformers.php',
'PhpCsFixer\\ToolInfo' => __DIR__ . '/../..' . '/src/ToolInfo.php',
'PhpCsFixer\\ToolInfoInterface' => __DIR__ . '/../..' . '/src/ToolInfoInterface.php',
'PhpCsFixer\\Utils' => __DIR__ . '/../..' . '/src/Utils.php',
'PhpCsFixer\\WhitespacesFixerConfig' => __DIR__ . '/../..' . '/src/WhitespacesFixerConfig.php',
'PhpCsFixer\\WordMatcher' => __DIR__ . '/../..' . '/src/WordMatcher.php',
'Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerAwareInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareInterface.php',
'Psr\\Log\\LoggerAwareTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareTrait.php',
'Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/DummyTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\TestLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/TestLogger.php',
'SessionUpdateTimestampHandlerInterface' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php',
'Symfony\\Component\\Console\\Application' => __DIR__ . '/..' . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\CommandLoader\\CommandLoaderInterface' => __DIR__ . '/..' . '/symfony/console/CommandLoader/CommandLoaderInterface.php',
'Symfony\\Component\\Console\\CommandLoader\\ContainerCommandLoader' => __DIR__ . '/..' . '/symfony/console/CommandLoader/ContainerCommandLoader.php',
'Symfony\\Component\\Console\\CommandLoader\\FactoryCommandLoader' => __DIR__ . '/..' . '/symfony/console/CommandLoader/FactoryCommandLoader.php',
'Symfony\\Component\\Console\\Command\\Command' => __DIR__ . '/..' . '/symfony/console/Command/Command.php',
'Symfony\\Component\\Console\\Command\\HelpCommand' => __DIR__ . '/..' . '/symfony/console/Command/HelpCommand.php',
'Symfony\\Component\\Console\\Command\\ListCommand' => __DIR__ . '/..' . '/symfony/console/Command/ListCommand.php',
'Symfony\\Component\\Console\\Command\\LockableTrait' => __DIR__ . '/..' . '/symfony/console/Command/LockableTrait.php',
'Symfony\\Component\\Console\\ConsoleEvents' => __DIR__ . '/..' . '/symfony/console/ConsoleEvents.php',
'Symfony\\Component\\Console\\DependencyInjection\\AddConsoleCommandPass' => __DIR__ . '/..' . '/symfony/console/DependencyInjection/AddConsoleCommandPass.php',
'Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => __DIR__ . '/..' . '/symfony/console/Descriptor/ApplicationDescription.php',
'Symfony\\Component\\Console\\Descriptor\\Descriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/Descriptor.php',
'Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => __DIR__ . '/..' . '/symfony/console/Descriptor/DescriptorInterface.php',
'Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/JsonDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/MarkdownDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/TextDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/XmlDescriptor.php',
'Symfony\\Component\\Console\\EventListener\\ErrorListener' => __DIR__ . '/..' . '/symfony/console/EventListener/ErrorListener.php',
'Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleCommandEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleErrorEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleErrorEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleExceptionEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleExceptionEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleTerminateEvent.php',
'Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => __DIR__ . '/..' . '/symfony/console/Exception/CommandNotFoundException.php',
'Symfony\\Component\\Console\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/console/Exception/ExceptionInterface.php',
'Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Console\\Exception\\InvalidOptionException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidOptionException.php',
'Symfony\\Component\\Console\\Exception\\LogicException' => __DIR__ . '/..' . '/symfony/console/Exception/LogicException.php',
'Symfony\\Component\\Console\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/console/Exception/RuntimeException.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatter' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatter.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyle.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleStack.php',
'Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DebugFormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\DescriptorHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DescriptorHelper.php',
'Symfony\\Component\\Console\\Helper\\FormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/FormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\Helper' => __DIR__ . '/..' . '/symfony/console/Helper/Helper.php',
'Symfony\\Component\\Console\\Helper\\HelperInterface' => __DIR__ . '/..' . '/symfony/console/Helper/HelperInterface.php',
'Symfony\\Component\\Console\\Helper\\HelperSet' => __DIR__ . '/..' . '/symfony/console/Helper/HelperSet.php',
'Symfony\\Component\\Console\\Helper\\InputAwareHelper' => __DIR__ . '/..' . '/symfony/console/Helper/InputAwareHelper.php',
'Symfony\\Component\\Console\\Helper\\ProcessHelper' => __DIR__ . '/..' . '/symfony/console/Helper/ProcessHelper.php',
'Symfony\\Component\\Console\\Helper\\ProgressBar' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressBar.php',
'Symfony\\Component\\Console\\Helper\\ProgressIndicator' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressIndicator.php',
'Symfony\\Component\\Console\\Helper\\QuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/QuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/SymfonyQuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\Table' => __DIR__ . '/..' . '/symfony/console/Helper/Table.php',
'Symfony\\Component\\Console\\Helper\\TableCell' => __DIR__ . '/..' . '/symfony/console/Helper/TableCell.php',
'Symfony\\Component\\Console\\Helper\\TableSeparator' => __DIR__ . '/..' . '/symfony/console/Helper/TableSeparator.php',
'Symfony\\Component\\Console\\Helper\\TableStyle' => __DIR__ . '/..' . '/symfony/console/Helper/TableStyle.php',
'Symfony\\Component\\Console\\Input\\ArgvInput' => __DIR__ . '/..' . '/symfony/console/Input/ArgvInput.php',
'Symfony\\Component\\Console\\Input\\ArrayInput' => __DIR__ . '/..' . '/symfony/console/Input/ArrayInput.php',
'Symfony\\Component\\Console\\Input\\Input' => __DIR__ . '/..' . '/symfony/console/Input/Input.php',
'Symfony\\Component\\Console\\Input\\InputArgument' => __DIR__ . '/..' . '/symfony/console/Input/InputArgument.php',
'Symfony\\Component\\Console\\Input\\InputAwareInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputAwareInterface.php',
'Symfony\\Component\\Console\\Input\\InputDefinition' => __DIR__ . '/..' . '/symfony/console/Input/InputDefinition.php',
'Symfony\\Component\\Console\\Input\\InputInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputInterface.php',
'Symfony\\Component\\Console\\Input\\InputOption' => __DIR__ . '/..' . '/symfony/console/Input/InputOption.php',
'Symfony\\Component\\Console\\Input\\StreamableInputInterface' => __DIR__ . '/..' . '/symfony/console/Input/StreamableInputInterface.php',
'Symfony\\Component\\Console\\Input\\StringInput' => __DIR__ . '/..' . '/symfony/console/Input/StringInput.php',
'Symfony\\Component\\Console\\Logger\\ConsoleLogger' => __DIR__ . '/..' . '/symfony/console/Logger/ConsoleLogger.php',
'Symfony\\Component\\Console\\Output\\BufferedOutput' => __DIR__ . '/..' . '/symfony/console/Output/BufferedOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutput' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutputInterface.php',
'Symfony\\Component\\Console\\Output\\NullOutput' => __DIR__ . '/..' . '/symfony/console/Output/NullOutput.php',
'Symfony\\Component\\Console\\Output\\Output' => __DIR__ . '/..' . '/symfony/console/Output/Output.php',
'Symfony\\Component\\Console\\Output\\OutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/OutputInterface.php',
'Symfony\\Component\\Console\\Output\\StreamOutput' => __DIR__ . '/..' . '/symfony/console/Output/StreamOutput.php',
'Symfony\\Component\\Console\\Question\\ChoiceQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ChoiceQuestion.php',
'Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ConfirmationQuestion.php',
'Symfony\\Component\\Console\\Question\\Question' => __DIR__ . '/..' . '/symfony/console/Question/Question.php',
'Symfony\\Component\\Console\\Style\\OutputStyle' => __DIR__ . '/..' . '/symfony/console/Style/OutputStyle.php',
'Symfony\\Component\\Console\\Style\\StyleInterface' => __DIR__ . '/..' . '/symfony/console/Style/StyleInterface.php',
'Symfony\\Component\\Console\\Style\\SymfonyStyle' => __DIR__ . '/..' . '/symfony/console/Style/SymfonyStyle.php',
'Symfony\\Component\\Console\\Terminal' => __DIR__ . '/..' . '/symfony/console/Terminal.php',
'Symfony\\Component\\Console\\Tester\\ApplicationTester' => __DIR__ . '/..' . '/symfony/console/Tester/ApplicationTester.php',
'Symfony\\Component\\Console\\Tester\\CommandTester' => __DIR__ . '/..' . '/symfony/console/Tester/CommandTester.php',
'Symfony\\Component\\Debug\\BufferingLogger' => __DIR__ . '/..' . '/symfony/debug/BufferingLogger.php',
'Symfony\\Component\\Debug\\Debug' => __DIR__ . '/..' . '/symfony/debug/Debug.php',
'Symfony\\Component\\Debug\\DebugClassLoader' => __DIR__ . '/..' . '/symfony/debug/DebugClassLoader.php',
'Symfony\\Component\\Debug\\ErrorHandler' => __DIR__ . '/..' . '/symfony/debug/ErrorHandler.php',
'Symfony\\Component\\Debug\\ExceptionHandler' => __DIR__ . '/..' . '/symfony/debug/ExceptionHandler.php',
'Symfony\\Component\\Debug\\Exception\\ClassNotFoundException' => __DIR__ . '/..' . '/symfony/debug/Exception/ClassNotFoundException.php',
'Symfony\\Component\\Debug\\Exception\\ContextErrorException' => __DIR__ . '/..' . '/symfony/debug/Exception/ContextErrorException.php',
'Symfony\\Component\\Debug\\Exception\\FatalErrorException' => __DIR__ . '/..' . '/symfony/debug/Exception/FatalErrorException.php',
'Symfony\\Component\\Debug\\Exception\\FatalThrowableError' => __DIR__ . '/..' . '/symfony/debug/Exception/FatalThrowableError.php',
'Symfony\\Component\\Debug\\Exception\\FlattenException' => __DIR__ . '/..' . '/symfony/debug/Exception/FlattenException.php',
'Symfony\\Component\\Debug\\Exception\\OutOfMemoryException' => __DIR__ . '/..' . '/symfony/debug/Exception/OutOfMemoryException.php',
'Symfony\\Component\\Debug\\Exception\\SilencedErrorContext' => __DIR__ . '/..' . '/symfony/debug/Exception/SilencedErrorContext.php',
'Symfony\\Component\\Debug\\Exception\\UndefinedFunctionException' => __DIR__ . '/..' . '/symfony/debug/Exception/UndefinedFunctionException.php',
'Symfony\\Component\\Debug\\Exception\\UndefinedMethodException' => __DIR__ . '/..' . '/symfony/debug/Exception/UndefinedMethodException.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\ClassNotFoundFatalErrorHandler' => __DIR__ . '/..' . '/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\FatalErrorHandlerInterface' => __DIR__ . '/..' . '/symfony/debug/FatalErrorHandler/FatalErrorHandlerInterface.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\UndefinedFunctionFatalErrorHandler' => __DIR__ . '/..' . '/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\UndefinedMethodFatalErrorHandler' => __DIR__ . '/..' . '/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php',
'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/ContainerAwareEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/WrappedListener.php',
'Symfony\\Component\\EventDispatcher\\DependencyInjection\\RegisterListenersPass' => __DIR__ . '/..' . '/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php',
'Symfony\\Component\\EventDispatcher\\Event' => __DIR__ . '/..' . '/symfony/event-dispatcher/Event.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventSubscriberInterface.php',
'Symfony\\Component\\EventDispatcher\\GenericEvent' => __DIR__ . '/..' . '/symfony/event-dispatcher/GenericEvent.php',
'Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/ImmutableEventDispatcher.php',
'Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/ExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/FileNotFoundException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Filesystem' => __DIR__ . '/..' . '/symfony/filesystem/Filesystem.php',
'Symfony\\Component\\Filesystem\\LockHandler' => __DIR__ . '/..' . '/symfony/filesystem/LockHandler.php',
'Symfony\\Component\\Finder\\Comparator\\Comparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/Comparator.php',
'Symfony\\Component\\Finder\\Comparator\\DateComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/DateComparator.php',
'Symfony\\Component\\Finder\\Comparator\\NumberComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/NumberComparator.php',
'Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => __DIR__ . '/..' . '/symfony/finder/Exception/AccessDeniedException.php',
'Symfony\\Component\\Finder\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/finder/Exception/ExceptionInterface.php',
'Symfony\\Component\\Finder\\Finder' => __DIR__ . '/..' . '/symfony/finder/Finder.php',
'Symfony\\Component\\Finder\\Glob' => __DIR__ . '/..' . '/symfony/finder/Glob.php',
'Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/CustomFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/PathFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SortableIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SortableIterator.php',
'Symfony\\Component\\Finder\\SplFileInfo' => __DIR__ . '/..' . '/symfony/finder/SplFileInfo.php',
'Symfony\\Component\\OptionsResolver\\Debug\\OptionsResolverIntrospector' => __DIR__ . '/..' . '/symfony/options-resolver/Debug/OptionsResolverIntrospector.php',
'Symfony\\Component\\OptionsResolver\\Exception\\AccessException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/AccessException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/ExceptionInterface.php',
'Symfony\\Component\\OptionsResolver\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidArgumentException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\MissingOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/MissingOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\NoConfigurationException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoConfigurationException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\NoSuchOptionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoSuchOptionException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\OptionDefinitionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/OptionDefinitionException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/UndefinedOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Options' => __DIR__ . '/..' . '/symfony/options-resolver/Options.php',
'Symfony\\Component\\OptionsResolver\\OptionsResolver' => __DIR__ . '/..' . '/symfony/options-resolver/OptionsResolver.php',
'Symfony\\Component\\Process\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/process/Exception/ExceptionInterface.php',
'Symfony\\Component\\Process\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/process/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Process\\Exception\\LogicException' => __DIR__ . '/..' . '/symfony/process/Exception/LogicException.php',
'Symfony\\Component\\Process\\Exception\\ProcessFailedException' => __DIR__ . '/..' . '/symfony/process/Exception/ProcessFailedException.php',
'Symfony\\Component\\Process\\Exception\\ProcessTimedOutException' => __DIR__ . '/..' . '/symfony/process/Exception/ProcessTimedOutException.php',
'Symfony\\Component\\Process\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/process/Exception/RuntimeException.php',
'Symfony\\Component\\Process\\ExecutableFinder' => __DIR__ . '/..' . '/symfony/process/ExecutableFinder.php',
'Symfony\\Component\\Process\\InputStream' => __DIR__ . '/..' . '/symfony/process/InputStream.php',
'Symfony\\Component\\Process\\PhpExecutableFinder' => __DIR__ . '/..' . '/symfony/process/PhpExecutableFinder.php',
'Symfony\\Component\\Process\\PhpProcess' => __DIR__ . '/..' . '/symfony/process/PhpProcess.php',
'Symfony\\Component\\Process\\Pipes\\AbstractPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/AbstractPipes.php',
'Symfony\\Component\\Process\\Pipes\\PipesInterface' => __DIR__ . '/..' . '/symfony/process/Pipes/PipesInterface.php',
'Symfony\\Component\\Process\\Pipes\\UnixPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/UnixPipes.php',
'Symfony\\Component\\Process\\Pipes\\WindowsPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/WindowsPipes.php',
'Symfony\\Component\\Process\\Process' => __DIR__ . '/..' . '/symfony/process/Process.php',
'Symfony\\Component\\Process\\ProcessBuilder' => __DIR__ . '/..' . '/symfony/process/ProcessBuilder.php',
'Symfony\\Component\\Process\\ProcessUtils' => __DIR__ . '/..' . '/symfony/process/ProcessUtils.php',
'Symfony\\Component\\Stopwatch\\Section' => __DIR__ . '/..' . '/symfony/stopwatch/Section.php',
'Symfony\\Component\\Stopwatch\\Stopwatch' => __DIR__ . '/..' . '/symfony/stopwatch/Stopwatch.php',
'Symfony\\Component\\Stopwatch\\StopwatchEvent' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchEvent.php',
'Symfony\\Component\\Stopwatch\\StopwatchPeriod' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchPeriod.php',
'Symfony\\Polyfill\\Ctype\\Ctype' => __DIR__ . '/..' . '/symfony/polyfill-ctype/Ctype.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php',
'Symfony\\Polyfill\\Php70\\Php70' => __DIR__ . '/..' . '/symfony/polyfill-php70/Php70.php',
'Symfony\\Polyfill\\Php72\\Php72' => __DIR__ . '/..' . '/symfony/polyfill-php72/Php72.php',
'TypeError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/TypeError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e::$classMap;
}, null, ClassLoader::class);
}
}
<?php
namespace Composer\XdebugHandler;
use Psr\Log\LoggerInterface;
class XdebugHandler
{
const SUFFIX_ALLOW = '_ALLOW_XDEBUG';
const SUFFIX_INIS = '_ORIGINAL_INIS';
const RESTART_ID = 'internal';
const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS';
const DEBUG = 'XDEBUG_HANDLER_DEBUG';
protected $tmpIni;
private static $inRestart;
private static $name;
private static $skipped;
private $cli;
private $colorOption;
private $debug;
private $envAllowXdebug;
private $envOriginalInis;
private $loaded;
private $persistent;
private $script;
private $statusWriter;
public function __construct($envPrefix, $colorOption = '')
{
if (!is_string($envPrefix) || empty($envPrefix) || !is_string($colorOption)) {
throw new \RuntimeException('Invalid constructor parameter');
}
self::$name = strtoupper($envPrefix);
$this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW;
$this->envOriginalInis = self::$name.self::SUFFIX_INIS;
$this->colorOption = $colorOption;
if (extension_loaded('xdebug')) {
$ext = new \ReflectionExtension('xdebug');
$this->loaded = $ext->getVersion() ?: 'unknown';
}
if ($this->cli = PHP_SAPI === 'cli') {
$this->debug = getenv(self::DEBUG);
}
$this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug);
}
public function setLogger(LoggerInterface $logger)
{
$this->statusWriter->setLogger($logger);
return $this;
}
public function setMainScript($script)
{
$this->script = $script;
return $this;
}
public function setPersistent()
{
$this->persistent = true;
return $this;
}
public function check()
{
$this->notify(Status::CHECK, $this->loaded);
$envArgs = explode('|', (string) getenv($this->envAllowXdebug));
if (empty($envArgs[0]) && $this->requiresRestart((bool) $this->loaded)) {
$this->notify(Status::RESTART);
if ($this->prepareRestart()) {
$command = $this->getCommand();
$this->restart($command);
}
return;
}
if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) {
$this->notify(Status::RESTARTED);
Process::setEnv($this->envAllowXdebug);
self::$inRestart = true;
if (!$this->loaded) {
self::$skipped = $envArgs[1];
}
$this->tryEnableSignals();
$this->setEnvRestartSettings($envArgs);
return;
}
$this->notify(Status::NORESTART);
if ($settings = self::getRestartSettings()) {
$this->syncSettings($settings);
}
}
public static function getAllIniFiles()
{
if (!empty(self::$name)) {
$env = getenv(self::$name.self::SUFFIX_INIS);
if (false !== $env) {
return explode(PATH_SEPARATOR, $env);
}
}
$paths = array((string) php_ini_loaded_file());
if ($scanned = php_ini_scanned_files()) {
$paths = array_merge($paths, array_map('trim', explode(',', $scanned)));
}
return $paths;
}
public static function getRestartSettings()
{
$envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS));
if (count($envArgs) !== 6
|| (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) {
return;
}
return array(
'tmpIni' => $envArgs[0],
'scannedInis' => (bool) $envArgs[1],
'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2],
'phprc' => '*' === $envArgs[3] ? false : $envArgs[3],
'inis' => explode(PATH_SEPARATOR, $envArgs[4]),
'skipped' => $envArgs[5],
);
}
public static function getSkippedVersion()
{
return (string) self::$skipped;
}
protected function requiresRestart($isLoaded)
{
return $isLoaded;
}
protected function restart($command)
{
$this->doRestart($command);
}
private function doRestart($command)
{
$this->tryEnableSignals();
$this->notify(Status::RESTARTING, $command);
if (function_exists('proc_open')) {
if (defined('PHP_WINDOWS_VERSION_BUILD') && PHP_VERSION_ID < 80000) {
$command = '"'.$command.'"';
}
$process = proc_open($command, array(), $pipes);
if (is_resource($process)) {
$exitCode = proc_close($process);
}
} else {
passthru($command, $exitCode);
}
if (!isset($exitCode)) {
$this->notify(Status::ERROR, 'Unable to restart process');
$exitCode = -1;
} else {
$this->notify(Status::INFO, 'Restarted process exited '.$exitCode);
}
if ($this->debug === '2') {
$this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni);
} else {
@unlink($this->tmpIni);
}
exit($exitCode);
}
private function prepareRestart()
{
$error = '';
$iniFiles = self::getAllIniFiles();
$scannedInis = count($iniFiles) > 1;
$tmpDir = sys_get_temp_dir();
if (!$this->cli) {
$error = 'Unsupported SAPI: '.PHP_SAPI;
} elseif (!defined('PHP_BINARY')) {
$error = 'PHP version is too old: '.PHP_VERSION;
} elseif (!$this->checkConfiguration($info)) {
$error = $info;
} elseif (!$this->checkScanDirConfig()) {
$error = 'PHP version does not report scanned inis: '.PHP_VERSION;
} elseif (!$this->checkMainScript()) {
$error = 'Unable to access main script: '.$this->script;
} elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) {
$error = $error ?: 'Unable to create temp ini file at: '.$tmpDir;
} elseif (!$this->setEnvironment($scannedInis, $iniFiles)) {
$error = 'Unable to set environment variables';
}
if ($error) {
$this->notify(Status::ERROR, $error);
}
return empty($error);
}
private function writeTmpIni(array $iniFiles, $tmpDir, &$error)
{
if (!$this->tmpIni = @tempnam($tmpDir, '')) {
return false;
}
if (empty($iniFiles[0])) {
array_shift($iniFiles);
}
$content = '';
$regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
foreach ($iniFiles as $file) {
if (($data = @file_get_contents($file)) === false) {
$error = 'Unable to read ini: '.$file;
return false;
}
$content .= preg_replace($regex, ';$1', $data).PHP_EOL;
}
if ($config = parse_ini_string($content)) {
$loaded = ini_get_all(null, false);
$content .= $this->mergeLoadedConfig($loaded, $config);
}
$content .= 'opcache.enable_cli=0'.PHP_EOL;
return @file_put_contents($this->tmpIni, $content);
}
private function getCommand()
{
$php = array(PHP_BINARY);
$args = array_slice($_SERVER['argv'], 1);
if (!$this->persistent) {
array_push($php, '-n', '-c', $this->tmpIni);
}
if (defined('STDOUT') && Process::supportsColor(STDOUT)) {
$args = Process::addColorOption($args, $this->colorOption);
}
$args = array_merge($php, array($this->script), $args);
$cmd = Process::escape(array_shift($args), true, true);
foreach ($args as $arg) {
$cmd .= ' '.Process::escape($arg);
}
return $cmd;
}
private function setEnvironment($scannedInis, array $iniFiles)
{
$scanDir = getenv('PHP_INI_SCAN_DIR');
$phprc = getenv('PHPRC');
if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) {
return false;
}
if ($this->persistent) {
if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$this->tmpIni)) {
return false;
}
}
$envArgs = array(
self::RESTART_ID,
$this->loaded,
(int) $scannedInis,
false === $scanDir ? '*' : $scanDir,
false === $phprc ? '*' : $phprc,
);
return putenv($this->envAllowXdebug.'='.implode('|', $envArgs));
}
private function notify($op, $data = null)
{
$this->statusWriter->report($op, $data);
}
private function mergeLoadedConfig(array $loadedConfig, array $iniConfig)
{
$content = '';
foreach ($loadedConfig as $name => $value) {
if (!is_string($value)
|| strpos($name, 'xdebug') === 0
|| $name === 'apc.mmap_file_mask') {
continue;
}
if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) {
$content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL;
}
}
return $content;
}
private function checkMainScript()
{
if (null !== $this->script) {
return file_exists($this->script) || '--' === $this->script;
}
if (file_exists($this->script = $_SERVER['argv'][0])) {
return true;
}
$options = PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS : false;
$trace = debug_backtrace($options);
if (($main = end($trace)) && isset($main['file'])) {
return file_exists($this->script = $main['file']);
}
return false;
}
private function setEnvRestartSettings($envArgs)
{
$settings = array(
php_ini_loaded_file(),
$envArgs[2],
$envArgs[3],
$envArgs[4],
getenv($this->envOriginalInis),
self::$skipped,
);
Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings));
}
private function syncSettings(array $settings)
{
if (false === getenv($this->envOriginalInis)) {
Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis']));
}
self::$skipped = $settings['skipped'];
$this->notify(Status::INFO, 'Process called with existing restart settings');
}
private function checkScanDirConfig()
{
return !(getenv('PHP_INI_SCAN_DIR')
&& !PHP_CONFIG_FILE_SCAN_DIR
&& (PHP_VERSION_ID < 70113
|| PHP_VERSION_ID === 70200));
}
private function checkConfiguration(&$info)
{
if (false !== strpos(ini_get('disable_functions'), 'passthru')) {
$info = 'passthru function is disabled';
return false;
}
if (extension_loaded('uopz') && !ini_get('uopz.disable')) {
if (function_exists('uopz_allow_exit')) {
@uopz_allow_exit(true);
} else {
$info = 'uopz extension is not compatible';
return false;
}
}
return true;
}
private function tryEnableSignals()
{
if (!function_exists('pcntl_async_signals') || !function_exists('pcntl_signal')) {
return;
}
pcntl_async_signals(true);
$message = 'Async signals enabled';
if (!self::$inRestart) {
pcntl_signal(SIGINT, SIG_IGN);
$message .= ' (SIGINT = SIG_IGN)';
} elseif (is_int(pcntl_signal_get_handler(SIGINT))) {
pcntl_signal(SIGINT, SIG_DFL);
$message .= ' (SIGINT = SIG_DFL)';
}
$this->notify(Status::INFO, $message);
}
}
<?php
namespace Composer\XdebugHandler;
class PhpConfig
{
public function useOriginal()
{
$this->getDataAndReset();
return array();
}
public function useStandard()
{
if ($data = $this->getDataAndReset()) {
return array('-n', '-c', $data['tmpIni']);
}
return array();
}
public function usePersistent()
{
if ($data = $this->getDataAndReset()) {
Process::setEnv('PHPRC', $data['tmpIni']);
Process::setEnv('PHP_INI_SCAN_DIR', '');
}
return array();
}
private function getDataAndReset()
{
if ($data = XdebugHandler::getRestartSettings()) {
Process::setEnv('PHPRC', $data['phprc']);
Process::setEnv('PHP_INI_SCAN_DIR', $data['scanDir']);
}
return $data;
}
}
<?php
namespace Composer\XdebugHandler;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class Status
{
const ENV_RESTART = 'XDEBUG_HANDLER_RESTART';
const CHECK = 'Check';
const ERROR = 'Error';
const INFO = 'Info';
const NORESTART = 'NoRestart';
const RESTART = 'Restart';
const RESTARTING = 'Restarting';
const RESTARTED = 'Restarted';
private $debug;
private $envAllowXdebug;
private $loaded;
private $logger;
private $time;
public function __construct($envAllowXdebug, $debug)
{
$start = getenv(self::ENV_RESTART);
Process::setEnv(self::ENV_RESTART);
$this->time = $start ? round((microtime(true) - $start) * 1000) : 0;
$this->envAllowXdebug = $envAllowXdebug;
$this->debug = $debug && defined('STDERR');
}
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function report($op, $data)
{
if ($this->logger || $this->debug) {
call_user_func(array($this, 'report'.$op), $data);
}
}
private function output($text, $level = null)
{
if ($this->logger) {
$this->logger->log($level ?: LogLevel::DEBUG, $text);
}
if ($this->debug) {
fwrite(STDERR, sprintf('xdebug-handler[%d] %s', getmypid(), $text.PHP_EOL));
}
}
private function reportCheck($loaded)
{
$this->loaded = $loaded;
$this->output('Checking '.$this->envAllowXdebug);
}
private function reportError($error)
{
$this->output(sprintf('No restart (%s)', $error), LogLevel::WARNING);
}
private function reportInfo($info)
{
$this->output($info);
}
private function reportNoRestart()
{
$this->output($this->getLoadedMessage());
if ($this->loaded) {
$text = sprintf('No restart (%s)', $this->getEnvAllow());
if (!getenv($this->envAllowXdebug)) {
$text .= ' Allowed by application';
}
$this->output($text);
}
}
private function reportRestart()
{
$this->output($this->getLoadedMessage());
Process::setEnv(self::ENV_RESTART, (string) microtime(true));
}
private function reportRestarted()
{
$loaded = $this->getLoadedMessage();
$text = sprintf('Restarted (%d ms). %s', $this->time, $loaded);
$level = $this->loaded ? LogLevel::WARNING : null;
$this->output($text, $level);
}
private function reportRestarting($command)
{
$text = sprintf('Process restarting (%s)', $this->getEnvAllow());
$this->output($text);
$text = 'Running '.$command;
$this->output($text);
}
private function getEnvAllow()
{
return $this->envAllowXdebug.'='.getenv($this->envAllowXdebug);
}
private function getLoadedMessage()
{
$loaded = $this->loaded ? sprintf('loaded (%s)', $this->loaded) : 'not loaded';
return 'The Xdebug extension is '.$loaded;
}
}
<?php
namespace Composer\XdebugHandler;
class Process
{
public static function addColorOption(array $args, $colorOption)
{
if (!$colorOption
|| in_array($colorOption, $args)
|| !preg_match('/^--([a-z]+$)|(^--[a-z]+=)/', $colorOption, $matches)) {
return $args;
}
if (isset($matches[2])) {
if (false !== ($index = array_search($matches[2].'auto', $args))) {
$args[$index] = $colorOption;
return $args;
} elseif (preg_grep('/^'.$matches[2].'/', $args)) {
return $args;
}
} elseif (in_array('--no-'.$matches[1], $args)) {
return $args;
}
if (false !== getenv('NO_COLOR')) {
return $args;
}
if (false !== ($index = array_search('--', $args))) {
array_splice($args, $index, 0, $colorOption);
} else {
$args[] = $colorOption;
}
return $args;
}
/**
@blueyonder
*/
public static function escape($arg, $meta = true, $module = false)
{
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
return "'".str_replace("'", "'\\''", $arg)."'";
}
$quote = strpbrk($arg, " \t") !== false || $arg === '';
$arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
if ($meta) {
$meta = $dquotes || preg_match('/%[^%]+%/', $arg);
if (!$meta) {
$quote = $quote || strpbrk($arg, '^&|<>()') !== false;
} elseif ($module && !$dquotes && $quote) {
$meta = false;
}
}
if ($quote) {
$arg = '"'.preg_replace('/(\\\\*)$/', '$1$1', $arg).'"';
}
if ($meta) {
$arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg);
}
return $arg;
}
public static function supportsColor($output)
{
if ('Hyper' === getenv('TERM_PROGRAM')) {
return true;
}
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
return (function_exists('sapi_windows_vt100_support')
&& sapi_windows_vt100_support($output))
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
if (function_exists('stream_isatty')) {
return stream_isatty($output);
}
if (function_exists('posix_isatty')) {
return posix_isatty($output);
}
$stat = fstat($output);
return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
}
public static function setEnv($name, $value = false)
{
$unset = false === $value;
if (!putenv($unset ? $name : $name.'='.$value)) {
return false;
}
if ($unset) {
unset($_SERVER[$name]);
} else {
$_SERVER[$name] = $value;
}
if (false !== stripos((string) ini_get('variables_order'), 'E')) {
if ($unset) {
unset($_ENV[$name]);
} else {
$_ENV[$name] = $value;
}
}
return true;
}
}
<?php
namespace Composer;
use Composer\Semver\VersionParser;
class InstalledVersions
{
private static $installed = array (
'root' =>
array (
'pretty_version' => '2.18.x-dev',
'version' => '2.18.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '18f8c9d184ba777380794a389fabc179896ba913',
'name' => 'friendsofphp/php-cs-fixer',
),
'versions' =>
array (
'composer/semver' =>
array (
'pretty_version' => '3.2.4',
'version' => '3.2.4.0',
'aliases' =>
array (
),
'reference' => 'a02fdf930a3c1c3ed3a49b5f63859c0c20e10464',
),
'composer/xdebug-handler' =>
array (
'pretty_version' => '1.4.5',
'version' => '1.4.5.0',
'aliases' =>
array (
),
'reference' => 'f28d44c286812c714741478d968104c5e604a1d4',
),
'doctrine/annotations' =>
array (
'pretty_version' => 'v1.4.0',
'version' => '1.4.0.0',
'aliases' =>
array (
),
'reference' => '54cacc9b81758b14e3ce750f205a393d52339e97',
),
'doctrine/lexer' =>
array (
'pretty_version' => '1.0.2',
'version' => '1.0.2.0',
'aliases' =>
array (
),
'reference' => '1febd6c3ef84253d7c815bed85fc622ad207a9f8',
),
'friendsofphp/php-cs-fixer' =>
array (
'pretty_version' => '2.18.x-dev',
'version' => '2.18.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '18f8c9d184ba777380794a389fabc179896ba913',
),
'paragonie/random_compat' =>
array (
'pretty_version' => 'v2.0.19',
'version' => '2.0.19.0',
'aliases' =>
array (
),
'reference' => '446fc9faa5c2a9ddf65eb7121c0af7e857295241',
),
'php-cs-fixer/diff' =>
array (
'pretty_version' => 'v1.3.1',
'version' => '1.3.1.0',
'aliases' =>
array (
),
'reference' => 'dbd31aeb251639ac0b9e7e29405c1441907f5759',
),
'psr/log' =>
array (
'pretty_version' => '1.1.3',
'version' => '1.1.3.0',
'aliases' =>
array (
),
'reference' => '0f73288fd15629204f9d42b7055f72dacbe811fc',
),
'psr/log-implementation' =>
array (
'provided' =>
array (
0 => '1.0',
),
),
'symfony/console' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'a10b1da6fc93080c180bba7219b5ff5b7518fe81',
),
'symfony/debug' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'ab42889de57fdfcfcc0759ab102e2fd4ea72dcae',
),
'symfony/event-dispatcher' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => '31fde73757b6bad247c54597beef974919ec6860',
),
'symfony/filesystem' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'e58d7841cddfed6e846829040dca2cca0ebbbbb3',
),
'symfony/finder' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'b6b6ad3db3edb1b4b1c1896b1975fb684994de6e',
),
'symfony/options-resolver' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'c7efc97a47b2ebaabc19d5b6c6b50f5c37c92744',
),
'symfony/polyfill-ctype' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'aed596913b70fae57be53d86faa2e9ef85a2297b',
),
'symfony/polyfill-mbstring' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'b5f7b932ee6fa802fc792eabd77c4c88084517ce',
),
'symfony/polyfill-php70' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => '3fe414077251a81a1b15b1c709faf5c2fbae3d4e',
),
'symfony/polyfill-php72' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'beecef6b463b06954638f02378f52496cb84bacc',
),
'symfony/process' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'b8648cf1d5af12a44a51d07ef9bf980921f15fca',
),
'symfony/stopwatch' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => '298b81faad4ce60e94466226b2abbb8c9bca7462',
),
),
);
public static function getInstalledPackages()
{
return array_keys(self::$installed['versions']);
}
public static function isInstalled($packageName)
{
return isset(self::$installed['versions'][$packageName]);
}
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
public static function getVersionRanges($packageName)
{
if (!isset(self::$installed['versions'][$packageName])) {
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
$ranges = array();
if (isset(self::$installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = self::$installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', self::$installed['versions'][$packageName])) {
$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', self::$installed['versions'][$packageName])) {
$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', self::$installed['versions'][$packageName])) {
$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
public static function getVersion($packageName)
{
if (!isset(self::$installed['versions'][$packageName])) {
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
if (!isset(self::$installed['versions'][$packageName]['version'])) {
return null;
}
return self::$installed['versions'][$packageName]['version'];
}
public static function getPrettyVersion($packageName)
{
if (!isset(self::$installed['versions'][$packageName])) {
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
if (!isset(self::$installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return self::$installed['versions'][$packageName]['pretty_version'];
}
public static function getReference($packageName)
{
if (!isset(self::$installed['versions'][$packageName])) {
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
if (!isset(self::$installed['versions'][$packageName]['reference'])) {
return null;
}
return self::$installed['versions'][$packageName]['reference'];
}
public static function getRootPackage()
{
return self::$installed['root'];
}
public static function getRawData()
{
return self::$installed;
}
public static function reload($data)
{
self::$installed = $data;
}
}
<?php
class ComposerAutoloaderInit9f0dd14c94ce02dc34a0e91e293e3b6e
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit9f0dd14c94ce02dc34a0e91e293e3b6e', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit9f0dd14c94ce02dc34a0e91e293e3b6e', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit9f0dd14c94ce02dc34a0e91e293e3b6e::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire9f0dd14c94ce02dc34a0e91e293e3b6e($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire9f0dd14c94ce02dc34a0e91e293e3b6e($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
<?php return array (
'root' =>
array (
'pretty_version' => '2.18.x-dev',
'version' => '2.18.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '18f8c9d184ba777380794a389fabc179896ba913',
'name' => 'friendsofphp/php-cs-fixer',
),
'versions' =>
array (
'composer/semver' =>
array (
'pretty_version' => '3.2.4',
'version' => '3.2.4.0',
'aliases' =>
array (
),
'reference' => 'a02fdf930a3c1c3ed3a49b5f63859c0c20e10464',
),
'composer/xdebug-handler' =>
array (
'pretty_version' => '1.4.5',
'version' => '1.4.5.0',
'aliases' =>
array (
),
'reference' => 'f28d44c286812c714741478d968104c5e604a1d4',
),
'doctrine/annotations' =>
array (
'pretty_version' => 'v1.4.0',
'version' => '1.4.0.0',
'aliases' =>
array (
),
'reference' => '54cacc9b81758b14e3ce750f205a393d52339e97',
),
'doctrine/lexer' =>
array (
'pretty_version' => '1.0.2',
'version' => '1.0.2.0',
'aliases' =>
array (
),
'reference' => '1febd6c3ef84253d7c815bed85fc622ad207a9f8',
),
'friendsofphp/php-cs-fixer' =>
array (
'pretty_version' => '2.18.x-dev',
'version' => '2.18.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '18f8c9d184ba777380794a389fabc179896ba913',
),
'paragonie/random_compat' =>
array (
'pretty_version' => 'v2.0.19',
'version' => '2.0.19.0',
'aliases' =>
array (
),
'reference' => '446fc9faa5c2a9ddf65eb7121c0af7e857295241',
),
'php-cs-fixer/diff' =>
array (
'pretty_version' => 'v1.3.1',
'version' => '1.3.1.0',
'aliases' =>
array (
),
'reference' => 'dbd31aeb251639ac0b9e7e29405c1441907f5759',
),
'psr/log' =>
array (
'pretty_version' => '1.1.3',
'version' => '1.1.3.0',
'aliases' =>
array (
),
'reference' => '0f73288fd15629204f9d42b7055f72dacbe811fc',
),
'psr/log-implementation' =>
array (
'provided' =>
array (
0 => '1.0',
),
),
'symfony/console' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'a10b1da6fc93080c180bba7219b5ff5b7518fe81',
),
'symfony/debug' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'ab42889de57fdfcfcc0759ab102e2fd4ea72dcae',
),
'symfony/event-dispatcher' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => '31fde73757b6bad247c54597beef974919ec6860',
),
'symfony/filesystem' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'e58d7841cddfed6e846829040dca2cca0ebbbbb3',
),
'symfony/finder' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'b6b6ad3db3edb1b4b1c1896b1975fb684994de6e',
),
'symfony/options-resolver' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'c7efc97a47b2ebaabc19d5b6c6b50f5c37c92744',
),
'symfony/polyfill-ctype' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'aed596913b70fae57be53d86faa2e9ef85a2297b',
),
'symfony/polyfill-mbstring' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'b5f7b932ee6fa802fc792eabd77c4c88084517ce',
),
'symfony/polyfill-php70' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => '3fe414077251a81a1b15b1c709faf5c2fbae3d4e',
),
'symfony/polyfill-php72' =>
array (
'pretty_version' => 'v1.19.0',
'version' => '1.19.0.0',
'aliases' =>
array (
),
'reference' => 'beecef6b463b06954638f02378f52496cb84bacc',
),
'symfony/process' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => 'b8648cf1d5af12a44a51d07ef9bf980921f15fca',
),
'symfony/stopwatch' =>
array (
'pretty_version' => 'v3.4.47',
'version' => '3.4.47.0',
'aliases' =>
array (
),
'reference' => '298b81faad4ce60e94466226b2abbb8c9bca7462',
),
),
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php',
'023d27dca8066ef29e6739335ea73bad' => $vendorDir . '/symfony/polyfill-php70/bootstrap.php',
'25072dd6e2470089de65ae7bf11d3109' => $vendorDir . '/symfony/polyfill-php72/bootstrap.php',
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php72\\' => array($vendorDir . '/symfony/polyfill-php72'),
'Symfony\\Polyfill\\Php70\\' => array($vendorDir . '/symfony/polyfill-php70'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'PhpCsFixer\\' => array($baseDir . '/src'),
'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib/Doctrine/Common/Lexer'),
'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations'),
'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'),
'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'),
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'ArithmeticError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php',
'AssertionError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/AssertionError.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'Composer\\Semver\\Comparator' => $vendorDir . '/composer/semver/src/Comparator.php',
'Composer\\Semver\\CompilingMatcher' => $vendorDir . '/composer/semver/src/CompilingMatcher.php',
'Composer\\Semver\\Constraint\\Bound' => $vendorDir . '/composer/semver/src/Constraint/Bound.php',
'Composer\\Semver\\Constraint\\Constraint' => $vendorDir . '/composer/semver/src/Constraint/Constraint.php',
'Composer\\Semver\\Constraint\\ConstraintInterface' => $vendorDir . '/composer/semver/src/Constraint/ConstraintInterface.php',
'Composer\\Semver\\Constraint\\MatchAllConstraint' => $vendorDir . '/composer/semver/src/Constraint/MatchAllConstraint.php',
'Composer\\Semver\\Constraint\\MatchNoneConstraint' => $vendorDir . '/composer/semver/src/Constraint/MatchNoneConstraint.php',
'Composer\\Semver\\Constraint\\MultiConstraint' => $vendorDir . '/composer/semver/src/Constraint/MultiConstraint.php',
'Composer\\Semver\\Interval' => $vendorDir . '/composer/semver/src/Interval.php',
'Composer\\Semver\\Intervals' => $vendorDir . '/composer/semver/src/Intervals.php',
'Composer\\Semver\\Semver' => $vendorDir . '/composer/semver/src/Semver.php',
'Composer\\Semver\\VersionParser' => $vendorDir . '/composer/semver/src/VersionParser.php',
'Composer\\XdebugHandler\\PhpConfig' => $vendorDir . '/composer/xdebug-handler/src/PhpConfig.php',
'Composer\\XdebugHandler\\Process' => $vendorDir . '/composer/xdebug-handler/src/Process.php',
'Composer\\XdebugHandler\\Status' => $vendorDir . '/composer/xdebug-handler/src/Status.php',
'Composer\\XdebugHandler\\XdebugHandler' => $vendorDir . '/composer/xdebug-handler/src/XdebugHandler.php',
'DivisionByZeroError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php',
'Doctrine\\Common\\Annotations\\Annotation' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php',
'Doctrine\\Common\\Annotations\\AnnotationException' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php',
'Doctrine\\Common\\Annotations\\AnnotationReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php',
'Doctrine\\Common\\Annotations\\AnnotationRegistry' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php',
'Doctrine\\Common\\Annotations\\Annotation\\Attribute' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php',
'Doctrine\\Common\\Annotations\\Annotation\\Attributes' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php',
'Doctrine\\Common\\Annotations\\Annotation\\Enum' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php',
'Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php',
'Doctrine\\Common\\Annotations\\Annotation\\Required' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.php',
'Doctrine\\Common\\Annotations\\Annotation\\Target' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php',
'Doctrine\\Common\\Annotations\\CachedReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/CachedReader.php',
'Doctrine\\Common\\Annotations\\DocLexer' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.php',
'Doctrine\\Common\\Annotations\\DocParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php',
'Doctrine\\Common\\Annotations\\FileCacheReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/FileCacheReader.php',
'Doctrine\\Common\\Annotations\\IndexedReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php',
'Doctrine\\Common\\Annotations\\PhpParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php',
'Doctrine\\Common\\Annotations\\Reader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php',
'Doctrine\\Common\\Annotations\\SimpleAnnotationReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/SimpleAnnotationReader.php',
'Doctrine\\Common\\Annotations\\TokenParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php',
'Doctrine\\Common\\Lexer\\AbstractLexer' => $vendorDir . '/doctrine/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php',
'Error' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/Error.php',
'ParseError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/ParseError.php',
'PhpCsFixer\\AbstractAlignFixerHelper' => $baseDir . '/src/AbstractAlignFixerHelper.php',
'PhpCsFixer\\AbstractDoctrineAnnotationFixer' => $baseDir . '/src/AbstractDoctrineAnnotationFixer.php',
'PhpCsFixer\\AbstractFixer' => $baseDir . '/src/AbstractFixer.php',
'PhpCsFixer\\AbstractFopenFlagFixer' => $baseDir . '/src/AbstractFopenFlagFixer.php',
'PhpCsFixer\\AbstractFunctionReferenceFixer' => $baseDir . '/src/AbstractFunctionReferenceFixer.php',
'PhpCsFixer\\AbstractLinesBeforeNamespaceFixer' => $baseDir . '/src/AbstractLinesBeforeNamespaceFixer.php',
'PhpCsFixer\\AbstractNoUselessElseFixer' => $baseDir . '/src/AbstractNoUselessElseFixer.php',
'PhpCsFixer\\AbstractPhpdocToTypeDeclarationFixer' => $baseDir . '/src/AbstractPhpdocToTypeDeclarationFixer.php',
'PhpCsFixer\\AbstractPhpdocTypesFixer' => $baseDir . '/src/AbstractPhpdocTypesFixer.php',
'PhpCsFixer\\AbstractProxyFixer' => $baseDir . '/src/AbstractProxyFixer.php',
'PhpCsFixer\\Cache\\Cache' => $baseDir . '/src/Cache/Cache.php',
'PhpCsFixer\\Cache\\CacheInterface' => $baseDir . '/src/Cache/CacheInterface.php',
'PhpCsFixer\\Cache\\CacheManagerInterface' => $baseDir . '/src/Cache/CacheManagerInterface.php',
'PhpCsFixer\\Cache\\Directory' => $baseDir . '/src/Cache/Directory.php',
'PhpCsFixer\\Cache\\DirectoryInterface' => $baseDir . '/src/Cache/DirectoryInterface.php',
'PhpCsFixer\\Cache\\FileCacheManager' => $baseDir . '/src/Cache/FileCacheManager.php',
'PhpCsFixer\\Cache\\FileHandler' => $baseDir . '/src/Cache/FileHandler.php',
'PhpCsFixer\\Cache\\FileHandlerInterface' => $baseDir . '/src/Cache/FileHandlerInterface.php',
'PhpCsFixer\\Cache\\NullCacheManager' => $baseDir . '/src/Cache/NullCacheManager.php',
'PhpCsFixer\\Cache\\Signature' => $baseDir . '/src/Cache/Signature.php',
'PhpCsFixer\\Cache\\SignatureInterface' => $baseDir . '/src/Cache/SignatureInterface.php',
'PhpCsFixer\\Config' => $baseDir . '/src/Config.php',
'PhpCsFixer\\ConfigInterface' => $baseDir . '/src/ConfigInterface.php',
'PhpCsFixer\\ConfigurationException\\InvalidConfigurationException' => $baseDir . '/src/ConfigurationException/InvalidConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\InvalidFixerConfigurationException' => $baseDir . '/src/ConfigurationException/InvalidFixerConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\InvalidForEnvFixerConfigurationException' => $baseDir . '/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php',
'PhpCsFixer\\ConfigurationException\\RequiredFixerConfigurationException' => $baseDir . '/src/ConfigurationException/RequiredFixerConfigurationException.php',
'PhpCsFixer\\Console\\Application' => $baseDir . '/src/Console/Application.php',
'PhpCsFixer\\Console\\Command\\DescribeCommand' => $baseDir . '/src/Console/Command/DescribeCommand.php',
'PhpCsFixer\\Console\\Command\\DescribeNameNotFoundException' => $baseDir . '/src/Console/Command/DescribeNameNotFoundException.php',
'PhpCsFixer\\Console\\Command\\DocumentationCommand' => $baseDir . '/src/Console/Command/DocumentationCommand.php',
'PhpCsFixer\\Console\\Command\\FixCommand' => $baseDir . '/src/Console/Command/FixCommand.php',
'PhpCsFixer\\Console\\Command\\FixCommandExitStatusCalculator' => $baseDir . '/src/Console/Command/FixCommandExitStatusCalculator.php',
'PhpCsFixer\\Console\\Command\\HelpCommand' => $baseDir . '/src/Console/Command/HelpCommand.php',
'PhpCsFixer\\Console\\Command\\SelfUpdateCommand' => $baseDir . '/src/Console/Command/SelfUpdateCommand.php',
'PhpCsFixer\\Console\\ConfigurationResolver' => $baseDir . '/src/Console/ConfigurationResolver.php',
'PhpCsFixer\\Console\\Output\\ErrorOutput' => $baseDir . '/src/Console/Output/ErrorOutput.php',
'PhpCsFixer\\Console\\Output\\NullOutput' => $baseDir . '/src/Console/Output/NullOutput.php',
'PhpCsFixer\\Console\\Output\\ProcessOutput' => $baseDir . '/src/Console/Output/ProcessOutput.php',
'PhpCsFixer\\Console\\Output\\ProcessOutputInterface' => $baseDir . '/src/Console/Output/ProcessOutputInterface.php',
'PhpCsFixer\\Console\\SelfUpdate\\GithubClient' => $baseDir . '/src/Console/SelfUpdate/GithubClient.php',
'PhpCsFixer\\Console\\SelfUpdate\\GithubClientInterface' => $baseDir . '/src/Console/SelfUpdate/GithubClientInterface.php',
'PhpCsFixer\\Console\\SelfUpdate\\NewVersionChecker' => $baseDir . '/src/Console/SelfUpdate/NewVersionChecker.php',
'PhpCsFixer\\Console\\SelfUpdate\\NewVersionCheckerInterface' => $baseDir . '/src/Console/SelfUpdate/NewVersionCheckerInterface.php',
'PhpCsFixer\\Console\\WarningsDetector' => $baseDir . '/src/Console/WarningsDetector.php',
'PhpCsFixer\\Diff\\GeckoPackages\\DiffOutputBuilder\\ConfigurationException' => $vendorDir . '/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/ConfigurationException.php',
'PhpCsFixer\\Diff\\GeckoPackages\\DiffOutputBuilder\\UnifiedDiffOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/GeckoPackages/DiffOutputBuilder/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v1_4\\Chunk' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/Chunk.php',
'PhpCsFixer\\Diff\\v1_4\\Diff' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/Diff.php',
'PhpCsFixer\\Diff\\v1_4\\Differ' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/Differ.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\LongestCommonSubsequence' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/LCS/LongestCommonSubsequence.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\MemoryEfficientImplementation' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php',
'PhpCsFixer\\Diff\\v1_4\\LCS\\TimeEfficientImplementation' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php',
'PhpCsFixer\\Diff\\v1_4\\Line' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/Line.php',
'PhpCsFixer\\Diff\\v1_4\\Parser' => $vendorDir . '/php-cs-fixer/diff/src/v1_4/Parser.php',
'PhpCsFixer\\Diff\\v2_0\\Chunk' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Chunk.php',
'PhpCsFixer\\Diff\\v2_0\\Diff' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Diff.php',
'PhpCsFixer\\Diff\\v2_0\\Differ' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Differ.php',
'PhpCsFixer\\Diff\\v2_0\\Exception' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Exception/Exception.php',
'PhpCsFixer\\Diff\\v2_0\\InvalidArgumentException' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Exception/InvalidArgumentException.php',
'PhpCsFixer\\Diff\\v2_0\\Line' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Line.php',
'PhpCsFixer\\Diff\\v2_0\\LongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/LongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v2_0\\MemoryEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/MemoryEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\AbstractChunkOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Output/AbstractChunkOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Output/DiffOnlyOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Output/DiffOutputBuilderInterface.php',
'PhpCsFixer\\Diff\\v2_0\\Output\\UnifiedDiffOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Output/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v2_0\\Parser' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/Parser.php',
'PhpCsFixer\\Diff\\v2_0\\TimeEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v2_0/TimeEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\Chunk' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Chunk.php',
'PhpCsFixer\\Diff\\v3_0\\ConfigurationException' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Exception/ConfigurationException.php',
'PhpCsFixer\\Diff\\v3_0\\Diff' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Diff.php',
'PhpCsFixer\\Diff\\v3_0\\Differ' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Differ.php',
'PhpCsFixer\\Diff\\v3_0\\Exception' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Exception/Exception.php',
'PhpCsFixer\\Diff\\v3_0\\InvalidArgumentException' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Exception/InvalidArgumentException.php',
'PhpCsFixer\\Diff\\v3_0\\Line' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Line.php',
'PhpCsFixer\\Diff\\v3_0\\LongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/LongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\MemoryEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/MemoryEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\AbstractChunkOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Output/AbstractChunkOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Output/DiffOnlyOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Output/DiffOutputBuilderInterface.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\StrictUnifiedDiffOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Output/StrictUnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Output\\UnifiedDiffOutputBuilder' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Output/UnifiedDiffOutputBuilder.php',
'PhpCsFixer\\Diff\\v3_0\\Parser' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/Parser.php',
'PhpCsFixer\\Diff\\v3_0\\TimeEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/php-cs-fixer/diff/src/v3_0/TimeEfficientLongestCommonSubsequenceCalculator.php',
'PhpCsFixer\\Differ\\DiffConsoleFormatter' => $baseDir . '/src/Differ/DiffConsoleFormatter.php',
'PhpCsFixer\\Differ\\DifferInterface' => $baseDir . '/src/Differ/DifferInterface.php',
'PhpCsFixer\\Differ\\FullDiffer' => $baseDir . '/src/Differ/FullDiffer.php',
'PhpCsFixer\\Differ\\NullDiffer' => $baseDir . '/src/Differ/NullDiffer.php',
'PhpCsFixer\\Differ\\SebastianBergmannDiffer' => $baseDir . '/src/Differ/SebastianBergmannDiffer.php',
'PhpCsFixer\\Differ\\SebastianBergmannShortDiffer' => $baseDir . '/src/Differ/SebastianBergmannShortDiffer.php',
'PhpCsFixer\\Differ\\UnifiedDiffer' => $baseDir . '/src/Differ/UnifiedDiffer.php',
'PhpCsFixer\\DocBlock\\Annotation' => $baseDir . '/src/DocBlock/Annotation.php',
'PhpCsFixer\\DocBlock\\DocBlock' => $baseDir . '/src/DocBlock/DocBlock.php',
'PhpCsFixer\\DocBlock\\Line' => $baseDir . '/src/DocBlock/Line.php',
'PhpCsFixer\\DocBlock\\ShortDescription' => $baseDir . '/src/DocBlock/ShortDescription.php',
'PhpCsFixer\\DocBlock\\Tag' => $baseDir . '/src/DocBlock/Tag.php',
'PhpCsFixer\\DocBlock\\TagComparator' => $baseDir . '/src/DocBlock/TagComparator.php',
'PhpCsFixer\\Doctrine\\Annotation\\Token' => $baseDir . '/src/Doctrine/Annotation/Token.php',
'PhpCsFixer\\Doctrine\\Annotation\\Tokens' => $baseDir . '/src/Doctrine/Annotation/Tokens.php',
'PhpCsFixer\\Documentation\\DocumentationGenerator' => $baseDir . '/src/Documentation/DocumentationGenerator.php',
'PhpCsFixer\\Error\\Error' => $baseDir . '/src/Error/Error.php',
'PhpCsFixer\\Error\\ErrorsManager' => $baseDir . '/src/Error/ErrorsManager.php',
'PhpCsFixer\\Event\\Event' => $baseDir . '/src/Event/Event.php',
'PhpCsFixer\\FileReader' => $baseDir . '/src/FileReader.php',
'PhpCsFixer\\FileRemoval' => $baseDir . '/src/FileRemoval.php',
'PhpCsFixer\\Finder' => $baseDir . '/src/Finder.php',
'PhpCsFixer\\FixerConfiguration\\AliasedFixerOption' => $baseDir . '/src/FixerConfiguration/AliasedFixerOption.php',
'PhpCsFixer\\FixerConfiguration\\AliasedFixerOptionBuilder' => $baseDir . '/src/FixerConfiguration/AliasedFixerOptionBuilder.php',
'PhpCsFixer\\FixerConfiguration\\AllowedValueSubset' => $baseDir . '/src/FixerConfiguration/AllowedValueSubset.php',
'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOption' => $baseDir . '/src/FixerConfiguration/DeprecatedFixerOption.php',
'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOptionInterface' => $baseDir . '/src/FixerConfiguration/DeprecatedFixerOptionInterface.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolver' => $baseDir . '/src/FixerConfiguration/FixerConfigurationResolver.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverInterface' => $baseDir . '/src/FixerConfiguration/FixerConfigurationResolverInterface.php',
'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverRootless' => $baseDir . '/src/FixerConfiguration/FixerConfigurationResolverRootless.php',
'PhpCsFixer\\FixerConfiguration\\FixerOption' => $baseDir . '/src/FixerConfiguration/FixerOption.php',
'PhpCsFixer\\FixerConfiguration\\FixerOptionBuilder' => $baseDir . '/src/FixerConfiguration/FixerOptionBuilder.php',
'PhpCsFixer\\FixerConfiguration\\FixerOptionInterface' => $baseDir . '/src/FixerConfiguration/FixerOptionInterface.php',
'PhpCsFixer\\FixerConfiguration\\InvalidOptionsForEnvException' => $baseDir . '/src/FixerConfiguration/InvalidOptionsForEnvException.php',
'PhpCsFixer\\FixerDefinition\\CodeSample' => $baseDir . '/src/FixerDefinition/CodeSample.php',
'PhpCsFixer\\FixerDefinition\\CodeSampleInterface' => $baseDir . '/src/FixerDefinition/CodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSample' => $baseDir . '/src/FixerDefinition/FileSpecificCodeSample.php',
'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSampleInterface' => $baseDir . '/src/FixerDefinition/FileSpecificCodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\FixerDefinition' => $baseDir . '/src/FixerDefinition/FixerDefinition.php',
'PhpCsFixer\\FixerDefinition\\FixerDefinitionInterface' => $baseDir . '/src/FixerDefinition/FixerDefinitionInterface.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSample' => $baseDir . '/src/FixerDefinition/VersionSpecificCodeSample.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSampleInterface' => $baseDir . '/src/FixerDefinition/VersionSpecificCodeSampleInterface.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecification' => $baseDir . '/src/FixerDefinition/VersionSpecification.php',
'PhpCsFixer\\FixerDefinition\\VersionSpecificationInterface' => $baseDir . '/src/FixerDefinition/VersionSpecificationInterface.php',
'PhpCsFixer\\FixerFactory' => $baseDir . '/src/FixerFactory.php',
'PhpCsFixer\\FixerFileProcessedEvent' => $baseDir . '/src/FixerFileProcessedEvent.php',
'PhpCsFixer\\FixerNameValidator' => $baseDir . '/src/FixerNameValidator.php',
'PhpCsFixer\\Fixer\\AbstractIncrementOperatorFixer' => $baseDir . '/src/Fixer/AbstractIncrementOperatorFixer.php',
'PhpCsFixer\\Fixer\\AbstractPhpUnitFixer' => $baseDir . '/src/Fixer/AbstractPhpUnitFixer.php',
'PhpCsFixer\\Fixer\\Alias\\ArrayPushFixer' => $baseDir . '/src/Fixer/Alias/ArrayPushFixer.php',
'PhpCsFixer\\Fixer\\Alias\\BacktickToShellExecFixer' => $baseDir . '/src/Fixer/Alias/BacktickToShellExecFixer.php',
'PhpCsFixer\\Fixer\\Alias\\EregToPregFixer' => $baseDir . '/src/Fixer/Alias/EregToPregFixer.php',
'PhpCsFixer\\Fixer\\Alias\\MbStrFunctionsFixer' => $baseDir . '/src/Fixer/Alias/MbStrFunctionsFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoAliasFunctionsFixer' => $baseDir . '/src/Fixer/Alias/NoAliasFunctionsFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoAliasLanguageConstructCallFixer' => $baseDir . '/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php',
'PhpCsFixer\\Fixer\\Alias\\NoMixedEchoPrintFixer' => $baseDir . '/src/Fixer/Alias/NoMixedEchoPrintFixer.php',
'PhpCsFixer\\Fixer\\Alias\\PowToExponentiationFixer' => $baseDir . '/src/Fixer/Alias/PowToExponentiationFixer.php',
'PhpCsFixer\\Fixer\\Alias\\RandomApiMigrationFixer' => $baseDir . '/src/Fixer/Alias/RandomApiMigrationFixer.php',
'PhpCsFixer\\Fixer\\Alias\\SetTypeToCastFixer' => $baseDir . '/src/Fixer/Alias/SetTypeToCastFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\ArraySyntaxFixer' => $baseDir . '/src/Fixer/ArrayNotation/ArraySyntaxFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoMultilineWhitespaceAroundDoubleArrowFixer' => $baseDir . '/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoTrailingCommaInSinglelineArrayFixer' => $baseDir . '/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NoWhitespaceBeforeCommaInArrayFixer' => $baseDir . '/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\NormalizeIndexBraceFixer' => $baseDir . '/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\TrailingCommaInMultilineArrayFixer' => $baseDir . '/src/Fixer/ArrayNotation/TrailingCommaInMultilineArrayFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\TrimArraySpacesFixer' => $baseDir . '/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php',
'PhpCsFixer\\Fixer\\ArrayNotation\\WhitespaceAfterCommaInArrayFixer' => $baseDir . '/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php',
'PhpCsFixer\\Fixer\\Basic\\BracesFixer' => $baseDir . '/src/Fixer/Basic/BracesFixer.php',
'PhpCsFixer\\Fixer\\Basic\\EncodingFixer' => $baseDir . '/src/Fixer/Basic/EncodingFixer.php',
'PhpCsFixer\\Fixer\\Basic\\NonPrintableCharacterFixer' => $baseDir . '/src/Fixer/Basic/NonPrintableCharacterFixer.php',
'PhpCsFixer\\Fixer\\Basic\\Psr0Fixer' => $baseDir . '/src/Fixer/Basic/Psr0Fixer.php',
'PhpCsFixer\\Fixer\\Basic\\Psr4Fixer' => $baseDir . '/src/Fixer/Basic/Psr4Fixer.php',
'PhpCsFixer\\Fixer\\Basic\\PsrAutoloadingFixer' => $baseDir . '/src/Fixer/Basic/PsrAutoloadingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\ConstantCaseFixer' => $baseDir . '/src/Fixer/Casing/ConstantCaseFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseConstantsFixer' => $baseDir . '/src/Fixer/Casing/LowercaseConstantsFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseKeywordsFixer' => $baseDir . '/src/Fixer/Casing/LowercaseKeywordsFixer.php',
'PhpCsFixer\\Fixer\\Casing\\LowercaseStaticReferenceFixer' => $baseDir . '/src/Fixer/Casing/LowercaseStaticReferenceFixer.php',
'PhpCsFixer\\Fixer\\Casing\\MagicConstantCasingFixer' => $baseDir . '/src/Fixer/Casing/MagicConstantCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\MagicMethodCasingFixer' => $baseDir . '/src/Fixer/Casing/MagicMethodCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\NativeFunctionCasingFixer' => $baseDir . '/src/Fixer/Casing/NativeFunctionCasingFixer.php',
'PhpCsFixer\\Fixer\\Casing\\NativeFunctionTypeDeclarationCasingFixer' => $baseDir . '/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\CastSpacesFixer' => $baseDir . '/src/Fixer/CastNotation/CastSpacesFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\LowercaseCastFixer' => $baseDir . '/src/Fixer/CastNotation/LowercaseCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\ModernizeTypesCastingFixer' => $baseDir . '/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\NoShortBoolCastFixer' => $baseDir . '/src/Fixer/CastNotation/NoShortBoolCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\NoUnsetCastFixer' => $baseDir . '/src/Fixer/CastNotation/NoUnsetCastFixer.php',
'PhpCsFixer\\Fixer\\CastNotation\\ShortScalarCastFixer' => $baseDir . '/src/Fixer/CastNotation/ShortScalarCastFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ClassAttributesSeparationFixer' => $baseDir . '/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ClassDefinitionFixer' => $baseDir . '/src/Fixer/ClassNotation/ClassDefinitionFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalClassFixer' => $baseDir . '/src/Fixer/ClassNotation/FinalClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalInternalClassFixer' => $baseDir . '/src/Fixer/ClassNotation/FinalInternalClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalPublicMethodForAbstractClassFixer' => $baseDir . '/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\FinalStaticAccessFixer' => $baseDir . '/src/Fixer/ClassNotation/FinalStaticAccessFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\MethodSeparationFixer' => $baseDir . '/src/Fixer/ClassNotation/MethodSeparationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoBlankLinesAfterClassOpeningFixer' => $baseDir . '/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoNullPropertyInitializationFixer' => $baseDir . '/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoPhp4ConstructorFixer' => $baseDir . '/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\NoUnneededFinalMethodFixer' => $baseDir . '/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedClassElementsFixer' => $baseDir . '/src/Fixer/ClassNotation/OrderedClassElementsFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedInterfacesFixer' => $baseDir . '/src/Fixer/ClassNotation/OrderedInterfacesFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTraitsFixer' => $baseDir . '/src/Fixer/ClassNotation/OrderedTraitsFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\ProtectedToPrivateFixer' => $baseDir . '/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SelfAccessorFixer' => $baseDir . '/src/Fixer/ClassNotation/SelfAccessorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SelfStaticAccessorFixer' => $baseDir . '/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SingleClassElementPerStatementFixer' => $baseDir . '/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\SingleTraitInsertPerStatementFixer' => $baseDir . '/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php',
'PhpCsFixer\\Fixer\\ClassNotation\\VisibilityRequiredFixer' => $baseDir . '/src/Fixer/ClassNotation/VisibilityRequiredFixer.php',
'PhpCsFixer\\Fixer\\ClassUsage\\DateTimeImmutableFixer' => $baseDir . '/src/Fixer/ClassUsage/DateTimeImmutableFixer.php',
'PhpCsFixer\\Fixer\\Comment\\CommentToPhpdocFixer' => $baseDir . '/src/Fixer/Comment/CommentToPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Comment\\HashToSlashCommentFixer' => $baseDir . '/src/Fixer/Comment/HashToSlashCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\HeaderCommentFixer' => $baseDir . '/src/Fixer/Comment/HeaderCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\MultilineCommentOpeningClosingFixer' => $baseDir . '/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php',
'PhpCsFixer\\Fixer\\Comment\\NoEmptyCommentFixer' => $baseDir . '/src/Fixer/Comment/NoEmptyCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\NoTrailingWhitespaceInCommentFixer' => $baseDir . '/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php',
'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentStyleFixer' => $baseDir . '/src/Fixer/Comment/SingleLineCommentStyleFixer.php',
'PhpCsFixer\\Fixer\\ConfigurableFixerInterface' => $baseDir . '/src/Fixer/ConfigurableFixerInterface.php',
'PhpCsFixer\\Fixer\\ConfigurationDefinitionFixerInterface' => $baseDir . '/src/Fixer/ConfigurationDefinitionFixerInterface.php',
'PhpCsFixer\\Fixer\\ConstantNotation\\NativeConstantInvocationFixer' => $baseDir . '/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\ElseifFixer' => $baseDir . '/src/Fixer/ControlStructure/ElseifFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\IncludeFixer' => $baseDir . '/src/Fixer/ControlStructure/IncludeFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoAlternativeSyntaxFixer' => $baseDir . '/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoBreakCommentFixer' => $baseDir . '/src/Fixer/ControlStructure/NoBreakCommentFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoSuperfluousElseifFixer' => $baseDir . '/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoTrailingCommaInListCallFixer' => $baseDir . '/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededControlParenthesesFixer' => $baseDir . '/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededCurlyBracesFixer' => $baseDir . '/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\NoUselessElseFixer' => $baseDir . '/src/Fixer/ControlStructure/NoUselessElseFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SimplifiedIfReturnFixer' => $baseDir . '/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSemicolonToColonFixer' => $baseDir . '/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSpaceFixer' => $baseDir . '/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\SwitchContinueToBreakFixer' => $baseDir . '/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php',
'PhpCsFixer\\Fixer\\ControlStructure\\YodaStyleFixer' => $baseDir . '/src/Fixer/ControlStructure/YodaStyleFixer.php',
'PhpCsFixer\\Fixer\\DefinedFixerInterface' => $baseDir . '/src/Fixer/DefinedFixerInterface.php',
'PhpCsFixer\\Fixer\\DeprecatedFixerInterface' => $baseDir . '/src/Fixer/DeprecatedFixerInterface.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationArrayAssignmentFixer' => $baseDir . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationBracesFixer' => $baseDir . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationIndentationFixer' => $baseDir . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php',
'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationSpacesFixer' => $baseDir . '/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php',
'PhpCsFixer\\Fixer\\FixerInterface' => $baseDir . '/src/Fixer/FixerInterface.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\CombineNestedDirnameFixer' => $baseDir . '/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagOrderFixer' => $baseDir . '/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagsFixer' => $baseDir . '/src/Fixer/FunctionNotation/FopenFlagsFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionDeclarationFixer' => $baseDir . '/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionTypehintSpaceFixer' => $baseDir . '/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\ImplodeCallFixer' => $baseDir . '/src/Fixer/FunctionNotation/ImplodeCallFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\LambdaNotUsedImportFixer' => $baseDir . '/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\MethodArgumentSpaceFixer' => $baseDir . '/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NativeFunctionInvocationFixer' => $baseDir . '/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoSpacesAfterFunctionNameFixer' => $baseDir . '/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoUnreachableDefaultArgumentValueFixer' => $baseDir . '/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NoUselessSprintfFixer' => $baseDir . '/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\NullableTypeDeclarationForDefaultNullValueFixer' => $baseDir . '/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToParamTypeFixer' => $baseDir . '/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToReturnTypeFixer' => $baseDir . '/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\RegularCallableCallFixer' => $baseDir . '/src/Fixer/FunctionNotation/RegularCallableCallFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\ReturnTypeDeclarationFixer' => $baseDir . '/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\SingleLineThrowFixer' => $baseDir . '/src/Fixer/FunctionNotation/SingleLineThrowFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\StaticLambdaFixer' => $baseDir . '/src/Fixer/FunctionNotation/StaticLambdaFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\UseArrowFunctionsFixer' => $baseDir . '/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php',
'PhpCsFixer\\Fixer\\FunctionNotation\\VoidReturnFixer' => $baseDir . '/src/Fixer/FunctionNotation/VoidReturnFixer.php',
'PhpCsFixer\\Fixer\\Import\\FullyQualifiedStrictTypesFixer' => $baseDir . '/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php',
'PhpCsFixer\\Fixer\\Import\\GlobalNamespaceImportFixer' => $baseDir . '/src/Fixer/Import/GlobalNamespaceImportFixer.php',
'PhpCsFixer\\Fixer\\Import\\GroupImportFixer' => $baseDir . '/src/Fixer/Import/GroupImportFixer.php',
'PhpCsFixer\\Fixer\\Import\\NoLeadingImportSlashFixer' => $baseDir . '/src/Fixer/Import/NoLeadingImportSlashFixer.php',
'PhpCsFixer\\Fixer\\Import\\NoUnusedImportsFixer' => $baseDir . '/src/Fixer/Import/NoUnusedImportsFixer.php',
'PhpCsFixer\\Fixer\\Import\\OrderedImportsFixer' => $baseDir . '/src/Fixer/Import/OrderedImportsFixer.php',
'PhpCsFixer\\Fixer\\Import\\SingleImportPerStatementFixer' => $baseDir . '/src/Fixer/Import/SingleImportPerStatementFixer.php',
'PhpCsFixer\\Fixer\\Import\\SingleLineAfterImportsFixer' => $baseDir . '/src/Fixer/Import/SingleLineAfterImportsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ClassKeywordRemoveFixer' => $baseDir . '/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveIssetsFixer' => $baseDir . '/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveUnsetsFixer' => $baseDir . '/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareEqualNormalizeFixer' => $baseDir . '/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\DirConstantFixer' => $baseDir . '/src/Fixer/LanguageConstruct/DirConstantFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ErrorSuppressionFixer' => $baseDir . '/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\ExplicitIndirectVariableFixer' => $baseDir . '/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\FunctionToConstantFixer' => $baseDir . '/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\IsNullFixer' => $baseDir . '/src/Fixer/LanguageConstruct/IsNullFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\NoUnsetOnPropertyFixer' => $baseDir . '/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\SilencedDeprecationErrorFixer' => $baseDir . '/src/Fixer/LanguageConstruct/SilencedDeprecationErrorFixer.php',
'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAfterConstructFixer' => $baseDir . '/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php',
'PhpCsFixer\\Fixer\\ListNotation\\ListSyntaxFixer' => $baseDir . '/src/Fixer/ListNotation/ListSyntaxFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLineAfterNamespaceFixer' => $baseDir . '/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\CleanNamespaceFixer' => $baseDir . '/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\NoBlankLinesBeforeNamespaceFixer' => $baseDir . '/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\NoLeadingNamespaceWhitespaceFixer' => $baseDir . '/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\NamespaceNotation\\SingleBlankLineBeforeNamespaceFixer' => $baseDir . '/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php',
'PhpCsFixer\\Fixer\\Naming\\NoHomoglyphNamesFixer' => $baseDir . '/src/Fixer/Naming/NoHomoglyphNamesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\AlignDoubleArrowFixerHelper' => $baseDir . '/src/Fixer/Operator/AlignDoubleArrowFixerHelper.php',
'PhpCsFixer\\Fixer\\Operator\\AlignEqualsFixerHelper' => $baseDir . '/src/Fixer/Operator/AlignEqualsFixerHelper.php',
'PhpCsFixer\\Fixer\\Operator\\BinaryOperatorSpacesFixer' => $baseDir . '/src/Fixer/Operator/BinaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\ConcatSpaceFixer' => $baseDir . '/src/Fixer/Operator/ConcatSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\IncrementStyleFixer' => $baseDir . '/src/Fixer/Operator/IncrementStyleFixer.php',
'PhpCsFixer\\Fixer\\Operator\\LogicalOperatorsFixer' => $baseDir . '/src/Fixer/Operator/LogicalOperatorsFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NewWithBracesFixer' => $baseDir . '/src/Fixer/Operator/NewWithBracesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSpaceFixer' => $baseDir . '/src/Fixer/Operator/NotOperatorWithSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSuccessorSpaceFixer' => $baseDir . '/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\ObjectOperatorWithoutWhitespaceFixer' => $baseDir . '/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\Operator\\OperatorLinebreakFixer' => $baseDir . '/src/Fixer/Operator/OperatorLinebreakFixer.php',
'PhpCsFixer\\Fixer\\Operator\\PreIncrementFixer' => $baseDir . '/src/Fixer/Operator/PreIncrementFixer.php',
'PhpCsFixer\\Fixer\\Operator\\StandardizeIncrementFixer' => $baseDir . '/src/Fixer/Operator/StandardizeIncrementFixer.php',
'PhpCsFixer\\Fixer\\Operator\\StandardizeNotEqualsFixer' => $baseDir . '/src/Fixer/Operator/StandardizeNotEqualsFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryOperatorSpacesFixer' => $baseDir . '/src/Fixer/Operator/TernaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryToElvisOperatorFixer' => $baseDir . '/src/Fixer/Operator/TernaryToElvisOperatorFixer.php',
'PhpCsFixer\\Fixer\\Operator\\TernaryToNullCoalescingFixer' => $baseDir . '/src/Fixer/Operator/TernaryToNullCoalescingFixer.php',
'PhpCsFixer\\Fixer\\Operator\\UnaryOperatorSpacesFixer' => $baseDir . '/src/Fixer/Operator/UnaryOperatorSpacesFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\BlankLineAfterOpeningTagFixer' => $baseDir . '/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\EchoTagSyntaxFixer' => $baseDir . '/src/Fixer/PhpTag/EchoTagSyntaxFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\FullOpeningTagFixer' => $baseDir . '/src/Fixer/PhpTag/FullOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\LinebreakAfterOpeningTagFixer' => $baseDir . '/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\NoClosingTagFixer' => $baseDir . '/src/Fixer/PhpTag/NoClosingTagFixer.php',
'PhpCsFixer\\Fixer\\PhpTag\\NoShortEchoTagFixer' => $baseDir . '/src/Fixer/PhpTag/NoShortEchoTagFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitConstructFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitConstructFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertInternalTypeFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitExpectationFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitFqcnAnnotationFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitInternalClassFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMethodCasingFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitMockFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockShortWillReturnFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNamespacedFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNoExpectationAnnotationFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitOrderedCoversFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitOrderedCoversFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSetUpTearDownVisibilityFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSizeClassFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitStrictFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitStrictFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTargetVersion' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitTargetVersion.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestAnnotationFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestCaseStaticMethodCallsFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php',
'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestClassRequiresCoversFixer' => $baseDir . '/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\AlignMultilineCommentFixer' => $baseDir . '/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocAnnotationRemoveFixer' => $baseDir . '/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocTagRenameFixer' => $baseDir . '/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoBlankLinesAfterPhpdocFixer' => $baseDir . '/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoEmptyPhpdocFixer' => $baseDir . '/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\NoSuperfluousPhpdocTagsFixer' => $baseDir . '/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAddMissingParamAnnotationFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAlignFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocAlignFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAnnotationWithoutDotFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocIndentFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocIndentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocInlineTagFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagNormalizerFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocLineSpanFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAccessFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAliasTagFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoEmptyReturnFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoPackageFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoUselessInheritdocFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderByValueFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocReturnSelfReferenceFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocScalarFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocScalarFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSeparationFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocSeparationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSingleLineVarSpacingFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSummaryFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocSummaryFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagCasingFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagTypeFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocToCommentFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocToCommentFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimConsecutiveBlankLineSeparationFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTrimFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTypesFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesOrderFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarAnnotationCorrectOrderFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php',
'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarWithoutNameFixer' => $baseDir . '/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\BlankLineBeforeReturnFixer' => $baseDir . '/src/Fixer/ReturnNotation/BlankLineBeforeReturnFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\NoUselessReturnFixer' => $baseDir . '/src/Fixer/ReturnNotation/NoUselessReturnFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\ReturnAssignmentFixer' => $baseDir . '/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php',
'PhpCsFixer\\Fixer\\ReturnNotation\\SimplifiedNullReturnFixer' => $baseDir . '/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\MultilineWhitespaceBeforeSemicolonsFixer' => $baseDir . '/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoEmptyStatementFixer' => $baseDir . '/src/Fixer/Semicolon/NoEmptyStatementFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoMultilineWhitespaceBeforeSemicolonsFixer' => $baseDir . '/src/Fixer/Semicolon/NoMultilineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\NoSinglelineWhitespaceBeforeSemicolonsFixer' => $baseDir . '/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\SemicolonAfterInstructionFixer' => $baseDir . '/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php',
'PhpCsFixer\\Fixer\\Semicolon\\SpaceAfterSemicolonFixer' => $baseDir . '/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php',
'PhpCsFixer\\Fixer\\Strict\\DeclareStrictTypesFixer' => $baseDir . '/src/Fixer/Strict/DeclareStrictTypesFixer.php',
'PhpCsFixer\\Fixer\\Strict\\StrictComparisonFixer' => $baseDir . '/src/Fixer/Strict/StrictComparisonFixer.php',
'PhpCsFixer\\Fixer\\Strict\\StrictParamFixer' => $baseDir . '/src/Fixer/Strict/StrictParamFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\EscapeImplicitBackslashesFixer' => $baseDir . '/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\ExplicitStringVariableFixer' => $baseDir . '/src/Fixer/StringNotation/ExplicitStringVariableFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\HeredocToNowdocFixer' => $baseDir . '/src/Fixer/StringNotation/HeredocToNowdocFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\NoBinaryStringFixer' => $baseDir . '/src/Fixer/StringNotation/NoBinaryStringFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\NoTrailingWhitespaceInStringFixer' => $baseDir . '/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\SimpleToComplexStringVariableFixer' => $baseDir . '/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\SingleQuoteFixer' => $baseDir . '/src/Fixer/StringNotation/SingleQuoteFixer.php',
'PhpCsFixer\\Fixer\\StringNotation\\StringLineEndingFixer' => $baseDir . '/src/Fixer/StringNotation/StringLineEndingFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\ArrayIndentationFixer' => $baseDir . '/src/Fixer/Whitespace/ArrayIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBeforeStatementFixer' => $baseDir . '/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\CompactNullableTypehintFixer' => $baseDir . '/src/Fixer/Whitespace/CompactNullableTypehintFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\HeredocIndentationFixer' => $baseDir . '/src/Fixer/Whitespace/HeredocIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\IndentationTypeFixer' => $baseDir . '/src/Fixer/Whitespace/IndentationTypeFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\LineEndingFixer' => $baseDir . '/src/Fixer/Whitespace/LineEndingFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\MethodChainingIndentationFixer' => $baseDir . '/src/Fixer/Whitespace/MethodChainingIndentationFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoExtraBlankLinesFixer' => $baseDir . '/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoExtraConsecutiveBlankLinesFixer' => $baseDir . '/src/Fixer/Whitespace/NoExtraConsecutiveBlankLinesFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesAroundOffsetFixer' => $baseDir . '/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesInsideParenthesisFixer' => $baseDir . '/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoTrailingWhitespaceFixer' => $baseDir . '/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\NoWhitespaceInBlankLineFixer' => $baseDir . '/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php',
'PhpCsFixer\\Fixer\\Whitespace\\SingleBlankLineAtEofFixer' => $baseDir . '/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php',
'PhpCsFixer\\Fixer\\WhitespacesAwareFixerInterface' => $baseDir . '/src/Fixer/WhitespacesAwareFixerInterface.php',
'PhpCsFixer\\Indicator\\PhpUnitTestCaseIndicator' => $baseDir . '/src/Indicator/PhpUnitTestCaseIndicator.php',
'PhpCsFixer\\Linter\\CachingLinter' => $baseDir . '/src/Linter/CachingLinter.php',
'PhpCsFixer\\Linter\\Linter' => $baseDir . '/src/Linter/Linter.php',
'PhpCsFixer\\Linter\\LinterInterface' => $baseDir . '/src/Linter/LinterInterface.php',
'PhpCsFixer\\Linter\\LintingException' => $baseDir . '/src/Linter/LintingException.php',
'PhpCsFixer\\Linter\\LintingResultInterface' => $baseDir . '/src/Linter/LintingResultInterface.php',
'PhpCsFixer\\Linter\\ProcessLinter' => $baseDir . '/src/Linter/ProcessLinter.php',
'PhpCsFixer\\Linter\\ProcessLinterProcessBuilder' => $baseDir . '/src/Linter/ProcessLinterProcessBuilder.php',
'PhpCsFixer\\Linter\\ProcessLintingResult' => $baseDir . '/src/Linter/ProcessLintingResult.php',
'PhpCsFixer\\Linter\\TokenizerLinter' => $baseDir . '/src/Linter/TokenizerLinter.php',
'PhpCsFixer\\Linter\\TokenizerLintingResult' => $baseDir . '/src/Linter/TokenizerLintingResult.php',
'PhpCsFixer\\Linter\\UnavailableLinterException' => $baseDir . '/src/Linter/UnavailableLinterException.php',
'PhpCsFixer\\PharChecker' => $baseDir . '/src/PharChecker.php',
'PhpCsFixer\\PharCheckerInterface' => $baseDir . '/src/PharCheckerInterface.php',
'PhpCsFixer\\Preg' => $baseDir . '/src/Preg.php',
'PhpCsFixer\\PregException' => $baseDir . '/src/PregException.php',
'PhpCsFixer\\Report\\CheckstyleReporter' => $baseDir . '/src/Report/CheckstyleReporter.php',
'PhpCsFixer\\Report\\GitlabReporter' => $baseDir . '/src/Report/GitlabReporter.php',
'PhpCsFixer\\Report\\JsonReporter' => $baseDir . '/src/Report/JsonReporter.php',
'PhpCsFixer\\Report\\JunitReporter' => $baseDir . '/src/Report/JunitReporter.php',
'PhpCsFixer\\Report\\ReportSummary' => $baseDir . '/src/Report/ReportSummary.php',
'PhpCsFixer\\Report\\ReporterFactory' => $baseDir . '/src/Report/ReporterFactory.php',
'PhpCsFixer\\Report\\ReporterInterface' => $baseDir . '/src/Report/ReporterInterface.php',
'PhpCsFixer\\Report\\TextReporter' => $baseDir . '/src/Report/TextReporter.php',
'PhpCsFixer\\Report\\XmlReporter' => $baseDir . '/src/Report/XmlReporter.php',
'PhpCsFixer\\RuleSet' => $baseDir . '/src/RuleSet.php',
'PhpCsFixer\\RuleSetInterface' => $baseDir . '/src/RuleSetInterface.php',
'PhpCsFixer\\RuleSet\\AbstractRuleSetDescription' => $baseDir . '/src/RuleSet/AbstractRuleSetDescription.php',
'PhpCsFixer\\RuleSet\\RuleSet' => $baseDir . '/src/RuleSet/RuleSet.php',
'PhpCsFixer\\RuleSet\\RuleSetDescriptionInterface' => $baseDir . '/src/RuleSet/RuleSetDescriptionInterface.php',
'PhpCsFixer\\RuleSet\\RuleSetInterface' => $baseDir . '/src/RuleSet/RuleSetInterface.php',
'PhpCsFixer\\RuleSet\\RuleSets' => $baseDir . '/src/RuleSet/RuleSets.php',
'PhpCsFixer\\RuleSet\\Sets\\DoctrineAnnotationSet' => $baseDir . '/src/RuleSet/Sets/DoctrineAnnotationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP54MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP54MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHP56MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP56MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHP70MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP70MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHP71MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP71MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP73MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP73MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHP74MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP74MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHP80MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationSet' => $baseDir . '/src/RuleSet/Sets/PHP80MigrationSet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit30MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit32MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit35MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit43MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit48MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit50MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit52MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit54MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit55MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit56MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit57MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit60MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit75MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PHPUnit84MigrationRiskySet' => $baseDir . '/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR12RiskySet' => $baseDir . '/src/RuleSet/Sets/PSR12RiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR12Set' => $baseDir . '/src/RuleSet/Sets/PSR12Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR1Set' => $baseDir . '/src/RuleSet/Sets/PSR1Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PSR2Set' => $baseDir . '/src/RuleSet/Sets/PSR2Set.php',
'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerRiskySet' => $baseDir . '/src/RuleSet/Sets/PhpCsFixerRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerSet' => $baseDir . '/src/RuleSet/Sets/PhpCsFixerSet.php',
'PhpCsFixer\\RuleSet\\Sets\\SymfonyRiskySet' => $baseDir . '/src/RuleSet/Sets/SymfonyRiskySet.php',
'PhpCsFixer\\RuleSet\\Sets\\SymfonySet' => $baseDir . '/src/RuleSet/Sets/SymfonySet.php',
'PhpCsFixer\\Runner\\FileCachingLintingIterator' => $baseDir . '/src/Runner/FileCachingLintingIterator.php',
'PhpCsFixer\\Runner\\FileFilterIterator' => $baseDir . '/src/Runner/FileFilterIterator.php',
'PhpCsFixer\\Runner\\FileLintingIterator' => $baseDir . '/src/Runner/FileLintingIterator.php',
'PhpCsFixer\\Runner\\Runner' => $baseDir . '/src/Runner/Runner.php',
'PhpCsFixer\\StdinFileInfo' => $baseDir . '/src/StdinFileInfo.php',
'PhpCsFixer\\Test\\AbstractFixerTestCase' => $baseDir . '/src/Test/AbstractFixerTestCase.php',
'PhpCsFixer\\Test\\AbstractIntegrationTestCase' => $baseDir . '/src/Test/AbstractIntegrationTestCase.php',
'PhpCsFixer\\Test\\AccessibleObject' => $baseDir . '/src/Test/AccessibleObject.php',
'PhpCsFixer\\Test\\IntegrationCase' => $baseDir . '/src/Test/IntegrationCase.php',
'PhpCsFixer\\Tests\\InterimTestCase' => $baseDir . '/tests/TestCase.php',
'PhpCsFixer\\Tests\\TestCase' => $baseDir . '/tests/TestCase.php',
'PhpCsFixer\\Tests\\Test\\AbstractFixerTestCase' => $baseDir . '/tests/Test/AbstractFixerTestCase.php',
'PhpCsFixer\\Tests\\Test\\AbstractIntegrationCaseFactory' => $baseDir . '/tests/Test/AbstractIntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\AbstractIntegrationTestCase' => $baseDir . '/tests/Test/AbstractIntegrationTestCase.php',
'PhpCsFixer\\Tests\\Test\\Assert\\AssertTokensTrait' => $baseDir . '/tests/Test/Assert/AssertTokensTrait.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCase' => $baseDir . '/tests/Test/IntegrationCase.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCaseFactory' => $baseDir . '/tests/Test/IntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\IntegrationCaseFactoryInterface' => $baseDir . '/tests/Test/IntegrationCaseFactoryInterface.php',
'PhpCsFixer\\Tests\\Test\\InternalIntegrationCaseFactory' => $baseDir . '/tests/Test/InternalIntegrationCaseFactory.php',
'PhpCsFixer\\Tests\\Test\\IsIdenticalConstraint' => $baseDir . '/tests/Test/IsIdenticalConstraint.php',
'PhpCsFixer\\Tokenizer\\AbstractTransformer' => $baseDir . '/src/Tokenizer/AbstractTransformer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\ArgumentAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\CaseAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceUseAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\StartEndTokenAwareAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\SwitchAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\TypeAnalysis' => $baseDir . '/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ArgumentsAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\BlocksAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/BlocksAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ClassyAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/ClassyAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\CommentsAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/CommentsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\FunctionsAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/FunctionsAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\GotoLabelAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\NamespaceUsesAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\NamespacesAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/NamespacesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\ReferenceAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/ReferenceAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\SwitchAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/SwitchAnalyzer.php',
'PhpCsFixer\\Tokenizer\\Analyzer\\WhitespacesAnalyzer' => $baseDir . '/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php',
'PhpCsFixer\\Tokenizer\\CT' => $baseDir . '/src/Tokenizer/CT.php',
'PhpCsFixer\\Tokenizer\\CodeHasher' => $baseDir . '/src/Tokenizer/CodeHasher.php',
'PhpCsFixer\\Tokenizer\\Generator\\NamespacedStringTokenGenerator' => $baseDir . '/src/Tokenizer/Generator/NamespacedStringTokenGenerator.php',
'PhpCsFixer\\Tokenizer\\Resolver\\TypeShortNameResolver' => $baseDir . '/src/Tokenizer/Resolver/TypeShortNameResolver.php',
'PhpCsFixer\\Tokenizer\\Token' => $baseDir . '/src/Tokenizer/Token.php',
'PhpCsFixer\\Tokenizer\\Tokens' => $baseDir . '/src/Tokenizer/Tokens.php',
'PhpCsFixer\\Tokenizer\\TokensAnalyzer' => $baseDir . '/src/Tokenizer/TokensAnalyzer.php',
'PhpCsFixer\\Tokenizer\\TransformerInterface' => $baseDir . '/src/Tokenizer/TransformerInterface.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ArrayTypehintTransformer' => $baseDir . '/src/Tokenizer/Transformer/ArrayTypehintTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\AttributeTransformer' => $baseDir . '/src/Tokenizer/Transformer/AttributeTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\BraceClassInstantiationTransformer' => $baseDir . '/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ClassConstantTransformer' => $baseDir . '/src/Tokenizer/Transformer/ClassConstantTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ConstructorPromotionTransformer' => $baseDir . '/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\CurlyBraceTransformer' => $baseDir . '/src/Tokenizer/Transformer/CurlyBraceTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ImportTransformer' => $baseDir . '/src/Tokenizer/Transformer/ImportTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NameQualifiedTransformer' => $baseDir . '/src/Tokenizer/Transformer/NameQualifiedTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NamedArgumentTransformer' => $baseDir . '/src/Tokenizer/Transformer/NamedArgumentTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NamespaceOperatorTransformer' => $baseDir . '/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\NullableTypeTransformer' => $baseDir . '/src/Tokenizer/Transformer/NullableTypeTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\ReturnRefTransformer' => $baseDir . '/src/Tokenizer/Transformer/ReturnRefTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\SquareBraceTransformer' => $baseDir . '/src/Tokenizer/Transformer/SquareBraceTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\TypeAlternationTransformer' => $baseDir . '/src/Tokenizer/Transformer/TypeAlternationTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\TypeColonTransformer' => $baseDir . '/src/Tokenizer/Transformer/TypeColonTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\UseTransformer' => $baseDir . '/src/Tokenizer/Transformer/UseTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformer\\WhitespacyCommentTransformer' => $baseDir . '/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php',
'PhpCsFixer\\Tokenizer\\Transformers' => $baseDir . '/src/Tokenizer/Transformers.php',
'PhpCsFixer\\ToolInfo' => $baseDir . '/src/ToolInfo.php',
'PhpCsFixer\\ToolInfoInterface' => $baseDir . '/src/ToolInfoInterface.php',
'PhpCsFixer\\Utils' => $baseDir . '/src/Utils.php',
'PhpCsFixer\\WhitespacesFixerConfig' => $baseDir . '/src/WhitespacesFixerConfig.php',
'PhpCsFixer\\WordMatcher' => $baseDir . '/src/WordMatcher.php',
'Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerAwareInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerAwareInterface.php',
'Psr\\Log\\LoggerAwareTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerAwareTrait.php',
'Psr\\Log\\LoggerInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => $vendorDir . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => $vendorDir . '/psr/log/Psr/Log/Test/DummyTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\TestLogger' => $vendorDir . '/psr/log/Psr/Log/Test/TestLogger.php',
'SessionUpdateTimestampHandlerInterface' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php',
'Symfony\\Component\\Console\\Application' => $vendorDir . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\CommandLoader\\CommandLoaderInterface' => $vendorDir . '/symfony/console/CommandLoader/CommandLoaderInterface.php',
'Symfony\\Component\\Console\\CommandLoader\\ContainerCommandLoader' => $vendorDir . '/symfony/console/CommandLoader/ContainerCommandLoader.php',
'Symfony\\Component\\Console\\CommandLoader\\FactoryCommandLoader' => $vendorDir . '/symfony/console/CommandLoader/FactoryCommandLoader.php',
'Symfony\\Component\\Console\\Command\\Command' => $vendorDir . '/symfony/console/Command/Command.php',
'Symfony\\Component\\Console\\Command\\HelpCommand' => $vendorDir . '/symfony/console/Command/HelpCommand.php',
'Symfony\\Component\\Console\\Command\\ListCommand' => $vendorDir . '/symfony/console/Command/ListCommand.php',
'Symfony\\Component\\Console\\Command\\LockableTrait' => $vendorDir . '/symfony/console/Command/LockableTrait.php',
'Symfony\\Component\\Console\\ConsoleEvents' => $vendorDir . '/symfony/console/ConsoleEvents.php',
'Symfony\\Component\\Console\\DependencyInjection\\AddConsoleCommandPass' => $vendorDir . '/symfony/console/DependencyInjection/AddConsoleCommandPass.php',
'Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => $vendorDir . '/symfony/console/Descriptor/ApplicationDescription.php',
'Symfony\\Component\\Console\\Descriptor\\Descriptor' => $vendorDir . '/symfony/console/Descriptor/Descriptor.php',
'Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => $vendorDir . '/symfony/console/Descriptor/DescriptorInterface.php',
'Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => $vendorDir . '/symfony/console/Descriptor/JsonDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => $vendorDir . '/symfony/console/Descriptor/MarkdownDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => $vendorDir . '/symfony/console/Descriptor/TextDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => $vendorDir . '/symfony/console/Descriptor/XmlDescriptor.php',
'Symfony\\Component\\Console\\EventListener\\ErrorListener' => $vendorDir . '/symfony/console/EventListener/ErrorListener.php',
'Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => $vendorDir . '/symfony/console/Event/ConsoleCommandEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleErrorEvent' => $vendorDir . '/symfony/console/Event/ConsoleErrorEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleEvent' => $vendorDir . '/symfony/console/Event/ConsoleEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleExceptionEvent' => $vendorDir . '/symfony/console/Event/ConsoleExceptionEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => $vendorDir . '/symfony/console/Event/ConsoleTerminateEvent.php',
'Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => $vendorDir . '/symfony/console/Exception/CommandNotFoundException.php',
'Symfony\\Component\\Console\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/console/Exception/ExceptionInterface.php',
'Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/console/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Console\\Exception\\InvalidOptionException' => $vendorDir . '/symfony/console/Exception/InvalidOptionException.php',
'Symfony\\Component\\Console\\Exception\\LogicException' => $vendorDir . '/symfony/console/Exception/LogicException.php',
'Symfony\\Component\\Console\\Exception\\RuntimeException' => $vendorDir . '/symfony/console/Exception/RuntimeException.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatter' => $vendorDir . '/symfony/console/Formatter/OutputFormatter.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyle.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleStack.php',
'Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => $vendorDir . '/symfony/console/Helper/DebugFormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\DescriptorHelper' => $vendorDir . '/symfony/console/Helper/DescriptorHelper.php',
'Symfony\\Component\\Console\\Helper\\FormatterHelper' => $vendorDir . '/symfony/console/Helper/FormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\Helper' => $vendorDir . '/symfony/console/Helper/Helper.php',
'Symfony\\Component\\Console\\Helper\\HelperInterface' => $vendorDir . '/symfony/console/Helper/HelperInterface.php',
'Symfony\\Component\\Console\\Helper\\HelperSet' => $vendorDir . '/symfony/console/Helper/HelperSet.php',
'Symfony\\Component\\Console\\Helper\\InputAwareHelper' => $vendorDir . '/symfony/console/Helper/InputAwareHelper.php',
'Symfony\\Component\\Console\\Helper\\ProcessHelper' => $vendorDir . '/symfony/console/Helper/ProcessHelper.php',
'Symfony\\Component\\Console\\Helper\\ProgressBar' => $vendorDir . '/symfony/console/Helper/ProgressBar.php',
'Symfony\\Component\\Console\\Helper\\ProgressIndicator' => $vendorDir . '/symfony/console/Helper/ProgressIndicator.php',
'Symfony\\Component\\Console\\Helper\\QuestionHelper' => $vendorDir . '/symfony/console/Helper/QuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => $vendorDir . '/symfony/console/Helper/SymfonyQuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\Table' => $vendorDir . '/symfony/console/Helper/Table.php',
'Symfony\\Component\\Console\\Helper\\TableCell' => $vendorDir . '/symfony/console/Helper/TableCell.php',
'Symfony\\Component\\Console\\Helper\\TableSeparator' => $vendorDir . '/symfony/console/Helper/TableSeparator.php',
'Symfony\\Component\\Console\\Helper\\TableStyle' => $vendorDir . '/symfony/console/Helper/TableStyle.php',
'Symfony\\Component\\Console\\Input\\ArgvInput' => $vendorDir . '/symfony/console/Input/ArgvInput.php',
'Symfony\\Component\\Console\\Input\\ArrayInput' => $vendorDir . '/symfony/console/Input/ArrayInput.php',
'Symfony\\Component\\Console\\Input\\Input' => $vendorDir . '/symfony/console/Input/Input.php',
'Symfony\\Component\\Console\\Input\\InputArgument' => $vendorDir . '/symfony/console/Input/InputArgument.php',
'Symfony\\Component\\Console\\Input\\InputAwareInterface' => $vendorDir . '/symfony/console/Input/InputAwareInterface.php',
'Symfony\\Component\\Console\\Input\\InputDefinition' => $vendorDir . '/symfony/console/Input/InputDefinition.php',
'Symfony\\Component\\Console\\Input\\InputInterface' => $vendorDir . '/symfony/console/Input/InputInterface.php',
'Symfony\\Component\\Console\\Input\\InputOption' => $vendorDir . '/symfony/console/Input/InputOption.php',
'Symfony\\Component\\Console\\Input\\StreamableInputInterface' => $vendorDir . '/symfony/console/Input/StreamableInputInterface.php',
'Symfony\\Component\\Console\\Input\\StringInput' => $vendorDir . '/symfony/console/Input/StringInput.php',
'Symfony\\Component\\Console\\Logger\\ConsoleLogger' => $vendorDir . '/symfony/console/Logger/ConsoleLogger.php',
'Symfony\\Component\\Console\\Output\\BufferedOutput' => $vendorDir . '/symfony/console/Output/BufferedOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutput' => $vendorDir . '/symfony/console/Output/ConsoleOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => $vendorDir . '/symfony/console/Output/ConsoleOutputInterface.php',
'Symfony\\Component\\Console\\Output\\NullOutput' => $vendorDir . '/symfony/console/Output/NullOutput.php',
'Symfony\\Component\\Console\\Output\\Output' => $vendorDir . '/symfony/console/Output/Output.php',
'Symfony\\Component\\Console\\Output\\OutputInterface' => $vendorDir . '/symfony/console/Output/OutputInterface.php',
'Symfony\\Component\\Console\\Output\\StreamOutput' => $vendorDir . '/symfony/console/Output/StreamOutput.php',
'Symfony\\Component\\Console\\Question\\ChoiceQuestion' => $vendorDir . '/symfony/console/Question/ChoiceQuestion.php',
'Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => $vendorDir . '/symfony/console/Question/ConfirmationQuestion.php',
'Symfony\\Component\\Console\\Question\\Question' => $vendorDir . '/symfony/console/Question/Question.php',
'Symfony\\Component\\Console\\Style\\OutputStyle' => $vendorDir . '/symfony/console/Style/OutputStyle.php',
'Symfony\\Component\\Console\\Style\\StyleInterface' => $vendorDir . '/symfony/console/Style/StyleInterface.php',
'Symfony\\Component\\Console\\Style\\SymfonyStyle' => $vendorDir . '/symfony/console/Style/SymfonyStyle.php',
'Symfony\\Component\\Console\\Terminal' => $vendorDir . '/symfony/console/Terminal.php',
'Symfony\\Component\\Console\\Tester\\ApplicationTester' => $vendorDir . '/symfony/console/Tester/ApplicationTester.php',
'Symfony\\Component\\Console\\Tester\\CommandTester' => $vendorDir . '/symfony/console/Tester/CommandTester.php',
'Symfony\\Component\\Debug\\BufferingLogger' => $vendorDir . '/symfony/debug/BufferingLogger.php',
'Symfony\\Component\\Debug\\Debug' => $vendorDir . '/symfony/debug/Debug.php',
'Symfony\\Component\\Debug\\DebugClassLoader' => $vendorDir . '/symfony/debug/DebugClassLoader.php',
'Symfony\\Component\\Debug\\ErrorHandler' => $vendorDir . '/symfony/debug/ErrorHandler.php',
'Symfony\\Component\\Debug\\ExceptionHandler' => $vendorDir . '/symfony/debug/ExceptionHandler.php',
'Symfony\\Component\\Debug\\Exception\\ClassNotFoundException' => $vendorDir . '/symfony/debug/Exception/ClassNotFoundException.php',
'Symfony\\Component\\Debug\\Exception\\ContextErrorException' => $vendorDir . '/symfony/debug/Exception/ContextErrorException.php',
'Symfony\\Component\\Debug\\Exception\\FatalErrorException' => $vendorDir . '/symfony/debug/Exception/FatalErrorException.php',
'Symfony\\Component\\Debug\\Exception\\FatalThrowableError' => $vendorDir . '/symfony/debug/Exception/FatalThrowableError.php',
'Symfony\\Component\\Debug\\Exception\\FlattenException' => $vendorDir . '/symfony/debug/Exception/FlattenException.php',
'Symfony\\Component\\Debug\\Exception\\OutOfMemoryException' => $vendorDir . '/symfony/debug/Exception/OutOfMemoryException.php',
'Symfony\\Component\\Debug\\Exception\\SilencedErrorContext' => $vendorDir . '/symfony/debug/Exception/SilencedErrorContext.php',
'Symfony\\Component\\Debug\\Exception\\UndefinedFunctionException' => $vendorDir . '/symfony/debug/Exception/UndefinedFunctionException.php',
'Symfony\\Component\\Debug\\Exception\\UndefinedMethodException' => $vendorDir . '/symfony/debug/Exception/UndefinedMethodException.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\ClassNotFoundFatalErrorHandler' => $vendorDir . '/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\FatalErrorHandlerInterface' => $vendorDir . '/symfony/debug/FatalErrorHandler/FatalErrorHandlerInterface.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\UndefinedFunctionFatalErrorHandler' => $vendorDir . '/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php',
'Symfony\\Component\\Debug\\FatalErrorHandler\\UndefinedMethodFatalErrorHandler' => $vendorDir . '/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php',
'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/ContainerAwareEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener' => $vendorDir . '/symfony/event-dispatcher/Debug/WrappedListener.php',
'Symfony\\Component\\EventDispatcher\\DependencyInjection\\RegisterListenersPass' => $vendorDir . '/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php',
'Symfony\\Component\\EventDispatcher\\Event' => $vendorDir . '/symfony/event-dispatcher/Event.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcher' => $vendorDir . '/symfony/event-dispatcher/EventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/EventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface' => $vendorDir . '/symfony/event-dispatcher/EventSubscriberInterface.php',
'Symfony\\Component\\EventDispatcher\\GenericEvent' => $vendorDir . '/symfony/event-dispatcher/GenericEvent.php',
'Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/ImmutableEventDispatcher.php',
'Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/ExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => $vendorDir . '/symfony/filesystem/Exception/FileNotFoundException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOException' => $vendorDir . '/symfony/filesystem/Exception/IOException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/IOExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Filesystem' => $vendorDir . '/symfony/filesystem/Filesystem.php',
'Symfony\\Component\\Filesystem\\LockHandler' => $vendorDir . '/symfony/filesystem/LockHandler.php',
'Symfony\\Component\\Finder\\Comparator\\Comparator' => $vendorDir . '/symfony/finder/Comparator/Comparator.php',
'Symfony\\Component\\Finder\\Comparator\\DateComparator' => $vendorDir . '/symfony/finder/Comparator/DateComparator.php',
'Symfony\\Component\\Finder\\Comparator\\NumberComparator' => $vendorDir . '/symfony/finder/Comparator/NumberComparator.php',
'Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => $vendorDir . '/symfony/finder/Exception/AccessDeniedException.php',
'Symfony\\Component\\Finder\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/finder/Exception/ExceptionInterface.php',
'Symfony\\Component\\Finder\\Finder' => $vendorDir . '/symfony/finder/Finder.php',
'Symfony\\Component\\Finder\\Glob' => $vendorDir . '/symfony/finder/Glob.php',
'Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => $vendorDir . '/symfony/finder/Iterator/CustomFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => $vendorDir . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => $vendorDir . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => $vendorDir . '/symfony/finder/Iterator/PathFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => $vendorDir . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SortableIterator' => $vendorDir . '/symfony/finder/Iterator/SortableIterator.php',
'Symfony\\Component\\Finder\\SplFileInfo' => $vendorDir . '/symfony/finder/SplFileInfo.php',
'Symfony\\Component\\OptionsResolver\\Debug\\OptionsResolverIntrospector' => $vendorDir . '/symfony/options-resolver/Debug/OptionsResolverIntrospector.php',
'Symfony\\Component\\OptionsResolver\\Exception\\AccessException' => $vendorDir . '/symfony/options-resolver/Exception/AccessException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/options-resolver/Exception/ExceptionInterface.php',
'Symfony\\Component\\OptionsResolver\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/options-resolver/Exception/InvalidArgumentException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/InvalidOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\MissingOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/MissingOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\NoConfigurationException' => $vendorDir . '/symfony/options-resolver/Exception/NoConfigurationException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\NoSuchOptionException' => $vendorDir . '/symfony/options-resolver/Exception/NoSuchOptionException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\OptionDefinitionException' => $vendorDir . '/symfony/options-resolver/Exception/OptionDefinitionException.php',
'Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/UndefinedOptionsException.php',
'Symfony\\Component\\OptionsResolver\\Options' => $vendorDir . '/symfony/options-resolver/Options.php',
'Symfony\\Component\\OptionsResolver\\OptionsResolver' => $vendorDir . '/symfony/options-resolver/OptionsResolver.php',
'Symfony\\Component\\Process\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/process/Exception/ExceptionInterface.php',
'Symfony\\Component\\Process\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/process/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Process\\Exception\\LogicException' => $vendorDir . '/symfony/process/Exception/LogicException.php',
'Symfony\\Component\\Process\\Exception\\ProcessFailedException' => $vendorDir . '/symfony/process/Exception/ProcessFailedException.php',
'Symfony\\Component\\Process\\Exception\\ProcessTimedOutException' => $vendorDir . '/symfony/process/Exception/ProcessTimedOutException.php',
'Symfony\\Component\\Process\\Exception\\RuntimeException' => $vendorDir . '/symfony/process/Exception/RuntimeException.php',
'Symfony\\Component\\Process\\ExecutableFinder' => $vendorDir . '/symfony/process/ExecutableFinder.php',
'Symfony\\Component\\Process\\InputStream' => $vendorDir . '/symfony/process/InputStream.php',
'Symfony\\Component\\Process\\PhpExecutableFinder' => $vendorDir . '/symfony/process/PhpExecutableFinder.php',
'Symfony\\Component\\Process\\PhpProcess' => $vendorDir . '/symfony/process/PhpProcess.php',
'Symfony\\Component\\Process\\Pipes\\AbstractPipes' => $vendorDir . '/symfony/process/Pipes/AbstractPipes.php',
'Symfony\\Component\\Process\\Pipes\\PipesInterface' => $vendorDir . '/symfony/process/Pipes/PipesInterface.php',
'Symfony\\Component\\Process\\Pipes\\UnixPipes' => $vendorDir . '/symfony/process/Pipes/UnixPipes.php',
'Symfony\\Component\\Process\\Pipes\\WindowsPipes' => $vendorDir . '/symfony/process/Pipes/WindowsPipes.php',
'Symfony\\Component\\Process\\Process' => $vendorDir . '/symfony/process/Process.php',
'Symfony\\Component\\Process\\ProcessBuilder' => $vendorDir . '/symfony/process/ProcessBuilder.php',
'Symfony\\Component\\Process\\ProcessUtils' => $vendorDir . '/symfony/process/ProcessUtils.php',
'Symfony\\Component\\Stopwatch\\Section' => $vendorDir . '/symfony/stopwatch/Section.php',
'Symfony\\Component\\Stopwatch\\Stopwatch' => $vendorDir . '/symfony/stopwatch/Stopwatch.php',
'Symfony\\Component\\Stopwatch\\StopwatchEvent' => $vendorDir . '/symfony/stopwatch/StopwatchEvent.php',
'Symfony\\Component\\Stopwatch\\StopwatchPeriod' => $vendorDir . '/symfony/stopwatch/StopwatchPeriod.php',
'Symfony\\Polyfill\\Ctype\\Ctype' => $vendorDir . '/symfony/polyfill-ctype/Ctype.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php',
'Symfony\\Polyfill\\Php70\\Php70' => $vendorDir . '/symfony/polyfill-php70/Php70.php',
'Symfony\\Polyfill\\Php72\\Php72' => $vendorDir . '/symfony/polyfill-php72/Php72.php',
'TypeError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/TypeError.php',
);
<?php
$issues = array();
if (!(PHP_VERSION_ID >= 50600)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 5.6.0". You are running ' . PHP_VERSION . '.';
}
$missingExtensions = array();
extension_loaded('json') || $missingExtensions[] = 'json';
extension_loaded('tokenizer') || $missingExtensions[] = 'tokenizer';
if ($missingExtensions) {
$issues[] = 'Your Composer dependencies require the following PHP extensions to be installed: ' . implode(', ', $missingExtensions);
}
if ($issues) {
echo 'Composer detected issues in your platform:' . "\n\n" . implode("\n", $issues);
exit(104);
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
class CompilingMatcher
{
private static $compiledCheckerCache = array();
private static $enabled;
/**
@phpstan
*/
private static $transOpInt = array(
Constraint::OP_EQ => '==',
Constraint::OP_LT => '<',
Constraint::OP_LE => '<=',
Constraint::OP_GT => '>',
Constraint::OP_GE => '>=',
Constraint::OP_NE => '!=',
);
/**
@phpstan
*/
public static function match(ConstraintInterface $constraint, $operator, $version)
{
if (self::$enabled === null) {
self::$enabled = !\in_array('eval', explode(',', ini_get('disable_functions')), true);
}
if (!self::$enabled) {
return $constraint->matches(new Constraint(self::$transOpInt[$operator], $version));
}
$cacheKey = $operator.$constraint;
if (!isset(self::$compiledCheckerCache[$cacheKey])) {
$code = $constraint->compile($operator);
self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};');
} else {
$function = self::$compiledCheckerCache[$cacheKey];
}
return $function($version, strpos($version, 'dev-') === 0);
}
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Interval
{
private $start;
private $end;
public function __construct(Constraint $start, Constraint $end)
{
$this->start = $start;
$this->end = $end;
}
public function getStart()
{
return $this->start;
}
public function getEnd()
{
return $this->end;
}
public static function fromZero()
{
static $zero;
if (null === $zero) {
$zero = new Constraint('>=', '0.0.0.0-dev');
}
return $zero;
}
public static function untilPositiveInfinity()
{
static $positiveInfinity;
if (null === $positiveInfinity) {
$positiveInfinity = new Constraint('<', PHP_INT_MAX.'.0.0.0');
}
return $positiveInfinity;
}
public static function any()
{
return new self(self::fromZero(), self::untilPositiveInfinity());
}
public static function anyDev()
{
return array('names' => array(), 'exclude' => true);
}
public static function noDev()
{
return array('names' => array(), 'exclude' => false);
}
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
use Composer\Semver\Constraint\Constraint;
class VersionParser
{
private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?';
private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev';
public static function parseStability($version)
{
$version = preg_replace('{#.+$}', '', $version);
if (strpos($version, 'dev-') === 0 || '-dev' === substr($version, -4)) {
return 'dev';
}
preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match);
if (!empty($match[3])) {
return 'dev';
}
if (!empty($match[1])) {
if ('beta' === $match[1] || 'b' === $match[1]) {
return 'beta';
}
if ('alpha' === $match[1] || 'a' === $match[1]) {
return 'alpha';
}
if ('rc' === $match[1]) {
return 'RC';
}
}
return 'stable';
}
public static function normalizeStability($stability)
{
$stability = strtolower($stability);
return $stability === 'rc' ? 'RC' : $stability;
}
public function normalize($version, $fullVersion = null)
{
$version = trim($version);
$origVersion = $version;
if (null === $fullVersion) {
$fullVersion = $version;
}
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) {
$version = $match[1];
}
if (preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) {
$version = substr($version, 0, strlen($version) - strlen($match[0]));
}
if (\in_array($version, array('master', 'trunk', 'default'), true)) {
$version = 'dev-' . $version;
}
if (stripos($version, 'dev-') === 0) {
return 'dev-' . substr($version, 4);
}
if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) {
$version = $match[1];
}
if (preg_match('{^v?(\d{1,5})(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = $matches[1]
. (!empty($matches[2]) ? $matches[2] : '.0')
. (!empty($matches[3]) ? $matches[3] : '.0')
. (!empty($matches[4]) ? $matches[4] : '.0');
$index = 5;
} elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = preg_replace('{\D}', '.', $matches[1]);
$index = 2;
}
if (isset($index)) {
if (!empty($matches[$index])) {
if ('stable' === $matches[$index]) {
return $version;
}
$version .= '-' . $this->expandStability($matches[$index]) . (isset($matches[$index + 1]) && '' !== $matches[$index + 1] ? ltrim($matches[$index + 1], '.-') : '');
}
if (!empty($matches[$index + 2])) {
$version .= '-dev';
}
return $version;
}
if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
try {
$normalized = $this->normalizeBranch($match[1]);
if (strpos($normalized, 'dev-') === false) {
return $normalized;
}
} catch (\Exception $e) {
}
}
$extraMessage = '';
if (preg_match('{ +as +' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))?$}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version';
} elseif (preg_match('{^' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))? +as +}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
}
throw new \UnexpectedValueException('Invalid version string "' . $origVersion . '"' . $extraMessage);
}
public function parseNumericAliasPrefix($branch)
{
if (preg_match('{^(?P<version>(\d++\\.)*\d++)(?:\.x)?-dev$}i', $branch, $matches)) {
return $matches['version'] . '.';
}
return false;
}
public function normalizeBranch($name)
{
$name = trim($name);
if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) {
$version = '';
for ($i = 1; $i < 5; ++$i) {
$version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
}
return str_replace('x', '9999999', $version) . '-dev';
}
return 'dev-' . $name;
}
public function normalizeDefaultBranch($name)
{
if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') {
return '9999999-dev';
}
return $name;
}
public function parseConstraints($constraints)
{
$prettyConstraint = $constraints;
$orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints));
$orGroups = array();
foreach ($orConstraints as $constraints) {
$andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
if (\count($andConstraints) > 1) {
$constraintObjects = array();
foreach ($andConstraints as $constraint) {
foreach ($this->parseConstraint($constraint) as $parsedConstraint) {
$constraintObjects[] = $parsedConstraint;
}
}
} else {
$constraintObjects = $this->parseConstraint($andConstraints[0]);
}
if (1 === \count($constraintObjects)) {
$constraint = $constraintObjects[0];
} else {
$constraint = new MultiConstraint($constraintObjects);
}
$orGroups[] = $constraint;
}
$constraint = MultiConstraint::create($orGroups, false);
$constraint->setPrettyString($prettyConstraint);
return $constraint;
}
private function parseConstraint($constraint)
{
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $constraint, $match)) {
$constraint = $match[1];
}
if (preg_match('{^([^,\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) {
$constraint = '' !== $match[1] ? $match[1] : '*';
if ($match[2] !== 'stable') {
$stabilityModifier = $match[2];
}
}
if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraint, $match)) {
$constraint = $match[1];
}
if (preg_match('{^(v)?[xX*](\.[xX*])*$}i', $constraint, $match)) {
if (!empty($match[1]) || !empty($match[2])) {
return array(new Constraint('>=', '0.0.0.0-dev'));
}
return array(new MatchAllConstraint());
}
$versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?(?:' . self::$modifierRegex . '|\.([xX*][.-]?dev))(?:\+[^\s]+)?';
if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) {
if (strpos($constraint, '~>') === 0) {
throw new \UnexpectedValueException(
'Could not parse version constraint ' . $constraint . ': ' .
'Invalid operator "~>", you probably meant to use the "~" operator'
);
}
if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) {
$position = 4;
} elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
if (!empty($matches[8])) {
$position++;
}
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
$highPosition = max(1, $position - 1);
$highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) {
if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) {
$position = 1;
} elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) {
$position = 2;
} else {
$position = 3;
}
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) {
if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
$lowVersion = $this->manipulateVersionString($matches, $position) . '-dev';
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
if ($lowVersion === '0.0.0.0-dev') {
return array(new Constraint('<', $highVersion));
}
return array(
new Constraint('>=', $lowVersion),
new Constraint('<', $highVersion),
);
}
if (preg_match('{^(?P<from>' . $versionRegex . ') +- +(?P<to>' . $versionRegex . ')($)}i', $constraint, $matches)) {
$lowStabilitySuffix = '';
if (empty($matches[6]) && empty($matches[8]) && empty($matches[9])) {
$lowStabilitySuffix = '-dev';
}
$lowVersion = $this->normalize($matches['from']);
$lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix);
$empty = function ($x) {
return ($x === 0 || $x === '0') ? false : empty($x);
};
if ((!$empty($matches[12]) && !$empty($matches[13])) || !empty($matches[15]) || !empty($matches[17]) || !empty($matches[18])) {
$highVersion = $this->normalize($matches['to']);
$upperBound = new Constraint('<=', $highVersion);
} else {
$highMatch = array('', $matches[11], $matches[12], $matches[13], $matches[14]);
$this->normalize($matches['to']);
$highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
}
return array(
$lowerBound,
$upperBound,
);
}
if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
try {
try {
$version = $this->normalize($matches[2]);
} catch (\UnexpectedValueException $e) {
if (substr($matches[2], -4) === '-dev' && preg_match('{^[0-9a-zA-Z-./]+$}', $matches[2])) {
$version = $this->normalize('dev-'.substr($matches[2], 0, -4));
} else {
throw $e;
}
}
$op = $matches[1] ?: '=';
if ($op !== '==' && $op !== '=' && !empty($stabilityModifier) && self::parseStability($version) === 'stable') {
$version .= '-' . $stabilityModifier;
} elseif ('<' === $op || '>=' === $op) {
if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
if (strpos($matches[2], 'dev-') !== 0) {
$version .= '-dev';
}
}
}
return array(new Constraint($matches[1] ?: '=', $version));
} catch (\Exception $e) {
}
}
$message = 'Could not parse version constraint ' . $constraint;
if (isset($e)) {
$message .= ': ' . $e->getMessage();
}
throw new \UnexpectedValueException($message);
}
private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0')
{
for ($i = 4; $i > 0; --$i) {
if ($i > $position) {
$matches[$i] = $pad;
} elseif ($i === $position && $increment) {
$matches[$i] += $increment;
if ($matches[$i] < 0) {
$matches[$i] = $pad;
--$position;
if ($i === 1) {
return null;
}
}
}
}
return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
}
private function expandStability($stability)
{
$stability = strtolower($stability);
switch ($stability) {
case 'a':
return 'alpha';
case 'b':
return 'beta';
case 'p':
case 'pl':
return 'patch';
case 'rc':
return 'RC';
default:
return $stability;
}
}
}
<?php
namespace Composer\Semver\Constraint;
class MatchAllConstraint implements ConstraintInterface
{
protected $prettyString;
public function matches(ConstraintInterface $provider)
{
return true;
}
public function compile($operator)
{
return 'true';
}
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
public function __toString()
{
return '*';
}
public function getUpperBound()
{
return Bound::positiveInfinity();
}
public function getLowerBound()
{
return Bound::zero();
}
}
<?php
namespace Composer\Semver\Constraint;
class Constraint implements ConstraintInterface
{
const OP_EQ = 0;
const OP_LT = 1;
const OP_LE = 2;
const OP_GT = 3;
const OP_GE = 4;
const OP_NE = 5;
/**
@phpstan
*/
private static $transOpStr = array(
'=' => self::OP_EQ,
'==' => self::OP_EQ,
'<' => self::OP_LT,
'<=' => self::OP_LE,
'>' => self::OP_GT,
'>=' => self::OP_GE,
'<>' => self::OP_NE,
'!=' => self::OP_NE,
);
/**
@phpstan
*/
private static $transOpInt = array(
self::OP_EQ => '==',
self::OP_LT => '<',
self::OP_LE => '<=',
self::OP_GT => '>',
self::OP_GE => '>=',
self::OP_NE => '!=',
);
/**
@phpstan
*/
protected $operator;
protected $version;
protected $prettyString;
protected $lowerBound;
protected $upperBound;
public function __construct($operator, $version)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$this->operator = self::$transOpStr[$operator];
$this->version = $version;
}
public function getVersion()
{
return $this->version;
}
public function getOperator()
{
return self::$transOpInt[$this->operator];
}
public function matches(ConstraintInterface $provider)
{
if ($provider instanceof self) {
return $this->matchSpecific($provider);
}
return $provider->matches($this);
}
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return $this->__toString();
}
public static function getSupportedOperators()
{
return array_keys(self::$transOpStr);
}
/**
@phpstan
*/
public static function getOperatorConstant($operator)
{
return self::$transOpStr[$operator];
}
public function versionCompare($a, $b, $operator, $compareBranches = false)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$aIsBranch = strpos($a, 'dev-') === 0;
$bIsBranch = strpos($b, 'dev-') === 0;
if ($operator === '!=' && ($aIsBranch || $bIsBranch)) {
return $a !== $b;
}
if ($aIsBranch && $bIsBranch) {
return $operator === '==' && $a === $b;
}
if (!$compareBranches && ($aIsBranch || $bIsBranch)) {
return false;
}
return \version_compare($a, $b, $operator);
}
public function compile($otherOperator)
{
if (strpos($this->version, 'dev-') === 0) {
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b && $v === %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
return 'false';
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
return 'false';
}
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('\version_compare($v, %s, \'==\')', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('$b || \version_compare($v, %s, \'!=\')', \var_export($this->version, true));
}
return sprintf('!$b && \version_compare(%s, $v, \'%s\')', \var_export($this->version, true), self::$transOpInt[$otherOperator]);
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b || (!$b && \version_compare($v, %s, \'!=\'))', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
if (self::OP_LT === $this->operator || self::OP_LE === $this->operator) {
if (self::OP_LT === $otherOperator || self::OP_LE === $otherOperator) {
return '!$b';
}
} elseif (self::OP_GT === $this->operator || self::OP_GE === $this->operator) {
if (self::OP_GT === $otherOperator || self::OP_GE === $otherOperator) {
return '!$b';
}
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
$codeComparison = sprintf('\version_compare($v, %s, \'%s\')', \var_export($this->version, true), self::$transOpInt[$this->operator]);
if ($this->operator === self::OP_LE) {
if ($otherOperator === self::OP_GT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
} elseif ($this->operator === self::OP_GE) {
if ($otherOperator === self::OP_LT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
}
return sprintf('!$b && %s', $codeComparison);
}
public function matchSpecific(Constraint $provider, $compareBranches = false)
{
$noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]);
$providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]);
$isEqualOp = self::OP_EQ === $this->operator;
$isNonEqualOp = self::OP_NE === $this->operator;
$isProviderEqualOp = self::OP_EQ === $provider->operator;
$isProviderNonEqualOp = self::OP_NE === $provider->operator;
if ($isNonEqualOp || $isProviderNonEqualOp) {
if ($isNonEqualOp && !$isProviderNonEqualOp && !$isProviderEqualOp && strpos($provider->version, 'dev-') === 0) {
return false;
}
if ($isProviderNonEqualOp && !$isNonEqualOp && !$isEqualOp && strpos($this->version, 'dev-') === 0) {
return false;
}
if (!$isEqualOp && !$isProviderEqualOp) {
return true;
}
return $this->versionCompare($provider->version, $this->version, '!=', $compareBranches);
}
if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) {
return !(strpos($this->version, 'dev-') === 0 || strpos($provider->version, 'dev-') === 0);
}
$version1 = $isEqualOp ? $this->version : $provider->version;
$version2 = $isEqualOp ? $provider->version : $this->version;
$operator = $isEqualOp ? $provider->operator : $this->operator;
if ($this->versionCompare($version1, $version2, self::$transOpInt[$operator], $compareBranches)) {
return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp
&& self::$transOpInt[$this->operator] !== $noEqualOp
&& \version_compare($provider->version, $this->version, '=='));
}
return false;
}
public function __toString()
{
return self::$transOpInt[$this->operator] . ' ' . $this->version;
}
public function getLowerBound()
{
$this->extractBounds();
return $this->lowerBound;
}
public function getUpperBound()
{
$this->extractBounds();
return $this->upperBound;
}
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
if (strpos($this->version, 'dev-') === 0) {
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
return;
}
switch ($this->operator) {
case self::OP_EQ:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_LT:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, false);
break;
case self::OP_LE:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_GT:
$this->lowerBound = new Bound($this->version, false);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_GE:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_NE:
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
break;
}
}
}
<?php
namespace Composer\Semver\Constraint;
interface ConstraintInterface
{
public function matches(ConstraintInterface $provider);
public function compile($operator);
public function getUpperBound();
public function getLowerBound();
public function getPrettyString();
public function setPrettyString($prettyString);
public function __toString();
}
<?php
namespace Composer\Semver\Constraint;
class MatchNoneConstraint implements ConstraintInterface
{
protected $prettyString;
public function matches(ConstraintInterface $provider)
{
return false;
}
public function compile($operator)
{
return 'false';
}
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
public function __toString()
{
return '[]';
}
public function getUpperBound()
{
return new Bound('0.0.0.0-dev', false);
}
public function getLowerBound()
{
return new Bound('0.0.0.0-dev', false);
}
}
<?php
namespace Composer\Semver\Constraint;
class Bound
{
private $version;
private $isInclusive;
public function __construct($version, $isInclusive)
{
$this->version = $version;
$this->isInclusive = $isInclusive;
}
public function getVersion()
{
return $this->version;
}
public function isInclusive()
{
return $this->isInclusive;
}
public function isZero()
{
return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive();
}
public function isPositiveInfinity()
{
return $this->getVersion() === PHP_INT_MAX.'.0.0.0' && !$this->isInclusive();
}
public function compareTo(Bound $other, $operator)
{
if (!\in_array($operator, array('<', '>'), true)) {
throw new \InvalidArgumentException('Does not support any other operator other than > or <.');
}
if ($this == $other) {
return false;
}
$compareResult = version_compare($this->getVersion(), $other->getVersion());
if (0 !== $compareResult) {
return (('>' === $operator) ? 1 : -1) === $compareResult;
}
return '>' === $operator ? $other->isInclusive() : !$other->isInclusive();
}
public function __toString()
{
return sprintf(
'%s [%s]',
$this->getVersion(),
$this->isInclusive() ? 'inclusive' : 'exclusive'
);
}
public static function zero()
{
return new Bound('0.0.0.0-dev', true);
}
public static function positiveInfinity()
{
return new Bound(PHP_INT_MAX.'.0.0.0', false);
}
}
<?php
namespace Composer\Semver\Constraint;
class MultiConstraint implements ConstraintInterface
{
protected $constraints;
protected $prettyString;
protected $string;
protected $conjunctive;
protected $lowerBound;
protected $upperBound;
public function __construct(array $constraints, $conjunctive = true)
{
if (\count($constraints) < 2) {
throw new \InvalidArgumentException(
'Must provide at least two constraints for a MultiConstraint. Use '.
'the regular Constraint class for one constraint only or MatchAllConstraint for none. You may use '.
'MultiConstraint::create() which optimizes and handles those cases automatically.'
);
}
$this->constraints = $constraints;
$this->conjunctive = $conjunctive;
}
public function getConstraints()
{
return $this->constraints;
}
public function isConjunctive()
{
return $this->conjunctive;
}
public function isDisjunctive()
{
return !$this->conjunctive;
}
public function compile($otherOperator)
{
$parts = array();
foreach ($this->constraints as $constraint) {
$code = $constraint->compile($otherOperator);
if ($code === 'true') {
if (!$this->conjunctive) {
return 'true';
}
} elseif ($code === 'false') {
if ($this->conjunctive) {
return 'false';
}
} else {
$parts[] = '('.$code.')';
}
}
if (!$parts) {
return $this->conjunctive ? 'true' : 'false';
}
return $this->conjunctive ? implode('&&', $parts) : implode('||', $parts);
}
public function matches(ConstraintInterface $provider)
{
if (false === $this->conjunctive) {
foreach ($this->constraints as $constraint) {
if ($provider->matches($constraint)) {
return true;
}
}
return false;
}
foreach ($this->constraints as $constraint) {
if (!$provider->matches($constraint)) {
return false;
}
}
return true;
}
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
public function __toString()
{
if ($this->string !== null) {
return $this->string;
}
$constraints = array();
foreach ($this->constraints as $constraint) {
$constraints[] = (string) $constraint;
}
return $this->string = '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']';
}
public function getLowerBound()
{
$this->extractBounds();
return $this->lowerBound;
}
public function getUpperBound()
{
$this->extractBounds();
return $this->upperBound;
}
public static function create(array $constraints, $conjunctive = true)
{
if (0 === \count($constraints)) {
return new MatchAllConstraint();
}
if (1 === \count($constraints)) {
return $constraints[0];
}
$optimized = self::optimizeConstraints($constraints, $conjunctive);
if ($optimized !== null) {
list($constraints, $conjunctive) = $optimized;
if (\count($constraints) === 1) {
return $constraints[0];
}
}
return new self($constraints, $conjunctive);
}
private static function optimizeConstraints(array $constraints, $conjunctive)
{
if (!$conjunctive) {
$left = $constraints[0];
$mergedConstraints = array();
$optimized = false;
for ($i = 1, $l = \count($constraints); $i < $l; $i++) {
$right = $constraints[$i];
if (
$left instanceof self
&& $left->conjunctive
&& $right instanceof self
&& $right->conjunctive
&& \count($left->constraints) === 2
&& \count($right->constraints) === 2
&& ($left0 = (string) $left->constraints[0])
&& $left0[0] === '>' && $left0[1] === '='
&& ($left1 = (string) $left->constraints[1])
&& $left1[0] === '<'
&& ($right0 = (string) $right->constraints[0])
&& $right0[0] === '>' && $right0[1] === '='
&& ($right1 = (string) $right->constraints[1])
&& $right1[0] === '<'
&& substr($left1, 2) === substr($right0, 3)
) {
$optimized = true;
$left = new MultiConstraint(
array(
$left->constraints[0],
$right->constraints[1],
),
true);
} else {
$mergedConstraints[] = $left;
$left = $right;
}
}
if ($optimized) {
$mergedConstraints[] = $left;
return array($mergedConstraints, false);
}
}
return null;
}
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
foreach ($this->constraints as $constraint) {
if (null === $this->lowerBound && null === $this->upperBound) {
$this->lowerBound = $constraint->getLowerBound();
$this->upperBound = $constraint->getUpperBound();
continue;
}
if ($constraint->getLowerBound()->compareTo($this->lowerBound, $this->isConjunctive() ? '>' : '<')) {
$this->lowerBound = $constraint->getLowerBound();
}
if ($constraint->getUpperBound()->compareTo($this->upperBound, $this->isConjunctive() ? '<' : '>')) {
$this->upperBound = $constraint->getUpperBound();
}
}
}
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Comparator
{
public static function greaterThan($version1, $version2)
{
return self::compare($version1, '>', $version2);
}
public static function greaterThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '>=', $version2);
}
public static function lessThan($version1, $version2)
{
return self::compare($version1, '<', $version2);
}
public static function lessThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '<=', $version2);
}
public static function equalTo($version1, $version2)
{
return self::compare($version1, '==', $version2);
}
public static function notEqualTo($version1, $version2)
{
return self::compare($version1, '!=', $version2);
}
public static function compare($version1, $operator, $version2)
{
$constraint = new Constraint($operator, $version2);
return $constraint->matchSpecific(new Constraint('==', $version1), true);
}
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MatchNoneConstraint;
use Composer\Semver\Constraint\MultiConstraint;
class Intervals
{
/**
@phpstan
*/
private static $intervalsCache = array();
/**
@phpstan
*/
private static $opSortOrder = array(
'>=' => -3,
'<' => -2,
'>' => 2,
'<=' => 3,
);
public static function clear()
{
self::$intervalsCache = array();
}
public static function isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint)
{
if ($constraint instanceof MatchAllConstraint) {
return true;
}
if ($candidate instanceof MatchNoneConstraint || $constraint instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::get(new MultiConstraint(array($candidate, $constraint), true));
$candidateIntervals = self::get($candidate);
if (\count($intersectionIntervals['numeric']) !== \count($candidateIntervals['numeric'])) {
return false;
}
foreach ($intersectionIntervals['numeric'] as $index => $interval) {
if (!isset($candidateIntervals['numeric'][$index])) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getStart() !== (string) $interval->getStart()) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getEnd() !== (string) $interval->getEnd()) {
return false;
}
}
if ($intersectionIntervals['branches']['exclude'] !== $candidateIntervals['branches']['exclude']) {
return false;
}
if (\count($intersectionIntervals['branches']['names']) !== \count($candidateIntervals['branches']['names'])) {
return false;
}
foreach ($intersectionIntervals['branches']['names'] as $index => $name) {
if ($name !== $candidateIntervals['branches']['names'][$index]) {
return false;
}
}
return true;
}
public static function haveIntersections(ConstraintInterface $a, ConstraintInterface $b)
{
if ($a instanceof MatchAllConstraint || $b instanceof MatchAllConstraint) {
return true;
}
if ($a instanceof MatchNoneConstraint || $b instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::generateIntervals(new MultiConstraint(array($a, $b), true), true);
return \count($intersectionIntervals['numeric']) > 0 || $intersectionIntervals['branches']['exclude'] || \count($intersectionIntervals['branches']['names']) > 0;
}
public static function compactConstraint(ConstraintInterface $constraint)
{
if (!$constraint instanceof MultiConstraint) {
return $constraint;
}
$intervals = self::generateIntervals($constraint);
$constraints = array();
$hasNumericMatchAll = false;
if (\count($intervals['numeric']) === 1 && (string) $intervals['numeric'][0]->getStart() === (string) Interval::fromZero() && (string) $intervals['numeric'][0]->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $intervals['numeric'][0]->getStart();
$hasNumericMatchAll = true;
} else {
$unEqualConstraints = array();
for ($i = 0, $count = \count($intervals['numeric']); $i < $count; $i++) {
$interval = $intervals['numeric'][$i];
if ($interval->getEnd()->getOperator() === '<' && $i+1 < $count) {
$nextInterval = $intervals['numeric'][$i+1];
if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') {
if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) {
$unEqualConstraints[] = $interval->getStart();
}
$unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion());
continue;
}
}
if (\count($unEqualConstraints) > 0) {
if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) {
$unEqualConstraints[] = $interval->getEnd();
}
if (\count($unEqualConstraints) > 1) {
$constraints[] = new MultiConstraint($unEqualConstraints, true);
} else {
$constraints[] = $unEqualConstraints[0];
}
$unEqualConstraints = array();
continue;
}
if ($interval->getStart()->getVersion() === $interval->getEnd()->getVersion() && $interval->getStart()->getOperator() === '>=' && $interval->getEnd()->getOperator() === '<=') {
$constraints[] = new Constraint('==', $interval->getStart()->getVersion());
continue;
}
if ((string) $interval->getStart() === (string) Interval::fromZero()) {
$constraints[] = $interval->getEnd();
} elseif ((string) $interval->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $interval->getStart();
} else {
$constraints[] = new MultiConstraint(array($interval->getStart(), $interval->getEnd()), true);
}
}
}
$devConstraints = array();
if (0 === \count($intervals['branches']['names'])) {
if ($intervals['branches']['exclude']) {
if ($hasNumericMatchAll) {
return new MatchAllConstraint;
}
}
} else {
foreach ($intervals['branches']['names'] as $branchName) {
if ($intervals['branches']['exclude']) {
$devConstraints[] = new Constraint('!=', $branchName);
} else {
$devConstraints[] = new Constraint('==', $branchName);
}
}
if ($intervals['branches']['exclude']) {
if (\count($constraints) > 1) {
return new MultiConstraint(array_merge(
array(new MultiConstraint($constraints, false)),
$devConstraints
), true);
}
if (\count($constraints) === 1 && (string)$constraints[0] === (string)Interval::fromZero()) {
if (\count($devConstraints) > 1) {
return new MultiConstraint($devConstraints, true);
}
return $devConstraints[0];
}
return new MultiConstraint(array_merge($constraints, $devConstraints), true);
}
$constraints = array_merge($constraints, $devConstraints);
}
if (\count($constraints) > 1) {
return new MultiConstraint($constraints, false);
}
if (\count($constraints) === 1) {
return $constraints[0];
}
return new MatchNoneConstraint;
}
/**
@phpstan
*/
public static function get(ConstraintInterface $constraint)
{
$key = (string) $constraint;
if (!isset(self::$intervalsCache[$key])) {
self::$intervalsCache[$key] = self::generateIntervals($constraint);
}
return self::$intervalsCache[$key];
}
/**
@phpstan
*/
private static function generateIntervals(ConstraintInterface $constraint, $stopOnFirstValidInterval = false)
{
if ($constraint instanceof MatchAllConstraint) {
return array('numeric' => array(new Interval(Interval::fromZero(), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev());
}
if ($constraint instanceof MatchNoneConstraint) {
return array('numeric' => array(), 'branches' => array('names' => array(), 'exclude' => false));
}
if ($constraint instanceof Constraint) {
return self::generateSingleConstraintIntervals($constraint);
}
if (!$constraint instanceof MultiConstraint) {
throw new \UnexpectedValueException('The constraint passed in should be an MatchAllConstraint, Constraint or MultiConstraint instance, got '.\get_class($constraint).'.');
}
$constraints = $constraint->getConstraints();
$numericGroups = array();
$constraintBranches = array();
foreach ($constraints as $c) {
$res = self::get($c);
$numericGroups[] = $res['numeric'];
$constraintBranches[] = $res['branches'];
}
if ($constraint->isDisjunctive()) {
$branches = Interval::noDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
$branches['names'] = array_intersect($branches['names'], $b['names']);
} else {
$branches['exclude'] = true;
$branches['names'] = array_diff($b['names'], $branches['names']);
}
} else {
if ($branches['exclude']) {
$branches['names'] = array_diff($branches['names'], $b['names']);
} else {
$branches['names'] = array_merge($branches['names'], $b['names']);
}
}
}
} else {
$branches = Interval::anyDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
$branches['names'] = array_merge($branches['names'], $b['names']);
} else {
$branches['names'] = array_diff($branches['names'], $b['names']);
}
} else {
if ($branches['exclude']) {
$branches['names'] = array_diff($b['names'], $branches['names']);
$branches['exclude'] = false;
} else {
$branches['names'] = array_intersect($branches['names'], $b['names']);
}
}
}
}
$branches['names'] = array_unique($branches['names']);
if (\count($numericGroups) === 1) {
return array('numeric' => $numericGroups[0], 'branches' => $branches);
}
$borders = array();
foreach ($numericGroups as $group) {
foreach ($group as $interval) {
$borders[] = array('version' => $interval->getStart()->getVersion(), 'operator' => $interval->getStart()->getOperator(), 'side' => 'start');
$borders[] = array('version' => $interval->getEnd()->getVersion(), 'operator' => $interval->getEnd()->getOperator(), 'side' => 'end');
}
}
$opSortOrder = self::$opSortOrder;
usort($borders, function ($a, $b) use ($opSortOrder) {
$order = version_compare($a['version'], $b['version']);
if ($order === 0) {
return $opSortOrder[$a['operator']] - $opSortOrder[$b['operator']];
}
return $order;
});
$activeIntervals = 0;
$intervals = array();
$index = 0;
$activationThreshold = $constraint->isConjunctive() ? \count($numericGroups) : 1;
$active = false;
$start = null;
foreach ($borders as $border) {
if ($border['side'] === 'start') {
$activeIntervals++;
} else {
$activeIntervals--;
}
if (!$active && $activeIntervals >= $activationThreshold) {
$start = new Constraint($border['operator'], $border['version']);
$active = true;
}
if ($active && $activeIntervals < $activationThreshold) {
$active = false;
if (
version_compare($start->getVersion(), $border['version'], '=')
&& (
($start->getOperator() === '>' && $border['operator'] === '<=')
|| ($start->getOperator() === '>=' && $border['operator'] === '<')
)
) {
unset($intervals[$index]);
} else {
$intervals[$index] = new Interval($start, new Constraint($border['operator'], $border['version']));
$index++;
if ($stopOnFirstValidInterval) {
break;
}
}
$start = null;
}
}
return array('numeric' => $intervals, 'branches' => $branches);
}
/**
@phpstan
*/
private static function generateSingleConstraintIntervals(Constraint $constraint)
{
$op = $constraint->getOperator();
if (strpos($constraint->getVersion(), 'dev-') === 0) {
$intervals = array();
$branches = array('names' => array(), 'exclude' => false);
if ($op === '!=') {
$intervals[] = new Interval(Interval::fromZero(), Interval::untilPositiveInfinity());
$branches = array('names' => array($constraint->getVersion()), 'exclude' => true);
} elseif ($op === '==') {
$branches['names'][] = $constraint->getVersion();
}
return array(
'numeric' => $intervals,
'branches' => $branches,
);
}
if ($op[0] === '>') {
return array('numeric' => array(new Interval($constraint, Interval::untilPositiveInfinity())), 'branches' => Interval::noDev());
}
if ($op[0] === '<') {
return array('numeric' => array(new Interval(Interval::fromZero(), $constraint)), 'branches' => Interval::noDev());
}
if ($op === '!=') {
return array('numeric' => array(
new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())),
new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity()),
), 'branches' => Interval::anyDev());
}
return array('numeric' => array(
new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion())),
), 'branches' => Interval::noDev());
}
}
<?php
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Semver
{
const SORT_ASC = 1;
const SORT_DESC = -1;
private static $versionParser;
public static function satisfies($version, $constraints)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$provider = new Constraint('==', $versionParser->normalize($version));
$parsedConstraints = $versionParser->parseConstraints($constraints);
return $parsedConstraints->matches($provider);
}
public static function satisfiedBy(array $versions, $constraints)
{
$versions = array_filter($versions, function ($version) use ($constraints) {
return Semver::satisfies($version, $constraints);
});
return array_values($versions);
}
public static function sort(array $versions)
{
return self::usort($versions, self::SORT_ASC);
}
public static function rsort(array $versions)
{
return self::usort($versions, self::SORT_DESC);
}
private static function usort(array $versions, $direction)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$normalized = array();
foreach ($versions as $key => $version) {
$normalizedVersion = $versionParser->normalize($version);
$normalizedVersion = $versionParser->normalizeDefaultBranch($normalizedVersion);
$normalized[] = array($normalizedVersion, $key);
}
usort($normalized, function (array $left, array $right) use ($direction) {
if ($left[0] === $right[0]) {
return 0;
}
if (Comparator::lessThan($left[0], $right[0])) {
return -$direction;
}
return $direction;
});
$sorted = array();
foreach ($normalized as $item) {
$sorted[] = $versions[$item[1]];
}
return $sorted;
}
}
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
<?php
namespace Composer\Autoload;
/**
@seld
*/
class ClassLoader
{
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
public function getUseIncludePath()
{
return $this->useIncludePath;
}
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
public function findFile($class)
{
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
if (false !== $pos = strrpos($class, '\\')) {
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
function includeFile($file)
{
include $file;
}
<?php
namespace Doctrine\Common\Annotations;
class IndexedReader implements Reader
{
private $delegate;
public function __construct(Reader $reader)
{
$this->delegate = $reader;
}
public function getClassAnnotations(\ReflectionClass $class)
{
$annotations = array();
foreach ($this->delegate->getClassAnnotations($class) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
public function getClassAnnotation(\ReflectionClass $class, $annotation)
{
return $this->delegate->getClassAnnotation($class, $annotation);
}
public function getMethodAnnotations(\ReflectionMethod $method)
{
$annotations = array();
foreach ($this->delegate->getMethodAnnotations($method) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
public function getMethodAnnotation(\ReflectionMethod $method, $annotation)
{
return $this->delegate->getMethodAnnotation($method, $annotation);
}
public function getPropertyAnnotations(\ReflectionProperty $property)
{
$annotations = array();
foreach ($this->delegate->getPropertyAnnotations($property) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
public function getPropertyAnnotation(\ReflectionProperty $property, $annotation)
{
return $this->delegate->getPropertyAnnotation($property, $annotation);
}
public function __call($method, $args)
{
return call_user_func_array(array($this->delegate, $method), $args);
}
}
<?php
namespace Doctrine\Common\Annotations;
interface Reader
{
function getClassAnnotations(\ReflectionClass $class);
function getClassAnnotation(\ReflectionClass $class, $annotationName);
function getMethodAnnotations(\ReflectionMethod $method);
function getMethodAnnotation(\ReflectionMethod $method, $annotationName);
function getPropertyAnnotations(\ReflectionProperty $property);
function getPropertyAnnotation(\ReflectionProperty $property, $annotationName);
}
<?php
namespace Doctrine\Common\Annotations;
/**
@mohiva
*/
class TokenParser
{
private $tokens;
private $numTokens;
private $pointer = 0;
public function __construct($contents)
{
$this->tokens = token_get_all($contents);
token_get_all("<?php\n/**\n *\n */");
$this->numTokens = count($this->tokens);
}
public function next($docCommentIsComment = TRUE)
{
for ($i = $this->pointer; $i < $this->numTokens; $i++) {
$this->pointer++;
if ($this->tokens[$i][0] === T_WHITESPACE ||
$this->tokens[$i][0] === T_COMMENT ||
($docCommentIsComment && $this->tokens[$i][0] === T_DOC_COMMENT)) {
continue;
}
return $this->tokens[$i];
}
return null;
}
public function parseUseStatement()
{
$groupRoot = '';
$class = '';
$alias = '';
$statements = array();
$explicitAlias = false;
while (($token = $this->next())) {
$isNameToken = $token[0] === T_STRING || $token[0] === T_NS_SEPARATOR;
if (!$explicitAlias && $isNameToken) {
$class .= $token[1];
$alias = $token[1];
} else if ($explicitAlias && $isNameToken) {
$alias .= $token[1];
} else if ($token[0] === T_AS) {
$explicitAlias = true;
$alias = '';
} else if ($token === ',') {
$statements[strtolower($alias)] = $groupRoot . $class;
$class = '';
$alias = '';
$explicitAlias = false;
} else if ($token === ';') {
$statements[strtolower($alias)] = $groupRoot . $class;
break;
} else if ($token === '{' ) {
$groupRoot = $class;
$class = '';
} else if ($token === '}' ) {
continue;
} else {
break;
}
}
return $statements;
}
public function parseUseStatements($namespaceName)
{
$statements = array();
while (($token = $this->next())) {
if ($token[0] === T_USE) {
$statements = array_merge($statements, $this->parseUseStatement());
continue;
}
if ($token[0] !== T_NAMESPACE || $this->parseNamespace() != $namespaceName) {
continue;
}
$statements = array();
}
return $statements;
}
public function parseNamespace()
{
$name = '';
while (($token = $this->next()) && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR)) {
$name .= $token[1];
}
return $name;
}
public function parseClass()
{
return $this->parseNamespace();
}
}
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Annotations\Annotation\IgnoreAnnotation;
use Doctrine\Common\Annotations\Annotation\Target;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
/**
@hotmail
@gmail
@gmail
*/
class AnnotationReader implements Reader
{
private static $globalImports = array(
'ignoreannotation' => 'Doctrine\Common\Annotations\Annotation\IgnoreAnnotation',
);
private static $globalIgnoredNames = array(
'Annotation' => true, 'Attribute' => true, 'Attributes' => true,
'Required' => true,
'Target' => true,
'fix' => true , 'fixme' => true,
'override' => true,
'abstract'=> true, 'access'=> true,
'code' => true,
'deprec'=> true,
'endcode' => true, 'exception'=> true,
'final'=> true,
'ingroup' => true, 'inheritdoc'=> true, 'inheritDoc'=> true,
'magic' => true,
'name'=> true,
'toc' => true, 'tutorial'=> true,
'private' => true,
'static'=> true, 'staticvar'=> true, 'staticVar'=> true,
'throw' => true,
'api' => true, 'author'=> true,
'category'=> true, 'copyright'=> true,
'deprecated'=> true,
'example'=> true,
'filesource'=> true,
'global'=> true,
'ignore'=> true, 'internal'=> true,
'license'=> true, 'link'=> true,
'method' => true,
'package'=> true, 'param'=> true, 'property' => true, 'property-read' => true, 'property-write' => true,
'return'=> true,
'see'=> true, 'since'=> true, 'source' => true, 'subpackage'=> true,
'throws'=> true, 'todo'=> true, 'TODO'=> true,
'usedby'=> true, 'uses' => true,
'var'=> true, 'version'=> true,
'codeCoverageIgnore' => true, 'codeCoverageIgnoreStart' => true, 'codeCoverageIgnoreEnd' => true,
'SuppressWarnings' => true,
'noinspection' => true,
'package_version' => true,
'startuml' => true, 'enduml' => true,
);
private static $globalIgnoredNamespaces = array();
static public function addGlobalIgnoredName($name)
{
self::$globalIgnoredNames[$name] = true;
}
static public function addGlobalIgnoredNamespace($namespace)
{
self::$globalIgnoredNamespaces[$namespace] = true;
}
private $parser;
private $preParser;
private $phpParser;
private $imports = array();
private $ignoredAnnotationNames = array();
public function __construct(DocParser $parser = null)
{
if (extension_loaded('Zend Optimizer+') && (ini_get('zend_optimizerplus.save_comments') === "0" || ini_get('opcache.save_comments') === "0")) {
throw AnnotationException::optimizerPlusSaveComments();
}
if (extension_loaded('Zend OPcache') && ini_get('opcache.save_comments') == 0) {
throw AnnotationException::optimizerPlusSaveComments();
}
if (PHP_VERSION_ID < 70000) {
if (extension_loaded('Zend Optimizer+') && (ini_get('zend_optimizerplus.load_comments') === "0" || ini_get('opcache.load_comments') === "0")) {
throw AnnotationException::optimizerPlusLoadComments();
}
if (extension_loaded('Zend OPcache') && ini_get('opcache.load_comments') == 0) {
throw AnnotationException::optimizerPlusLoadComments();
}
}
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/IgnoreAnnotation.php');
$this->parser = $parser ?: new DocParser();
$this->preParser = new DocParser;
$this->preParser->setImports(self::$globalImports);
$this->preParser->setIgnoreNotImportedAnnotations(true);
$this->phpParser = new PhpParser;
}
public function getClassAnnotations(ReflectionClass $class)
{
$this->parser->setTarget(Target::TARGET_CLASS);
$this->parser->setImports($this->getClassImports($class));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($class->getDocComment(), 'class ' . $class->getName());
}
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
$annotations = $this->getClassAnnotations($class);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
public function getPropertyAnnotations(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$context = 'property ' . $class->getName() . "::\$" . $property->getName();
$this->parser->setTarget(Target::TARGET_PROPERTY);
$this->parser->setImports($this->getPropertyImports($property));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($property->getDocComment(), $context);
}
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
$annotations = $this->getPropertyAnnotations($property);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
public function getMethodAnnotations(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$context = 'method ' . $class->getName() . '::' . $method->getName() . '()';
$this->parser->setTarget(Target::TARGET_METHOD);
$this->parser->setImports($this->getMethodImports($method));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($method->getDocComment(), $context);
}
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
$annotations = $this->getMethodAnnotations($method);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
private function getIgnoredAnnotationNames(ReflectionClass $class)
{
$name = $class->getName();
if (isset($this->ignoredAnnotationNames[$name])) {
return $this->ignoredAnnotationNames[$name];
}
$this->collectParsingMetadata($class);
return $this->ignoredAnnotationNames[$name];
}
private function getClassImports(ReflectionClass $class)
{
$name = $class->getName();
if (isset($this->imports[$name])) {
return $this->imports[$name];
}
$this->collectParsingMetadata($class);
return $this->imports[$name];
}
private function getMethodImports(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$classImports = $this->getClassImports($class);
if (!method_exists($class, 'getTraits')) {
return $classImports;
}
$traitImports = array();
foreach ($class->getTraits() as $trait) {
if ($trait->hasMethod($method->getName())
&& $trait->getFileName() === $method->getFileName()
) {
$traitImports = array_merge($traitImports, $this->phpParser->parseClass($trait));
}
}
return array_merge($classImports, $traitImports);
}
private function getPropertyImports(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$classImports = $this->getClassImports($class);
if (!method_exists($class, 'getTraits')) {
return $classImports;
}
$traitImports = array();
foreach ($class->getTraits() as $trait) {
if ($trait->hasProperty($property->getName())) {
$traitImports = array_merge($traitImports, $this->phpParser->parseClass($trait));
}
}
return array_merge($classImports, $traitImports);
}
private function collectParsingMetadata(ReflectionClass $class)
{
$ignoredAnnotationNames = self::$globalIgnoredNames;
$annotations = $this->preParser->parse($class->getDocComment(), 'class ' . $class->name);
foreach ($annotations as $annotation) {
if ($annotation instanceof IgnoreAnnotation) {
foreach ($annotation->names AS $annot) {
$ignoredAnnotationNames[$annot] = true;
}
}
}
$name = $class->getName();
$this->imports[$name] = array_merge(
self::$globalImports,
$this->phpParser->parseClass($class),
array('__NAMESPACE__' => $class->getNamespaceName())
);
$this->ignoredAnnotationNames[$name] = $ignoredAnnotationNames;
}
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
final class Required
{
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
final class IgnoreAnnotation
{
public $names;
public function __construct(array $values)
{
if (is_string($values['value'])) {
$values['value'] = array($values['value']);
}
if (!is_array($values['value'])) {
throw new \RuntimeException(sprintf('@IgnoreAnnotation expects either a string name, or an array of strings, but got %s.', json_encode($values['value'])));
}
$this->names = $values['value'];
}
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
final class Attribute
{
public $name;
public $type;
public $required = false;
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
final class Attributes
{
public $value;
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
@Attributes({@Attribute("value",required=true,type="array"),@Attribute("literal",required=false,type="array")})
*/
final class Enum
{
public $value;
public $literal;
public function __construct(array $values)
{
if ( ! isset($values['literal'])) {
$values['literal'] = array();
}
foreach ($values['value'] as $var) {
if( ! is_scalar($var)) {
throw new \InvalidArgumentException(sprintf(
'@Enum supports only scalar values "%s" given.',
is_object($var) ? get_class($var) : gettype($var)
));
}
}
foreach ($values['literal'] as $key => $var) {
if( ! in_array($key, $values['value'])) {
throw new \InvalidArgumentException(sprintf(
'Undefined enumerator value "%s" for literal "%s".',
$key , $var
));
}
}
$this->value = $values['value'];
$this->literal = $values['literal'];
}
}
<?php
namespace Doctrine\Common\Annotations\Annotation;
final class Target
{
const TARGET_CLASS = 1;
const TARGET_METHOD = 2;
const TARGET_PROPERTY = 4;
const TARGET_ANNOTATION = 8;
const TARGET_ALL = 15;
private static $map = array(
'ALL' => self::TARGET_ALL,
'CLASS' => self::TARGET_CLASS,
'METHOD' => self::TARGET_METHOD,
'PROPERTY' => self::TARGET_PROPERTY,
'ANNOTATION' => self::TARGET_ANNOTATION,
);
public $value;
public $targets;
public $literal;
public function __construct(array $values)
{
if (!isset($values['value'])){
$values['value'] = null;
}
if (is_string($values['value'])){
$values['value'] = array($values['value']);
}
if (!is_array($values['value'])){
throw new \InvalidArgumentException(
sprintf('@Target expects either a string value, or an array of strings, "%s" given.',
is_object($values['value']) ? get_class($values['value']) : gettype($values['value'])
)
);
}
$bitmask = 0;
foreach ($values['value'] as $literal) {
if(!isset(self::$map[$literal])){
throw new \InvalidArgumentException(
sprintf('Invalid Target "%s". Available targets: [%s]',
$literal, implode(', ', array_keys(self::$map)))
);
}
$bitmask |= self::$map[$literal];
}
$this->targets = $bitmask;
$this->value = $values['value'];
$this->literal = implode(', ', $this->value);
}
}
<?php
namespace Doctrine\Common\Annotations;
/**
@beberlei
*/
class FileCacheReader implements Reader
{
private $reader;
private $dir;
private $debug;
private $loadedAnnotations = array();
private $classNameHashes = array();
private $umask;
public function __construct(Reader $reader, $cacheDir, $debug = false, $umask = 0002)
{
if ( ! is_int($umask)) {
throw new \InvalidArgumentException(sprintf(
'The parameter umask must be an integer, was: %s',
gettype($umask)
));
}
$this->reader = $reader;
$this->umask = $umask;
if (!is_dir($cacheDir) && !@mkdir($cacheDir, 0777 & (~$this->umask), true)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist and could not be created.', $cacheDir));
}
$this->dir = rtrim($cacheDir, '\\/');
$this->debug = $debug;
}
public function getClassAnnotations(\ReflectionClass $class)
{
if ( ! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name];
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir.'/'.strtr($key, '\\', '-').'.cache.php';
if (!is_file($path)) {
$annot = $this->reader->getClassAnnotations($class);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
if ($this->debug
&& (false !== $filename = $class->getFileName())
&& filemtime($path) < filemtime($filename)) {
@unlink($path);
$annot = $this->reader->getClassAnnotations($class);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
public function getPropertyAnnotations(\ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
if ( ! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name].'$'.$property->getName();
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir.'/'.strtr($key, '\\', '-').'.cache.php';
if (!is_file($path)) {
$annot = $this->reader->getPropertyAnnotations($property);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
if ($this->debug
&& (false !== $filename = $class->getFilename())
&& filemtime($path) < filemtime($filename)) {
@unlink($path);
$annot = $this->reader->getPropertyAnnotations($property);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
public function getMethodAnnotations(\ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
if ( ! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name].'#'.$method->getName();
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir.'/'.strtr($key, '\\', '-').'.cache.php';
if (!is_file($path)) {
$annot = $this->reader->getMethodAnnotations($method);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
if ($this->debug
&& (false !== $filename = $class->getFilename())
&& filemtime($path) < filemtime($filename)) {
@unlink($path);
$annot = $this->reader->getMethodAnnotations($method);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
private function saveCacheFile($path, $data)
{
if (!is_writable($this->dir)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable. Both, the webserver and the console user need access. You can manage access rights for multiple users with "chmod +a". If your system does not support this, check out the acl package.', $this->dir));
}
$tempfile = tempnam($this->dir, uniqid('', true));
if (false === $tempfile) {
throw new \RuntimeException(sprintf('Unable to create tempfile in directory: %s', $this->dir));
}
@chmod($tempfile, 0666 & (~$this->umask));
$written = file_put_contents($tempfile, '<?php return unserialize('.var_export(serialize($data), true).');');
if (false === $written) {
throw new \RuntimeException(sprintf('Unable to write cached file to: %s', $tempfile));
}
@chmod($tempfile, 0666 & (~$this->umask));
if (false === rename($tempfile, $path)) {
@unlink($tempfile);
throw new \RuntimeException(sprintf('Unable to rename %s to %s', $tempfile, $path));
}
}
public function getClassAnnotation(\ReflectionClass $class, $annotationName)
{
$annotations = $this->getClassAnnotations($class);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
public function getMethodAnnotation(\ReflectionMethod $method, $annotationName)
{
$annotations = $this->getMethodAnnotations($method);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName)
{
$annotations = $this->getPropertyAnnotations($property);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
public function clearLoadedAnnotations()
{
$this->loadedAnnotations = array();
}
}
<?php
namespace Doctrine\Common\Annotations;
use SplFileObject;
/**
@mohiva
*/
final class PhpParser
{
public function parseClass(\ReflectionClass $class)
{
if (method_exists($class, 'getUseStatements')) {
return $class->getUseStatements();
}
if (false === $filename = $class->getFileName()) {
return array();
}
$content = $this->getFileContent($filename, $class->getStartLine());
if (null === $content) {
return array();
}
$namespace = preg_quote($class->getNamespaceName());
$content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);
$tokenizer = new TokenParser('<?php ' . $content);
$statements = $tokenizer->parseUseStatements($class->getNamespaceName());
return $statements;
}
private function getFileContent($filename, $lineNumber)
{
if ( ! is_file($filename)) {
return null;
}
$content = '';
$lineCnt = 0;
$file = new SplFileObject($filename);
while (!$file->eof()) {
if ($lineCnt++ == $lineNumber) {
break;
}
$content .= $file->fgets();
}
return $content;
}
}
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Lexer\AbstractLexer;
/**
@hotmail
@gmail
@gmail
*/
final class DocLexer extends AbstractLexer
{
const T_NONE = 1;
const T_INTEGER = 2;
const T_STRING = 3;
const T_FLOAT = 4;
const T_IDENTIFIER = 100;
const T_AT = 101;
const T_CLOSE_CURLY_BRACES = 102;
const T_CLOSE_PARENTHESIS = 103;
const T_COMMA = 104;
const T_EQUALS = 105;
const T_FALSE = 106;
const T_NAMESPACE_SEPARATOR = 107;
const T_OPEN_CURLY_BRACES = 108;
const T_OPEN_PARENTHESIS = 109;
const T_TRUE = 110;
const T_NULL = 111;
const T_COLON = 112;
protected $noCase = array(
'@' => self::T_AT,
',' => self::T_COMMA,
'(' => self::T_OPEN_PARENTHESIS,
')' => self::T_CLOSE_PARENTHESIS,
'{' => self::T_OPEN_CURLY_BRACES,
'}' => self::T_CLOSE_CURLY_BRACES,
'=' => self::T_EQUALS,
':' => self::T_COLON,
'\\' => self::T_NAMESPACE_SEPARATOR
);
protected $withCase = array(
'true' => self::T_TRUE,
'false' => self::T_FALSE,
'null' => self::T_NULL
);
protected function getCatchablePatterns()
{
return array(
'[a-z_\\\][a-z0-9_\:\\\]*[a-z_][a-z0-9_]*',
'(?:[+-]?[0-9]+(?:[\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?',
'"(?:""|[^"])*+"',
);
}
protected function getNonCatchablePatterns()
{
return array('\s+', '\*+', '(.)');
}
protected function getType(&$value)
{
$type = self::T_NONE;
if ($value[0] === '"') {
$value = str_replace('""', '"', substr($value, 1, strlen($value) - 2));
return self::T_STRING;
}
if (isset($this->noCase[$value])) {
return $this->noCase[$value];
}
if ($value[0] === '_' || $value[0] === '\\' || ctype_alpha($value[0])) {
return self::T_IDENTIFIER;
}
$lowerValue = strtolower($value);
if (isset($this->withCase[$lowerValue])) {
return $this->withCase[$lowerValue];
}
if (is_numeric($value)) {
return (strpos($value, '.') !== false || stripos($value, 'e') !== false)
? self::T_FLOAT : self::T_INTEGER;
}
return $type;
}
}
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Cache\Cache;
use ReflectionClass;
/**
@beberlei
*/
final class CachedReader implements Reader
{
private $delegate;
private $cache;
private $debug;
private $loadedAnnotations = array();
public function __construct(Reader $reader, Cache $cache, $debug = false)
{
$this->delegate = $reader;
$this->cache = $cache;
$this->debug = (boolean) $debug;
}
public function getClassAnnotations(ReflectionClass $class)
{
$cacheKey = $class->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
if (false === ($annots = $this->fetchFromCache($cacheKey, $class))) {
$annots = $this->delegate->getClassAnnotations($class);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
foreach ($this->getClassAnnotations($class) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function getPropertyAnnotations(\ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$cacheKey = $class->getName().'$'.$property->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
if (false === ($annots = $this->fetchFromCache($cacheKey, $class))) {
$annots = $this->delegate->getPropertyAnnotations($property);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName)
{
foreach ($this->getPropertyAnnotations($property) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function getMethodAnnotations(\ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$cacheKey = $class->getName().'#'.$method->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
if (false === ($annots = $this->fetchFromCache($cacheKey, $class))) {
$annots = $this->delegate->getMethodAnnotations($method);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
public function getMethodAnnotation(\ReflectionMethod $method, $annotationName)
{
foreach ($this->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function clearLoadedAnnotations()
{
$this->loadedAnnotations = array();
}
private function fetchFromCache($cacheKey, ReflectionClass $class)
{
if (($data = $this->cache->fetch($cacheKey)) !== false) {
if (!$this->debug || $this->isCacheFresh($cacheKey, $class)) {
return $data;
}
}
return false;
}
private function saveToCache($cacheKey, $value)
{
$this->cache->save($cacheKey, $value);
if ($this->debug) {
$this->cache->save('[C]'.$cacheKey, time());
}
}
private function isCacheFresh($cacheKey, ReflectionClass $class)
{
if (null === $lastModification = $this->getLastModification($class)) {
return true;
}
return $this->cache->fetch('[C]'.$cacheKey) >= $lastModification;
}
private function getLastModification(ReflectionClass $class)
{
$filename = $class->getFileName();
$parent = $class->getParentClass();
return max(array_merge(
[$filename ? filemtime($filename) : 0],
array_map([$this, 'getTraitLastModificationTime'], $class->getTraits()),
array_map([$this, 'getLastModification'], $class->getInterfaces()),
$parent ? [$this->getLastModification($parent)] : []
));
}
private function getTraitLastModificationTime(ReflectionClass $reflectionTrait)
{
$fileName = $reflectionTrait->getFileName();
return max(array_merge(
[$fileName ? filemtime($fileName) : 0],
array_map([$this, 'getTraitLastModificationTime'], $reflectionTrait->getTraits())
));
}
}
<?php
namespace Doctrine\Common\Annotations;
/**
@hotmail
@gmail
*/
class AnnotationException extends \Exception
{
public static function syntaxError($message)
{
return new self('[Syntax Error] ' . $message);
}
public static function semanticalError($message)
{
return new self('[Semantical Error] ' . $message);
}
public static function creationError($message)
{
return new self('[Creation Error] ' . $message);
}
public static function typeError($message)
{
return new self('[Type Error] ' . $message);
}
public static function semanticalErrorConstants($identifier, $context = null)
{
return self::semanticalError(sprintf(
"Couldn't find constant %s%s.",
$identifier,
$context ? ', ' . $context : ''
));
}
public static function attributeTypeError($attributeName, $annotationName, $context, $expected, $actual)
{
return self::typeError(sprintf(
'Attribute "%s" of @%s declared on %s expects %s, but got %s.',
$attributeName,
$annotationName,
$context,
$expected,
is_object($actual) ? 'an instance of ' . get_class($actual) : gettype($actual)
));
}
public static function requiredError($attributeName, $annotationName, $context, $expected)
{
return self::typeError(sprintf(
'Attribute "%s" of @%s declared on %s expects %s. This value should not be null.',
$attributeName,
$annotationName,
$context,
$expected
));
}
public static function enumeratorError($attributeName, $annotationName, $context, $available, $given)
{
return new self(sprintf(
'[Enum Error] Attribute "%s" of @%s declared on %s accept only [%s], but got %s.',
$attributeName,
$annotationName,
$context,
implode(', ', $available),
is_object($given) ? get_class($given) : $given
));
}
public static function optimizerPlusSaveComments()
{
return new self(
"You have to enable opcache.save_comments=1 or zend_optimizerplus.save_comments=1."
);
}
public static function optimizerPlusLoadComments()
{
return new self(
"You have to enable opcache.load_comments=1 or zend_optimizerplus.load_comments=1."
);
}
}
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Annotations\Annotation\Attribute;
use ReflectionClass;
use Doctrine\Common\Annotations\Annotation\Enum;
use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\Annotation\Attributes;
/**
@hotmail
@gmail
@gmail
@gmail
*/
final class DocParser
{
private static $classIdentifiers = array(
DocLexer::T_IDENTIFIER,
DocLexer::T_TRUE,
DocLexer::T_FALSE,
DocLexer::T_NULL
);
private $lexer;
private $target;
private static $metadataParser;
private $isNestedAnnotation = false;
private $imports = array();
private $classExists = array();
private $ignoreNotImportedAnnotations = false;
private $namespaces = array();
private $ignoredAnnotationNames = array();
private $ignoredAnnotationNamespaces = array();
private $context = '';
private static $annotationMetadata = array(
'Doctrine\Common\Annotations\Annotation\Target' => array(
'is_annotation' => true,
'has_constructor' => true,
'properties' => array(),
'targets_literal' => 'ANNOTATION_CLASS',
'targets' => Target::TARGET_CLASS,
'default_property' => 'value',
'attribute_types' => array(
'value' => array(
'required' => false,
'type' =>'array',
'array_type'=>'string',
'value' =>'array<string>'
)
),
),
'Doctrine\Common\Annotations\Annotation\Attribute' => array(
'is_annotation' => true,
'has_constructor' => false,
'targets_literal' => 'ANNOTATION_ANNOTATION',
'targets' => Target::TARGET_ANNOTATION,
'default_property' => 'name',
'properties' => array(
'name' => 'name',
'type' => 'type',
'required' => 'required'
),
'attribute_types' => array(
'value' => array(
'required' => true,
'type' =>'string',
'value' =>'string'
),
'type' => array(
'required' =>true,
'type' =>'string',
'value' =>'string'
),
'required' => array(
'required' =>false,
'type' =>'boolean',
'value' =>'boolean'
)
),
),
'Doctrine\Common\Annotations\Annotation\Attributes' => array(
'is_annotation' => true,
'has_constructor' => false,
'targets_literal' => 'ANNOTATION_CLASS',
'targets' => Target::TARGET_CLASS,
'default_property' => 'value',
'properties' => array(
'value' => 'value'
),
'attribute_types' => array(
'value' => array(
'type' =>'array',
'required' =>true,
'array_type'=>'Doctrine\Common\Annotations\Annotation\Attribute',
'value' =>'array<Doctrine\Common\Annotations\Annotation\Attribute>'
)
),
),
'Doctrine\Common\Annotations\Annotation\Enum' => array(
'is_annotation' => true,
'has_constructor' => true,
'targets_literal' => 'ANNOTATION_PROPERTY',
'targets' => Target::TARGET_PROPERTY,
'default_property' => 'value',
'properties' => array(
'value' => 'value'
),
'attribute_types' => array(
'value' => array(
'type' => 'array',
'required' => true,
),
'literal' => array(
'type' => 'array',
'required' => false,
),
),
),
);
private static $typeMap = array(
'float' => 'double',
'bool' => 'boolean',
'Boolean' => 'boolean',
'int' => 'integer',
);
public function __construct()
{
$this->lexer = new DocLexer;
}
public function setIgnoredAnnotationNames(array $names)
{
$this->ignoredAnnotationNames = $names;
}
public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
{
$this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
}
public function setIgnoreNotImportedAnnotations($bool)
{
$this->ignoreNotImportedAnnotations = (boolean) $bool;
}
public function addNamespace($namespace)
{
if ($this->imports) {
throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
}
$this->namespaces[] = $namespace;
}
public function setImports(array $imports)
{
if ($this->namespaces) {
throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
}
$this->imports = $imports;
}
public function setTarget($target)
{
$this->target = $target;
}
public function parse($input, $context = '')
{
$pos = $this->findInitialTokenPosition($input);
if ($pos === null) {
return array();
}
$this->context = $context;
$this->lexer->setInput(trim(substr($input, $pos), '* /'));
$this->lexer->moveNext();
return $this->Annotations();
}
private function findInitialTokenPosition($input)
{
$pos = 0;
while (($pos = strpos($input, '@', $pos)) !== false) {
$preceding = substr($input, $pos - 1, 1);
if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
return $pos;
}
$pos++;
}
return null;
}
private function match($token)
{
if ( ! $this->lexer->isNextToken($token) ) {
$this->syntaxError($this->lexer->getLiteral($token));
}
return $this->lexer->moveNext();
}
private function matchAny(array $tokens)
{
if ( ! $this->lexer->isNextTokenAny($tokens)) {
$this->syntaxError(implode(' or ', array_map(array($this->lexer, 'getLiteral'), $tokens)));
}
return $this->lexer->moveNext();
}
private function syntaxError($expected, $token = null)
{
if ($token === null) {
$token = $this->lexer->lookahead;
}
$message = sprintf('Expected %s, got ', $expected);
$message .= ($this->lexer->lookahead === null)
? 'end of string'
: sprintf("'%s' at position %s", $token['value'], $token['position']);
if (strlen($this->context)) {
$message .= ' in ' . $this->context;
}
$message .= '.';
throw AnnotationException::syntaxError($message);
}
private function classExists($fqcn)
{
if (isset($this->classExists[$fqcn])) {
return $this->classExists[$fqcn];
}
if (class_exists($fqcn, false)) {
return $this->classExists[$fqcn] = true;
}
return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn);
}
private function collectAnnotationMetadata($name)
{
if (self::$metadataParser === null) {
self::$metadataParser = new self();
self::$metadataParser->setIgnoreNotImportedAnnotations(true);
self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
self::$metadataParser->setImports(array(
'enum' => 'Doctrine\Common\Annotations\Annotation\Enum',
'target' => 'Doctrine\Common\Annotations\Annotation\Target',
'attribute' => 'Doctrine\Common\Annotations\Annotation\Attribute',
'attributes' => 'Doctrine\Common\Annotations\Annotation\Attributes'
));
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Enum.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Target.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attribute.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attributes.php');
}
$class = new \ReflectionClass($name);
$docComment = $class->getDocComment();
$metadata = array(
'default_property' => null,
'has_constructor' => (null !== $constructor = $class->getConstructor()) && $constructor->getNumberOfParameters() > 0,
'properties' => array(),
'property_types' => array(),
'attribute_types' => array(),
'targets_literal' => null,
'targets' => Target::TARGET_ALL,
'is_annotation' => false !== strpos($docComment, '@Annotation'),
);
if ($metadata['is_annotation']) {
self::$metadataParser->setTarget(Target::TARGET_CLASS);
foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
if ($annotation instanceof Target) {
$metadata['targets'] = $annotation->targets;
$metadata['targets_literal'] = $annotation->literal;
continue;
}
if ($annotation instanceof Attributes) {
foreach ($annotation->value as $attribute) {
$this->collectAttributeTypeMetadata($metadata, $attribute);
}
}
}
if (false === $metadata['has_constructor']) {
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
$metadata['properties'][$property->name] = $property->name;
if (false === ($propertyComment = $property->getDocComment())) {
continue;
}
$attribute = new Attribute();
$attribute->required = (false !== strpos($propertyComment, '@Required'));
$attribute->name = $property->name;
$attribute->type = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',$propertyComment, $matches))
? $matches[1]
: 'mixed';
$this->collectAttributeTypeMetadata($metadata, $attribute);
if (false !== strpos($propertyComment, '@Enum')) {
$context = 'property ' . $class->name . "::\$" . $property->name;
self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
foreach (self::$metadataParser->parse($propertyComment, $context) as $annotation) {
if ( ! $annotation instanceof Enum) {
continue;
}
$metadata['enum'][$property->name]['value'] = $annotation->value;
$metadata['enum'][$property->name]['literal'] = ( ! empty($annotation->literal))
? $annotation->literal
: $annotation->value;
}
}
}
$metadata['default_property'] = reset($metadata['properties']);
}
}
self::$annotationMetadata[$name] = $metadata;
}
private function collectAttributeTypeMetadata(&$metadata, Attribute $attribute)
{
$type = isset(self::$typeMap[$attribute->type])
? self::$typeMap[$attribute->type]
: $attribute->type;
if ('mixed' === $type) {
return;
}
switch (true) {
case (false !== $pos = strpos($type, '<')):
$arrayType = substr($type, $pos + 1, -1);
$type = 'array';
if (isset(self::$typeMap[$arrayType])) {
$arrayType = self::$typeMap[$arrayType];
}
$metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
break;
case (false !== $pos = strrpos($type, '[')):
$arrayType = substr($type, 0, $pos);
$type = 'array';
if (isset(self::$typeMap[$arrayType])) {
$arrayType = self::$typeMap[$arrayType];
}
$metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
break;
}
$metadata['attribute_types'][$attribute->name]['type'] = $type;
$metadata['attribute_types'][$attribute->name]['value'] = $attribute->type;
$metadata['attribute_types'][$attribute->name]['required'] = $attribute->required;
}
private function Annotations()
{
$annotations = array();
while (null !== $this->lexer->lookahead) {
if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
$this->lexer->moveNext();
continue;
}
if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
$this->lexer->moveNext();
continue;
}
if ((null === $peek = $this->lexer->glimpse())
|| (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
|| $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
$this->lexer->moveNext();
continue;
}
$this->isNestedAnnotation = false;
if (false !== $annot = $this->Annotation()) {
$annotations[] = $annot;
}
}
return $annotations;
}
/**
* Annotation ::= "@" AnnotationName MethodCall
* AnnotationName ::= QualifiedName | SimpleName
* QualifiedName ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
* NameSpacePart ::= identifier | null | false | true
* SimpleName ::= identifier | null | false | true
*
* @return mixed False if it is not a valid annotation.
*
* @throws AnnotationException
*/
private function Annotation()
{
$this->match(DocLexer::T_AT);
$name = $this->Identifier();
$originalName = $name;
if ('\\' !== $name[0]) {
$pos = strpos($name, '\\');
$alias = (false === $pos)? $name : substr($name, 0, $pos);
$found = false;
$loweredAlias = strtolower($alias);
if ($this->namespaces) {
foreach ($this->namespaces as $namespace) {
if ($this->classExists($namespace.'\\'.$name)) {
$name = $namespace.'\\'.$name;
$found = true;
break;
}
}
} elseif (isset($this->imports[$loweredAlias])) {
$found = true;
$name = (false !== $pos)
? $this->imports[$loweredAlias] . substr($name, $pos)
: $this->imports[$loweredAlias];
} elseif ( ! isset($this->ignoredAnnotationNames[$name])
&& isset($this->imports['__NAMESPACE__'])
&& $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
) {
$name = $this->imports['__NAMESPACE__'].'\\'.$name;
$found = true;
} elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
$found = true;
}
if ( ! $found) {
if ($this->isIgnoredAnnotation($name)) {
return false;
}
throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s was never imported. Did you maybe forget to add a "use" statement for this annotation?', $name, $this->context));
}
}
$name = ltrim($name,'\\');
if ( ! $this->classExists($name)) {
throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
}
if ( ! isset(self::$annotationMetadata[$name])) {
$this->collectAnnotationMetadata($name);
}
if (self::$annotationMetadata[$name]['is_annotation'] === false) {
if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
return false;
}
throw AnnotationException::semanticalError(sprintf('The class "%s" is not annotated with @Annotation. Are you sure this class can be used as annotation? If so, then you need to add @Annotation to the _class_ doc comment of "%s". If it is indeed no annotation, then you need to add @IgnoreAnnotation("%s") to the _class_ doc comment of %s.', $name, $name, $originalName, $this->context));
}
$target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
$this->isNestedAnnotation = true;
if (0 === (self::$annotationMetadata[$name]['targets'] & $target) && $target) {
throw AnnotationException::semanticalError(
sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
$originalName, $this->context, self::$annotationMetadata[$name]['targets_literal'])
);
}
$values = $this->MethodCall();
if (isset(self::$annotationMetadata[$name]['enum'])) {
foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) {
if (isset($values[$property]) && ! in_array($values[$property], $enum['value'])) {
throw AnnotationException::enumeratorError($property, $name, $this->context, $enum['literal'], $values[$property]);
}
}
}
foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) {
if ($property === self::$annotationMetadata[$name]['default_property']
&& !isset($values[$property]) && isset($values['value'])) {
$property = 'value';
}
if (!isset($values[$property])) {
if ($type['required']) {
throw AnnotationException::requiredError($property, $originalName, $this->context, 'a(n) '.$type['value']);
}
continue;
}
if ($type['type'] === 'array') {
if ( ! is_array($values[$property])) {
$values[$property] = array($values[$property]);
}
if (isset($type['array_type'])) {
foreach ($values[$property] as $item) {
if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
}
}
}
} elseif (gettype($values[$property]) !== $type['type'] && !$values[$property] instanceof $type['type']) {
throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'a(n) '.$type['value'], $values[$property]);
}
}
if (self::$annotationMetadata[$name]['has_constructor'] === true) {
return new $name($values);
}
$instance = new $name();
foreach ($values as $property => $value) {
if (!isset(self::$annotationMetadata[$name]['properties'][$property])) {
if ('value' !== $property) {
throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not have a property named "%s". Available properties: %s', $originalName, $this->context, $property, implode(', ', self::$annotationMetadata[$name]['properties'])));
}
if ( ! $property = self::$annotationMetadata[$name]['default_property']) {
throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not accept any values, but got %s.', $originalName, $this->context, json_encode($values)));
}
}
$instance->{$property} = $value;
}
return $instance;
}
private function MethodCall()
{
$values = array();
if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
return $values;
}
$this->match(DocLexer::T_OPEN_PARENTHESIS);
if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
$values = $this->Values();
}
$this->match(DocLexer::T_CLOSE_PARENTHESIS);
return $values;
}
private function Values()
{
$values = array($this->Value());
while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
$this->match(DocLexer::T_COMMA);
if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
break;
}
$token = $this->lexer->lookahead;
$value = $this->Value();
if ( ! is_object($value) && ! is_array($value)) {
$this->syntaxError('Value', $token);
}
$values[] = $value;
}
foreach ($values as $k => $value) {
if (is_object($value) && $value instanceof \stdClass) {
$values[$value->name] = $value->value;
} else if ( ! isset($values['value'])){
$values['value'] = $value;
} else {
if ( ! is_array($values['value'])) {
$values['value'] = array($values['value']);
}
$values['value'][] = $value;
}
unset($values[$k]);
}
return $values;
}
private function Constant()
{
$identifier = $this->Identifier();
if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
list($className, $const) = explode('::', $identifier);
$pos = strpos($className, '\\');
$alias = (false === $pos) ? $className : substr($className, 0, $pos);
$found = false;
$loweredAlias = strtolower($alias);
switch (true) {
case !empty ($this->namespaces):
foreach ($this->namespaces as $ns) {
if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
$className = $ns.'\\'.$className;
$found = true;
break;
}
}
break;
case isset($this->imports[$loweredAlias]):
$found = true;
$className = (false !== $pos)
? $this->imports[$loweredAlias] . substr($className, $pos)
: $this->imports[$loweredAlias];
break;
default:
if(isset($this->imports['__NAMESPACE__'])) {
$ns = $this->imports['__NAMESPACE__'];
if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
$className = $ns.'\\'.$className;
$found = true;
}
}
break;
}
if ($found) {
$identifier = $className . '::' . $const;
}
}
$classPos = stripos($identifier, '::class');
if ($classPos === strlen($identifier) - 7) {
return substr($identifier, 0, $classPos);
}
if (!defined($identifier)) {
throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
}
return constant($identifier);
}
private function Identifier()
{
if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
$this->syntaxError('namespace separator or identifier');
}
$this->lexer->moveNext();
$className = $this->lexer->token['value'];
while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
&& $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
$this->match(DocLexer::T_NAMESPACE_SEPARATOR);
$this->matchAny(self::$classIdentifiers);
$className .= '\\' . $this->lexer->token['value'];
}
return $className;
}
private function Value()
{
$peek = $this->lexer->glimpse();
if (DocLexer::T_EQUALS === $peek['type']) {
return $this->FieldAssignment();
}
return $this->PlainValue();
}
private function PlainValue()
{
if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
return $this->Arrayx();
}
if ($this->lexer->isNextToken(DocLexer::T_AT)) {
return $this->Annotation();
}
if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
return $this->Constant();
}
switch ($this->lexer->lookahead['type']) {
case DocLexer::T_STRING:
$this->match(DocLexer::T_STRING);
return $this->lexer->token['value'];
case DocLexer::T_INTEGER:
$this->match(DocLexer::T_INTEGER);
return (int)$this->lexer->token['value'];
case DocLexer::T_FLOAT:
$this->match(DocLexer::T_FLOAT);
return (float)$this->lexer->token['value'];
case DocLexer::T_TRUE:
$this->match(DocLexer::T_TRUE);
return true;
case DocLexer::T_FALSE:
$this->match(DocLexer::T_FALSE);
return false;
case DocLexer::T_NULL:
$this->match(DocLexer::T_NULL);
return null;
default:
$this->syntaxError('PlainValue');
}
}
private function FieldAssignment()
{
$this->match(DocLexer::T_IDENTIFIER);
$fieldName = $this->lexer->token['value'];
$this->match(DocLexer::T_EQUALS);
$item = new \stdClass();
$item->name = $fieldName;
$item->value = $this->PlainValue();
return $item;
}
private function Arrayx()
{
$array = $values = array();
$this->match(DocLexer::T_OPEN_CURLY_BRACES);
if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
$this->match(DocLexer::T_CLOSE_CURLY_BRACES);
return $array;
}
$values[] = $this->ArrayEntry();
while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
$this->match(DocLexer::T_COMMA);
if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
break;
}
$values[] = $this->ArrayEntry();
}
$this->match(DocLexer::T_CLOSE_CURLY_BRACES);
foreach ($values as $value) {
list ($key, $val) = $value;
if ($key !== null) {
$array[$key] = $val;
} else {
$array[] = $val;
}
}
return $array;
}
private function ArrayEntry()
{
$peek = $this->lexer->glimpse();
if (DocLexer::T_EQUALS === $peek['type']
|| DocLexer::T_COLON === $peek['type']) {
if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
$key = $this->Constant();
} else {
$this->matchAny(array(DocLexer::T_INTEGER, DocLexer::T_STRING));
$key = $this->lexer->token['value'];
}
$this->matchAny(array(DocLexer::T_EQUALS, DocLexer::T_COLON));
return array($key, $this->PlainValue());
}
return array(null, $this->Value());
}
private function isIgnoredAnnotation($name)
{
if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
return true;
}
foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
$ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {
return true;
}
}
return false;
}
}
<?php
namespace Doctrine\Common\Annotations;
/**
@hotmail
@gmail
*/
class Annotation
{
public $value;
public final function __construct(array $data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
public function __get($name)
{
throw new \BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, get_class($this))
);
}
public function __set($name, $value)
{
throw new \BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, get_class($this))
);
}
}
<?php
namespace Doctrine\Common\Annotations;
final class AnnotationRegistry
{
static private $autoloadNamespaces = array();
static private $loaders = array();
static public function reset()
{
self::$autoloadNamespaces = array();
self::$loaders = array();
}
static public function registerFile($file)
{
require_once $file;
}
static public function registerAutoloadNamespace($namespace, $dirs = null)
{
self::$autoloadNamespaces[$namespace] = $dirs;
}
static public function registerAutoloadNamespaces(array $namespaces)
{
self::$autoloadNamespaces = array_merge(self::$autoloadNamespaces, $namespaces);
}
static public function registerLoader($callable)
{
if (!is_callable($callable)) {
throw new \InvalidArgumentException("A callable is expected in AnnotationRegistry::registerLoader().");
}
self::$loaders[] = $callable;
}
static public function loadAnnotationClass($class)
{
foreach (self::$autoloadNamespaces AS $namespace => $dirs) {
if (strpos($class, $namespace) === 0) {
$file = str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php";
if ($dirs === null) {
if ($path = stream_resolve_include_path($file)) {
require $path;
return true;
}
} else {
foreach((array)$dirs AS $dir) {
if (is_file($dir . DIRECTORY_SEPARATOR . $file)) {
require $dir . DIRECTORY_SEPARATOR . $file;
return true;
}
}
}
}
}
foreach (self::$loaders AS $loader) {
if (call_user_func($loader, $class) === true) {
return true;
}
}
return false;
}
}
<?php
namespace Doctrine\Common\Annotations;
/**
@gmail
*/
class SimpleAnnotationReader implements Reader
{
private $parser;
public function __construct()
{
$this->parser = new DocParser();
$this->parser->setIgnoreNotImportedAnnotations(true);
}
public function addNamespace($namespace)
{
$this->parser->addNamespace($namespace);
}
public function getClassAnnotations(\ReflectionClass $class)
{
return $this->parser->parse($class->getDocComment(), 'class '.$class->getName());
}
public function getMethodAnnotations(\ReflectionMethod $method)
{
return $this->parser->parse($method->getDocComment(), 'method '.$method->getDeclaringClass()->name.'::'.$method->getName().'()');
}
public function getPropertyAnnotations(\ReflectionProperty $property)
{
return $this->parser->parse($property->getDocComment(), 'property '.$property->getDeclaringClass()->name.'::$'.$property->getName());
}
public function getClassAnnotation(\ReflectionClass $class, $annotationName)
{
foreach ($this->getClassAnnotations($class) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function getMethodAnnotation(\ReflectionMethod $method, $annotationName)
{
foreach ($this->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName)
{
foreach ($this->getPropertyAnnotations($property) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
}
<?php
namespace Doctrine\Common\Lexer;
/**
@gmail
*/
abstract class AbstractLexer
{
private $input;
private $tokens = array();
private $position = 0;
private $peek = 0;
public $lookahead;
public $token;
public function setInput($input)
{
$this->input = $input;
$this->tokens = array();
$this->reset();
$this->scan($input);
}
public function reset()
{
$this->lookahead = null;
$this->token = null;
$this->peek = 0;
$this->position = 0;
}
public function resetPeek()
{
$this->peek = 0;
}
public function resetPosition($position = 0)
{
$this->position = $position;
}
public function getInputUntilPosition($position)
{
return substr($this->input, 0, $position);
}
public function isNextToken($token)
{
return null !== $this->lookahead && $this->lookahead['type'] === $token;
}
public function isNextTokenAny(array $tokens)
{
return null !== $this->lookahead && in_array($this->lookahead['type'], $tokens, true);
}
public function moveNext()
{
$this->peek = 0;
$this->token = $this->lookahead;
$this->lookahead = (isset($this->tokens[$this->position]))
? $this->tokens[$this->position++] : null;
return $this->lookahead !== null;
}
public function skipUntil($type)
{
while ($this->lookahead !== null && $this->lookahead['type'] !== $type) {
$this->moveNext();
}
}
public function isA($value, $token)
{
return $this->getType($value) === $token;
}
public function peek()
{
if (isset($this->tokens[$this->position + $this->peek])) {
return $this->tokens[$this->position + $this->peek++];
} else {
return null;
}
}
public function glimpse()
{
$peek = $this->peek();
$this->peek = 0;
return $peek;
}
protected function scan($input)
{
static $regex;
if ( ! isset($regex)) {
$regex = sprintf(
'/(%s)|%s/%s',
implode(')|(', $this->getCatchablePatterns()),
implode('|', $this->getNonCatchablePatterns()),
$this->getModifiers()
);
}
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE;
$matches = preg_split($regex, $input, -1, $flags);
if (false === $matches) {
$matches = array(array($input, 0));
}
foreach ($matches as $match) {
$type = $this->getType($match[0]);
$this->tokens[] = array(
'value' => $match[0],
'type' => $type,
'position' => $match[1],
);
}
}
public function getLiteral($token)
{
$className = get_class($this);
$reflClass = new \ReflectionClass($className);
$constants = $reflClass->getConstants();
foreach ($constants as $name => $value) {
if ($value === $token) {
return $className . '::' . $name;
}
}
return $token;
}
protected function getModifiers()
{
return 'i';
}
abstract protected function getCatchablePatterns();
abstract protected function getNonCatchablePatterns();
abstract protected function getType(&$value);
}
<?php
namespace Psr\Log;
interface LoggerAwareInterface
{
public function setLogger(LoggerInterface $logger);
}
<?php
namespace Psr\Log;
trait LoggerAwareTrait
{
protected $logger;
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
<?php
namespace Psr\Log;
abstract class AbstractLogger implements LoggerInterface
{
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
}
<?php
namespace Psr\Log;
class NullLogger extends AbstractLogger
{
public function log($level, $message, array $context = array())
{
}
}
<?php
namespace Psr\Log;
class LogLevel
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
}
<?php
namespace Psr\Log;
trait LoggerTrait
{
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
abstract public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
interface LoggerInterface
{
public function emergency($message, array $context = array());
public function alert($message, array $context = array());
public function critical($message, array $context = array());
public function error($message, array $context = array());
public function warning($message, array $context = array());
public function notice($message, array $context = array());
public function info($message, array $context = array());
public function debug($message, array $context = array());
public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
class InvalidArgumentException extends \InvalidArgumentException
{
}
<?php
namespace PhpCsFixer\Diff\v1_4;
class Chunk
{
private $start;
private $startRange;
private $end;
private $endRange;
private $lines;
public function __construct($start = 0, $startRange = 1, $end = 0, $endRange = 1, array $lines = array())
{
$this->start = (int) $start;
$this->startRange = (int) $startRange;
$this->end = (int) $end;
$this->endRange = (int) $endRange;
$this->lines = $lines;
}
public function getStart()
{
return $this->start;
}
public function getStartRange()
{
return $this->startRange;
}
public function getEnd()
{
return $this->end;
}
public function getEndRange()
{
return $this->endRange;
}
public function getLines()
{
return $this->lines;
}
public function setLines(array $lines)
{
$this->lines = $lines;
}
}
<?php
namespace PhpCsFixer\Diff\v1_4;
class Line
{
const ADDED = 1;
const REMOVED = 2;
const UNCHANGED = 3;
private $type;
private $content;
public function __construct($type = self::UNCHANGED, $content = '')
{
$this->type = $type;
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function getType()
{
return $this->type;
}
}
<?php
namespace PhpCsFixer\Diff\v1_4;
use PhpCsFixer\Diff\v1_4\LCS\LongestCommonSubsequence;
use PhpCsFixer\Diff\v1_4\LCS\TimeEfficientImplementation;
use PhpCsFixer\Diff\v1_4\LCS\MemoryEfficientImplementation;
class Differ
{
private $header;
private $showNonDiffLines;
public function __construct($header = "--- Original\n+++ New\n", $showNonDiffLines = true)
{
$this->header = $header;
$this->showNonDiffLines = $showNonDiffLines;
}
public function diff($from, $to, LongestCommonSubsequence $lcs = null)
{
$from = $this->validateDiffInput($from);
$to = $this->validateDiffInput($to);
$diff = $this->diffToArray($from, $to, $lcs);
$old = $this->checkIfDiffInOld($diff);
$start = isset($old[0]) ? $old[0] : 0;
$end = \count($diff);
if ($tmp = \array_search($end, $old)) {
$end = $tmp;
}
return $this->getBuffer($diff, $old, $start, $end);
}
private function validateDiffInput($input)
{
if (!\is_array($input) && !\is_string($input)) {
return (string) $input;
}
return $input;
}
private function checkIfDiffInOld(array $diff)
{
$inOld = false;
$i = 0;
$old = array();
foreach ($diff as $line) {
if ($line[1] === 0 ) {
if ($inOld === false) {
$inOld = $i;
}
} elseif ($inOld !== false) {
if (($i - $inOld) > 5) {
$old[$inOld] = $i - 1;
}
$inOld = false;
}
++$i;
}
return $old;
}
private function getBuffer(array $diff, array $old, $start, $end)
{
$buffer = $this->header;
if (!isset($old[$start])) {
$buffer = $this->getDiffBufferElementNew($diff, $buffer, $start);
++$start;
}
for ($i = $start; $i < $end; $i++) {
if (isset($old[$i])) {
$i = $old[$i];
$buffer = $this->getDiffBufferElementNew($diff, $buffer, $i);
} else {
$buffer = $this->getDiffBufferElement($diff, $buffer, $i);
}
}
return $buffer;
}
private function getDiffBufferElement(array $diff, $buffer, $diffIndex)
{
if ($diff[$diffIndex][1] === 1 ) {
$buffer .= '+' . $diff[$diffIndex][0] . "\n";
} elseif ($diff[$diffIndex][1] === 2 ) {
$buffer .= '-' . $diff[$diffIndex][0] . "\n";
} elseif ($this->showNonDiffLines === true) {
$buffer .= ' ' . $diff[$diffIndex][0] . "\n";
}
return $buffer;
}
private function getDiffBufferElementNew(array $diff, $buffer, $diffIndex)
{
if ($this->showNonDiffLines === true) {
$buffer .= "@@ @@\n";
}
return $this->getDiffBufferElement($diff, $buffer, $diffIndex);
}
public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
{
if (\is_string($from)) {
$fromMatches = $this->getNewLineMatches($from);
$from = $this->splitStringByLines($from);
} elseif (\is_array($from)) {
$fromMatches = array();
} else {
throw new \InvalidArgumentException('"from" must be an array or string.');
}
if (\is_string($to)) {
$toMatches = $this->getNewLineMatches($to);
$to = $this->splitStringByLines($to);
} elseif (\is_array($to)) {
$toMatches = array();
} else {
throw new \InvalidArgumentException('"to" must be an array or string.');
}
list($from, $to, $start, $end) = self::getArrayDiffParted($from, $to);
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}
$common = $lcs->calculate(\array_values($from), \array_values($to));
$diff = array();
if ($this->detectUnmatchedLineEndings($fromMatches, $toMatches)) {
$diff[] = array(
'#Warnings contain different line endings!',
0
);
}
foreach ($start as $token) {
$diff[] = array($token, 0 );
}
\reset($from);
\reset($to);
foreach ($common as $token) {
while (($fromToken = \reset($from)) !== $token) {
$diff[] = array(\array_shift($from), 2 );
}
while (($toToken = \reset($to)) !== $token) {
$diff[] = array(\array_shift($to), 1 );
}
$diff[] = array($token, 0 );
\array_shift($from);
\array_shift($to);
}
while (($token = \array_shift($from)) !== null) {
$diff[] = array($token, 2 );
}
while (($token = \array_shift($to)) !== null) {
$diff[] = array($token, 1 );
}
foreach ($end as $token) {
$diff[] = array($token, 0 );
}
return $diff;
}
private function getNewLineMatches($string)
{
\preg_match_all('(\r\n|\r|\n)', $string, $stringMatches);
return $stringMatches;
}
private function splitStringByLines($input)
{
return \preg_split('(\r\n|\r|\n)', $input);
}
private function selectLcsImplementation(array $from, array $to)
{
$memoryLimit = 100 * 1024 * 1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientImplementation;
}
return new TimeEfficientImplementation;
}
private function calculateEstimatedFootprint(array $from, array $to)
{
$itemSize = PHP_INT_SIZE === 4 ? 76 : 144;
return $itemSize * \pow(\min(\count($from), \count($to)), 2);
}
private function detectUnmatchedLineEndings(array $fromMatches, array $toMatches)
{
return isset($fromMatches[0], $toMatches[0]) &&
\count($fromMatches[0]) === \count($toMatches[0]) &&
$fromMatches[0] !== $toMatches[0];
}
private static function getArrayDiffParted(array &$from, array &$to)
{
$start = array();
$end = array();
\reset($to);
foreach ($from as $k => $v) {
$toK = \key($to);
if ($toK === $k && $v === $to[$k]) {
$start[$k] = $v;
unset($from[$k], $to[$k]);
} else {
break;
}
}
\end($from);
\end($to);
do {
$fromK = \key($from);
$toK = \key($to);
if (null === $fromK || null === $toK || \current($from) !== \current($to)) {
break;
}
\prev($from);
\prev($to);
$end = array($fromK => $from[$fromK]) + $end;
unset($from[$fromK], $to[$toK]);
} while (true);
return array($from, $to, $start, $end);
}
}
<?php
namespace PhpCsFixer\Diff\v1_4\LCS;
class TimeEfficientImplementation implements LongestCommonSubsequence
{
public function calculate(array $from, array $to)
{
$common = array();
$fromLength = \count($from);
$toLength = \count($to);
$width = $fromLength + 1;
$matrix = new \SplFixedArray($width * ($toLength + 1));
for ($i = 0; $i <= $fromLength; ++$i) {
$matrix[$i] = 0;
}
for ($j = 0; $j <= $toLength; ++$j) {
$matrix[$j * $width] = 0;
}
for ($i = 1; $i <= $fromLength; ++$i) {
for ($j = 1; $j <= $toLength; ++$j) {
$o = ($j * $width) + $i;
$matrix[$o] = \max(
$matrix[$o - 1],
$matrix[$o - $width],
$from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
);
}
}
$i = $fromLength;
$j = $toLength;
while ($i > 0 && $j > 0) {
if ($from[$i - 1] === $to[$j - 1]) {
$common[] = $from[$i - 1];
--$i;
--$j;
} else {
$o = ($j * $width) + $i;
if ($matrix[$o - $width] > $matrix[$o - 1]) {
--$j;
} else {
--$i;
}
}
}
return \array_reverse($common);
}
}
<?php
namespace PhpCsFixer\Diff\v1_4\LCS;
class MemoryEfficientImplementation implements LongestCommonSubsequence
{
public function calculate(array $from, array $to)
{
$cFrom = \count($from);
$cTo = \count($to);
if ($cFrom === 0) {
return array();
}
if ($cFrom === 1) {
if (\in_array($from[0], $to, true)) {
return array($from[0]);
}
return array();
}
$i = (int) ($cFrom / 2);
$fromStart = \array_slice($from, 0, $i);
$fromEnd = \array_slice($from, $i);
$llB = $this->length($fromStart, $to);
$llE = $this->length(\array_reverse($fromEnd), \array_reverse($to));
$jMax = 0;
$max = 0;
for ($j = 0; $j <= $cTo; $j++) {
$m = $llB[$j] + $llE[$cTo - $j];
if ($m >= $max) {
$max = $m;
$jMax = $j;
}
}
$toStart = \array_slice($to, 0, $jMax);
$toEnd = \array_slice($to, $jMax);
return \array_merge(
$this->calculate($fromStart, $toStart),
$this->calculate($fromEnd, $toEnd)
);
}
private function length(array $from, array $to)
{
$current = \array_fill(0, \count($to) + 1, 0);
$cFrom = \count($from);
$cTo = \count($to);
for ($i = 0; $i < $cFrom; $i++) {
$prev = $current;
for ($j = 0; $j < $cTo; $j++) {
if ($from[$i] === $to[$j]) {
$current[$j + 1] = $prev[$j] + 1;
} else {
$current[$j + 1] = \max($current[$j], $prev[$j + 1]);
}
}
}
return $current;
}
}
<?php
namespace PhpCsFixer\Diff\v1_4\LCS;
interface LongestCommonSubsequence
{
public function calculate(array $from, array $to);
}
<?php
namespace PhpCsFixer\Diff\v1_4;
class Parser
{
public function parse($string)
{
$lines = \preg_split('(\r\n|\r|\n)', $string);
if (!empty($lines) && $lines[\count($lines) - 1] == '') {
\array_pop($lines);
}
$lineCount = \count($lines);
$diffs = array();
$diff = null;
$collected = array();
for ($i = 0; $i < $lineCount; ++$i) {
if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
\preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
if ($diff !== null) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
$collected = array();
}
$diff = new Diff($fromMatch['file'], $toMatch['file']);
++$i;
} else {
if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
continue;
}
$collected[] = $lines[$i];
}
}
if ($diff !== null && \count($collected)) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
}
return $diffs;
}
private function parseFileDiff(Diff $diff, array $lines)
{
$chunks = array();
$chunk = null;
foreach ($lines as $line) {
if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
$chunk = new Chunk(
$match['start'],
isset($match['startrange']) ? \max(1, $match['startrange']) : 1,
$match['end'],
isset($match['endrange']) ? \max(1, $match['endrange']) : 1
);
$chunks[] = $chunk;
$diffLines = array();
continue;
}
if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
$type = Line::UNCHANGED;
if ($match['type'] === '+') {
$type = Line::ADDED;
} elseif ($match['type'] === '-') {
$type = Line::REMOVED;
}
$diffLines[] = new Line($type, $match['line']);
if (null !== $chunk) {
$chunk->setLines($diffLines);
}
}
}
$diff->setChunks($chunks);
}
}
<?php
namespace PhpCsFixer\Diff\v1_4;
class Diff
{
private $from;
private $to;
private $chunks;
public function __construct($from, $to, array $chunks = array())
{
$this->from = $from;
$this->to = $to;
$this->chunks = $chunks;
}
public function getFrom()
{
return $this->from;
}
public function getTo()
{
return $this->to;
}
public function getChunks()
{
return $this->chunks;
}
public function setChunks(array $chunks)
{
$this->chunks = $chunks;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class Chunk
{
private $start;
private $startRange;
private $end;
private $endRange;
private $lines;
public function __construct($start = 0, $startRange = 1, $end = 0, $endRange = 1, array $lines = [])
{
$this->start = $start;
$this->startRange = $startRange;
$this->end = $end;
$this->endRange = $endRange;
$this->lines = $lines;
}
public function getStart()
{
return $this->start;
}
public function getStartRange()
{
return $this->startRange;
}
public function getEnd()
{
return $this->end;
}
public function getEndRange()
{
return $this->endRange;
}
public function getLines()
{
return $this->lines;
}
public function setLines(array $lines)
{
$this->lines = $lines;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class Line
{
const ADDED = 1;
const REMOVED = 2;
const UNCHANGED = 3;
private $type;
private $content;
public function __construct($type = self::UNCHANGED, $content = '')
{
$this->type = $type;
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function getType()
{
return $this->type;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
use PhpCsFixer\Diff\v3_0\Output\DiffOutputBuilderInterface;
use PhpCsFixer\Diff\v3_0\Output\UnifiedDiffOutputBuilder;
final class Differ
{
const OLD = 0;
const ADDED = 1;
const REMOVED = 2;
const DIFF_LINE_END_WARNING = 3;
const NO_LINE_END_EOF_WARNING = 4;
private $outputBuilder;
public function __construct($outputBuilder = null)
{
if ($outputBuilder instanceof DiffOutputBuilderInterface) {
$this->outputBuilder = $outputBuilder;
} elseif (null === $outputBuilder) {
$this->outputBuilder = new UnifiedDiffOutputBuilder;
} elseif (\is_string($outputBuilder)) {
$this->outputBuilder = new UnifiedDiffOutputBuilder($outputBuilder);
} else {
throw new InvalidArgumentException(
\sprintf(
'Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got %s.',
\is_object($outputBuilder) ? 'instance of "' . \get_class($outputBuilder) . '"' : \gettype($outputBuilder) . ' "' . $outputBuilder . '"'
)
);
}
}
public function diff($from, $to, LongestCommonSubsequenceCalculator $lcs = null)
{
$diff = $this->diffToArray(
$this->normalizeDiffInput($from),
$this->normalizeDiffInput($to),
$lcs
);
return $this->outputBuilder->getDiff($diff);
}
public function diffToArray($from, $to, LongestCommonSubsequenceCalculator $lcs = null)
{
if (\is_string($from)) {
$from = $this->splitStringByLines($from);
} elseif (!\is_array($from)) {
throw new InvalidArgumentException('"from" must be an array or string.');
}
if (\is_string($to)) {
$to = $this->splitStringByLines($to);
} elseif (!\is_array($to)) {
throw new InvalidArgumentException('"to" must be an array or string.');
}
list($from, $to, $start, $end) = self::getArrayDiffParted($from, $to);
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}
$common = $lcs->calculate(\array_values($from), \array_values($to));
$diff = [];
foreach ($start as $token) {
$diff[] = [$token, self::OLD];
}
\reset($from);
\reset($to);
foreach ($common as $token) {
while (($fromToken = \reset($from)) !== $token) {
$diff[] = [\array_shift($from), self::REMOVED];
}
while (($toToken = \reset($to)) !== $token) {
$diff[] = [\array_shift($to), self::ADDED];
}
$diff[] = [$token, self::OLD];
\array_shift($from);
\array_shift($to);
}
while (($token = \array_shift($from)) !== null) {
$diff[] = [$token, self::REMOVED];
}
while (($token = \array_shift($to)) !== null) {
$diff[] = [$token, self::ADDED];
}
foreach ($end as $token) {
$diff[] = [$token, self::OLD];
}
if ($this->detectUnmatchedLineEndings($diff)) {
\array_unshift($diff, ["#Warnings contain different line endings!\n", self::DIFF_LINE_END_WARNING]);
}
return $diff;
}
private function normalizeDiffInput($input)
{
if (!\is_array($input) && !\is_string($input)) {
return (string) $input;
}
return $input;
}
private function splitStringByLines($input)
{
return \preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
private function selectLcsImplementation(array $from, array $to)
{
$memoryLimit = 100 * 1024 * 1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientLongestCommonSubsequenceCalculator;
}
return new TimeEfficientLongestCommonSubsequenceCalculator;
}
private function calculateEstimatedFootprint(array $from, array $to)
{
$itemSize = PHP_INT_SIZE === 4 ? 76 : 144;
return $itemSize * \min(\count($from), \count($to)) ** 2;
}
private function detectUnmatchedLineEndings(array $diff)
{
$newLineBreaks = ['' => true];
$oldLineBreaks = ['' => true];
foreach ($diff as $entry) {
if (self::OLD === $entry[1]) {
$ln = $this->getLinebreak($entry[0]);
$oldLineBreaks[$ln] = true;
$newLineBreaks[$ln] = true;
} elseif (self::ADDED === $entry[1]) {
$newLineBreaks[$this->getLinebreak($entry[0])] = true;
} elseif (self::REMOVED === $entry[1]) {
$oldLineBreaks[$this->getLinebreak($entry[0])] = true;
}
}
if (['' => true] === $newLineBreaks || ['' => true] === $oldLineBreaks) {
return false;
}
foreach ($newLineBreaks as $break => $set) {
if (!isset($oldLineBreaks[$break])) {
return true;
}
}
foreach ($oldLineBreaks as $break => $set) {
if (!isset($newLineBreaks[$break])) {
return true;
}
}
return false;
}
private function getLinebreak($line)
{
if (!\is_string($line)) {
return '';
}
$lc = \substr($line, -1);
if ("\r" === $lc) {
return "\r";
}
if ("\n" !== $lc) {
return '';
}
if ("\r\n" === \substr($line, -2)) {
return "\r\n";
}
return "\n";
}
private static function getArrayDiffParted(array &$from, array &$to)
{
$start = [];
$end = [];
\reset($to);
foreach ($from as $k => $v) {
$toK = \key($to);
if ($toK === $k && $v === $to[$k]) {
$start[$k] = $v;
unset($from[$k], $to[$k]);
} else {
break;
}
}
\end($from);
\end($to);
do {
$fromK = \key($from);
$toK = \key($to);
if (null === $fromK || null === $toK || \current($from) !== \current($to)) {
break;
}
\prev($from);
\prev($to);
$end = [$fromK => $from[$fromK]] + $end;
unset($from[$fromK], $to[$toK]);
} while (true);
return [$from, $to, $start, $end];
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class Parser
{
public function parse($string)
{
$lines = \preg_split('(\r\n|\r|\n)', $string);
if (!empty($lines) && $lines[\count($lines) - 1] === '') {
\array_pop($lines);
}
$lineCount = \count($lines);
$diffs = [];
$diff = null;
$collected = [];
for ($i = 0; $i < $lineCount; ++$i) {
if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
\preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
if ($diff !== null) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
$collected = [];
}
$diff = new Diff($fromMatch['file'], $toMatch['file']);
++$i;
} else {
if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
continue;
}
$collected[] = $lines[$i];
}
}
if ($diff !== null && \count($collected)) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
}
return $diffs;
}
private function parseFileDiff(Diff $diff, array $lines)
{
$chunks = [];
$chunk = null;
foreach ($lines as $line) {
if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
$chunk = new Chunk(
(int) $match['start'],
isset($match['startrange']) ? \max(1, (int) $match['startrange']) : 1,
(int) $match['end'],
isset($match['endrange']) ? \max(1, (int) $match['endrange']) : 1
);
$chunks[] = $chunk;
$diffLines = [];
continue;
}
if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
$type = Line::UNCHANGED;
if ($match['type'] === '+') {
$type = Line::ADDED;
} elseif ($match['type'] === '-') {
$type = Line::REMOVED;
}
$diffLines[] = new Line($type, $match['line']);
if (null !== $chunk) {
$chunk->setLines($diffLines);
}
}
}
$diff->setChunks($chunks);
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to)
{
$common = [];
$fromLength = \count($from);
$toLength = \count($to);
$width = $fromLength + 1;
$matrix = new \SplFixedArray($width * ($toLength + 1));
for ($i = 0; $i <= $fromLength; ++$i) {
$matrix[$i] = 0;
}
for ($j = 0; $j <= $toLength; ++$j) {
$matrix[$j * $width] = 0;
}
for ($i = 1; $i <= $fromLength; ++$i) {
for ($j = 1; $j <= $toLength; ++$j) {
$o = ($j * $width) + $i;
$matrix[$o] = \max(
$matrix[$o - 1],
$matrix[$o - $width],
$from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
);
}
}
$i = $fromLength;
$j = $toLength;
while ($i > 0 && $j > 0) {
if ($from[$i - 1] === $to[$j - 1]) {
$common[] = $from[$i - 1];
--$i;
--$j;
} else {
$o = ($j * $width) + $i;
if ($matrix[$o - $width] > $matrix[$o - 1]) {
--$j;
} else {
--$i;
}
}
}
return \array_reverse($common);
}
}
<?php
namespace PhpCsFixer\Diff\v3_0\Output;
use PhpCsFixer\Diff\v3_0\ConfigurationException;
use PhpCsFixer\Diff\v3_0\Differ;
final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface
{
private $changed;
private $collapseRanges;
private $commonLineThreshold;
private $header;
private $contextLines;
private static $default = [
'collapseRanges' => true,
'commonLineThreshold' => 6,
'contextLines' => 3,
'fromFile' => null,
'fromFileDate' => null,
'toFile' => null,
'toFileDate' => null,
];
public function __construct(array $options = [])
{
$options = \array_merge(self::$default, $options);
if (!\is_bool($options['collapseRanges'])) {
throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']);
}
if (!\is_int($options['contextLines']) || $options['contextLines'] < 0) {
throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']);
}
if (!\is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] <= 0) {
throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']);
}
foreach (['fromFile', 'toFile'] as $option) {
if (!\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string', $options[$option]);
}
}
foreach (['fromFileDate', 'toFileDate'] as $option) {
if (null !== $options[$option] && !\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string or <null>', $options[$option]);
}
}
$this->header = \sprintf(
"--- %s%s\n+++ %s%s\n",
$options['fromFile'],
null === $options['fromFileDate'] ? '' : "\t" . $options['fromFileDate'],
$options['toFile'],
null === $options['toFileDate'] ? '' : "\t" . $options['toFileDate']
);
$this->collapseRanges = $options['collapseRanges'];
$this->commonLineThreshold = $options['commonLineThreshold'];
$this->contextLines = $options['contextLines'];
}
public function getDiff(array $diff)
{
if (0 === \count($diff)) {
return '';
}
$this->changed = false;
$buffer = \fopen('php://memory', 'r+b');
\fwrite($buffer, $this->header);
$this->writeDiffHunks($buffer, $diff);
if (!$this->changed) {
\fclose($buffer);
return '';
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
$last = \substr($diff, -1);
return "\n" !== $last && "\r" !== $last
? $diff . "\n"
: $diff
;
}
private function writeDiffHunks($output, array $diff)
{
$upperLimit = \count($diff);
if (0 === $diff[$upperLimit - 1][1]) {
$lc = \substr($diff[$upperLimit - 1][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
}
} else {
$toFind = [1 => true, 2 => true];
for ($i = $upperLimit - 1; $i >= 0; --$i) {
if (isset($toFind[$diff[$i][1]])) {
unset($toFind[$diff[$i][1]]);
$lc = \substr($diff[$i][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
}
if (!\count($toFind)) {
break;
}
}
}
}
$cutOff = \max($this->commonLineThreshold, $this->contextLines);
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
$toStart = $fromStart = 1;
foreach ($diff as $i => $entry) {
if (0 === $entry[1]) {
if (false === $hunkCapture) {
++$fromStart;
++$toStart;
continue;
}
++$sameCount;
++$toRange;
++$fromRange;
if ($sameCount === $cutOff) {
$contextStartOffset = ($hunkCapture - $this->contextLines) < 0
? $hunkCapture
: $this->contextLines
;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $cutOff + $this->contextLines + 1,
$fromStart - $contextStartOffset,
$fromRange - $cutOff + $contextStartOffset + $this->contextLines,
$toStart - $contextStartOffset,
$toRange - $cutOff + $contextStartOffset + $this->contextLines,
$output
);
$fromStart += $fromRange;
$toStart += $toRange;
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
}
continue;
}
$sameCount = 0;
if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) {
continue;
}
$this->changed = true;
if (false === $hunkCapture) {
$hunkCapture = $i;
}
if (Differ::ADDED === $entry[1]) {
++$toRange;
}
if (Differ::REMOVED === $entry[1]) {
++$fromRange;
}
}
if (false === $hunkCapture) {
return;
}
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
$contextEndOffset = \min($sameCount, $this->contextLines);
$fromRange -= $sameCount;
$toRange -= $sameCount;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $sameCount + $contextEndOffset + 1,
$fromStart - $contextStartOffset,
$fromRange + $contextStartOffset + $contextEndOffset,
$toStart - $contextStartOffset,
$toRange + $contextStartOffset + $contextEndOffset,
$output
);
}
private function writeHunk(
array $diff,
$diffStartIndex,
$diffEndIndex,
$fromStart,
$fromRange,
$toStart,
$toRange,
$output
) {
\fwrite($output, '@@ -' . $fromStart);
if (!$this->collapseRanges || 1 !== $fromRange) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . $toStart);
if (!$this->collapseRanges || 1 !== $toRange) {
\fwrite($output, ',' . $toRange);
}
\fwrite($output, " @@\n");
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === Differ::ADDED) {
$this->changed = true;
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::REMOVED) {
$this->changed = true;
\fwrite($output, '-' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::OLD) {
\fwrite($output, ' ' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) {
$this->changed = true;
\fwrite($output, $diff[$i][0]);
}
}
}
}
<?php
namespace PhpCsFixer\Diff\v3_0\Output;
use PhpCsFixer\Diff\v3_0\Differ;
final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
{
private $header;
public function __construct($header = "--- Original\n+++ New\n")
{
$this->header = $header;
}
public function getDiff(array $diff)
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
foreach ($diff as $diffEntry) {
if ($diffEntry[1] === Differ::ADDED) {
\fwrite($buffer, '+' . $diffEntry[0]);
} elseif ($diffEntry[1] === Differ::REMOVED) {
\fwrite($buffer, '-' . $diffEntry[0]);
} elseif ($diffEntry[1] === Differ::DIFF_LINE_END_WARNING) {
\fwrite($buffer, ' ' . $diffEntry[0]);
continue;
} else {
continue;
}
$lc = \substr($diffEntry[0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($buffer, "\n");
}
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0\Output;
abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
{
protected function getCommonChunks(array $diff, $lineThreshold = 5)
{
$diffSize = \count($diff);
$capturing = false;
$chunkStart = 0;
$chunkSize = 0;
$commonChunks = [];
for ($i = 0; $i < $diffSize; ++$i) {
if ($diff[$i][1] === 0 ) {
if ($capturing === false) {
$capturing = true;
$chunkStart = $i;
$chunkSize = 0;
} else {
++$chunkSize;
}
} elseif ($capturing !== false) {
if ($chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
$capturing = false;
}
}
if ($capturing !== false && $chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
return $commonChunks;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0\Output;
interface DiffOutputBuilderInterface
{
public function getDiff(array $diff);
}
<?php
namespace PhpCsFixer\Diff\v3_0\Output;
use PhpCsFixer\Diff\v3_0\Differ;
final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
private $collapseRanges = true;
private $commonLineThreshold = 6;
private $contextLines = 3;
private $header;
private $addLineNumbers;
public function __construct($header = "--- Original\n+++ New\n", $addLineNumbers = false)
{
$this->header = $header;
$this->addLineNumbers = $addLineNumbers;
}
public function getDiff(array $diff)
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
if (0 !== \count($diff)) {
$this->writeDiffHunks($buffer, $diff);
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
$last = \substr($diff, -1);
return 0 !== \strlen($diff) && "\n" !== $last && "\r" !== $last
? $diff . "\n"
: $diff
;
}
private function writeDiffHunks($output, array $diff)
{
$upperLimit = \count($diff);
if (0 === $diff[$upperLimit - 1][1]) {
$lc = \substr($diff[$upperLimit - 1][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
}
} else {
$toFind = [1 => true, 2 => true];
for ($i = $upperLimit - 1; $i >= 0; --$i) {
if (isset($toFind[$diff[$i][1]])) {
unset($toFind[$diff[$i][1]]);
$lc = \substr($diff[$i][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
}
if (!\count($toFind)) {
break;
}
}
}
}
$cutOff = \max($this->commonLineThreshold, $this->contextLines);
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
$toStart = $fromStart = 1;
foreach ($diff as $i => $entry) {
if (0 === $entry[1]) {
if (false === $hunkCapture) {
++$fromStart;
++$toStart;
continue;
}
++$sameCount;
++$toRange;
++$fromRange;
if ($sameCount === $cutOff) {
$contextStartOffset = ($hunkCapture - $this->contextLines) < 0
? $hunkCapture
: $this->contextLines
;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $cutOff + $this->contextLines + 1,
$fromStart - $contextStartOffset,
$fromRange - $cutOff + $contextStartOffset + $this->contextLines,
$toStart - $contextStartOffset,
$toRange - $cutOff + $contextStartOffset + $this->contextLines,
$output
);
$fromStart += $fromRange;
$toStart += $toRange;
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
}
continue;
}
$sameCount = 0;
if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) {
continue;
}
if (false === $hunkCapture) {
$hunkCapture = $i;
}
if (Differ::ADDED === $entry[1]) {
++$toRange;
}
if (Differ::REMOVED === $entry[1]) {
++$fromRange;
}
}
if (false === $hunkCapture) {
return;
}
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
$contextEndOffset = \min($sameCount, $this->contextLines);
$fromRange -= $sameCount;
$toRange -= $sameCount;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $sameCount + $contextEndOffset + 1,
$fromStart - $contextStartOffset,
$fromRange + $contextStartOffset + $contextEndOffset,
$toStart - $contextStartOffset,
$toRange + $contextStartOffset + $contextEndOffset,
$output
);
}
private function writeHunk(
array $diff,
$diffStartIndex,
$diffEndIndex,
$fromStart,
$fromRange,
$toStart,
$toRange,
$output
) {
if ($this->addLineNumbers) {
\fwrite($output, '@@ -' . $fromStart);
if (!$this->collapseRanges || 1 !== $fromRange) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . $toStart);
if (!$this->collapseRanges || 1 !== $toRange) {
\fwrite($output, ',' . $toRange);
}
\fwrite($output, " @@\n");
} else {
\fwrite($output, "@@ @@\n");
}
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === Differ::ADDED) {
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::REMOVED) {
\fwrite($output, '-' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::OLD) {
\fwrite($output, ' ' . $diff[$i][0]);
} elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) {
\fwrite($output, "\n");
} else {
\fwrite($output, ' ' . $diff[$i][0]);
}
}
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
interface LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to);
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class ConfigurationException extends InvalidArgumentException
{
public function __construct(
$option,
$expected,
$value,
$code = 0,
\Exception $previous = null
) {
parent::__construct(
\sprintf(
'Option "%s" must be %s, got "%s".',
$option,
$expected,
\is_object($value) ? \get_class($value) : (null === $value ? '<null>' : \gettype($value) . '#' . $value)
),
$code,
$previous
);
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
interface Exception
{
}
<?php
namespace PhpCsFixer\Diff\v3_0;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class Diff
{
private $from;
private $to;
private $chunks;
public function __construct($from, $to, array $chunks = [])
{
$this->from = $from;
$this->to = $to;
$this->chunks = $chunks;
}
public function getFrom()
{
return $this->from;
}
public function getTo()
{
return $this->to;
}
public function getChunks()
{
return $this->chunks;
}
public function setChunks(array $chunks)
{
$this->chunks = $chunks;
}
}
<?php
namespace PhpCsFixer\Diff\v3_0;
final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to)
{
$cFrom = \count($from);
$cTo = \count($to);
if ($cFrom === 0) {
return [];
}
if ($cFrom === 1) {
if (\in_array($from[0], $to, true)) {
return [$from[0]];
}
return [];
}
$i = (int) ($cFrom / 2);
$fromStart = \array_slice($from, 0, $i);
$fromEnd = \array_slice($from, $i);
$llB = $this->length($fromStart, $to);
$llE = $this->length(\array_reverse($fromEnd), \array_reverse($to));
$jMax = 0;
$max = 0;
for ($j = 0; $j <= $cTo; $j++) {
$m = $llB[$j] + $llE[$cTo - $j];
if ($m >= $max) {
$max = $m;
$jMax = $j;
}
}
$toStart = \array_slice($to, 0, $jMax);
$toEnd = \array_slice($to, $jMax);
return \array_merge(
$this->calculate($fromStart, $toStart),
$this->calculate($fromEnd, $toEnd)
);
}
private function length(array $from, array $to)
{
$current = \array_fill(0, \count($to) + 1, 0);
$cFrom = \count($from);
$cTo = \count($to);
for ($i = 0; $i < $cFrom; $i++) {
$prev = $current;
for ($j = 0; $j < $cTo; $j++) {
if ($from[$i] === $to[$j]) {
$current[$j + 1] = $prev[$j] + 1;
} else {
$current[$j + 1] = \max($current[$j], $prev[$j + 1]);
}
}
}
return $current;
}
}
<?php
namespace PhpCsFixer\Diff\GeckoPackages\DiffOutputBuilder;
use Exception;
final class ConfigurationException extends \InvalidArgumentException
{
public function __construct(
$option,
$expected,
$value,
$code = 0,
Exception $previous = null
) {
parent::__construct(
\sprintf(
'Option "%s" must be %s, got "%s".',
$option,
$expected,
\is_object($value) ? \get_class($value) : (null === $value ? '<null>' : \gettype($value).'#'.$value)
),
$code,
$previous
);
}
}
<?php
namespace PhpCsFixer\Diff\GeckoPackages\DiffOutputBuilder;
use PhpCsFixer\Diff\v2_0\Output\DiffOutputBuilderInterface;
/**
@description
*/
final class UnifiedDiffOutputBuilder implements DiffOutputBuilderInterface
{
private static $noNewlineAtOEFid = 998877;
private $changed;
private $collapseRanges;
private $commonLineThreshold;
private $header;
private $contextLines;
private static $default = [
'contextLines' => 3,
'collapseRanges' => true,
'fromFile' => null,
'fromFileDate' => null,
'toFile' => null,
'toFileDate' => null,
'commonLineThreshold' => 6,
];
public function __construct(array $options = [])
{
$options = \array_merge(self::$default, $options);
if (!\is_bool($options['collapseRanges'])) {
throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']);
}
if (!\is_int($options['contextLines']) || $options['contextLines'] < 0) {
throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']);
}
if (!\is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] < 1) {
throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']);
}
foreach (['fromFile', 'toFile'] as $option) {
if (!\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string', $options[$option]);
}
}
foreach (['fromFileDate', 'toFileDate'] as $option) {
if (null !== $options[$option] && !\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string or <null>', $options[$option]);
}
}
$this->header = \sprintf(
"--- %s%s\n+++ %s%s\n",
$options['fromFile'],
null === $options['fromFileDate'] ? '' : "\t".$options['fromFileDate'],
$options['toFile'],
null === $options['toFileDate'] ? '' : "\t".$options['toFileDate']
);
$this->collapseRanges = $options['collapseRanges'];
$this->commonLineThreshold = $options['commonLineThreshold'];
$this->contextLines = $options['contextLines'];
}
public function getDiff(array $diff)
{
if (0 === \count($diff)) {
return '';
}
$this->changed = false;
$buffer = \fopen('php://memory', 'r+b');
\fwrite($buffer, $this->header);
$this->writeDiffHunks($buffer, $diff);
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
if (!$this->changed) {
return '';
}
return $diff;
}
private function writeDiffHunks($output, array $diff)
{
$upperLimit = \count($diff);
if (0 === $diff[$upperLimit - 1][1]) {
$lc = \substr($diff[$upperLimit - 1][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
} else {
$toFind = [1 => true, 2 => true];
for ($i = $upperLimit - 1; $i >= 0; --$i) {
if (isset($toFind[$diff[$i][1]])) {
unset($toFind[$diff[$i][1]]);
$lc = \substr($diff[$i][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
if (!\count($toFind)) {
break;
}
}
}
}
$cutOff = \max($this->commonLineThreshold, $this->contextLines);
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
$toStart = $fromStart = 1;
foreach ($diff as $i => $entry) {
if (0 === $entry[1]) {
if (false === $hunkCapture) {
++$fromStart;
++$toStart;
continue;
}
++$sameCount;
++$toRange;
++$fromRange;
if ($sameCount === $cutOff) {
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
$contextEndOffset = $i + $this->contextLines >= \count($diff)
? \count($diff) - $i
: $this->contextLines
;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $cutOff + $contextEndOffset + 1,
$fromStart - $contextStartOffset,
$fromRange - $cutOff + $contextStartOffset + $contextEndOffset,
$toStart - $contextStartOffset,
$toRange - $cutOff + $contextStartOffset + $contextEndOffset,
$output
);
$fromStart += $fromRange;
$toStart += $toRange;
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
}
continue;
}
$sameCount = 0;
if ($entry[1] === self::$noNewlineAtOEFid) {
continue;
}
$this->changed = true;
if (false === $hunkCapture) {
$hunkCapture = $i;
}
if (1 === $entry[1]) {
++$toRange;
}
if (2 === $entry[1]) {
++$fromRange;
}
}
if (false !== $hunkCapture) {
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
\count($diff),
$fromStart - $contextStartOffset,
$fromRange + $contextStartOffset,
$toStart - $contextStartOffset,
$toRange + $contextStartOffset,
$output
);
}
}
private function writeHunk(
array $diff,
$diffStartIndex,
$diffEndIndex,
$fromStart,
$fromRange,
$toStart,
$toRange,
$output
) {
\fwrite($output, '@@ -'.$fromStart);
if (!$this->collapseRanges || 1 !== $fromRange) {
\fwrite($output, ','.$fromRange);
}
\fwrite($output, ' +'.$toStart);
if (!$this->collapseRanges || 1 !== $toRange) {
\fwrite($output, ','.$toRange);
}
\fwrite($output, " @@\n");
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1) {
$this->changed = true;
\fwrite($output, '+'.$diff[$i][0]);
} elseif ($diff[$i][1] === 2) {
$this->changed = true;
\fwrite($output, '-'.$diff[$i][0]);
} elseif ($diff[$i][1] === 0) {
\fwrite($output, ' '.$diff[$i][0]);
} elseif ($diff[$i][1] === self::$noNewlineAtOEFid) {
$this->changed = true;
\fwrite($output, $diff[$i][0]);
}
}
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class Chunk
{
private $start;
private $startRange;
private $end;
private $endRange;
private $lines;
public function __construct($start = 0, $startRange = 1, $end = 0, $endRange = 1, array $lines = [])
{
$this->start = $start;
$this->startRange = $startRange;
$this->end = $end;
$this->endRange = $endRange;
$this->lines = $lines;
}
public function getStart()
{
return $this->start;
}
public function getStartRange()
{
return $this->startRange;
}
public function getEnd()
{
return $this->end;
}
public function getEndRange()
{
return $this->endRange;
}
public function getLines()
{
return $this->lines;
}
public function setLines(array $lines)
{
$this->lines = $lines;
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class Line
{
const ADDED = 1;
const REMOVED = 2;
const UNCHANGED = 3;
private $type;
private $content;
public function __construct($type = self::UNCHANGED, $content = '')
{
$this->type = $type;
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function getType()
{
return $this->type;
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
use PhpCsFixer\Diff\v2_0\Output\DiffOutputBuilderInterface;
use PhpCsFixer\Diff\v2_0\Output\UnifiedDiffOutputBuilder;
final class Differ
{
private $outputBuilder;
public function __construct($outputBuilder = null)
{
if ($outputBuilder instanceof DiffOutputBuilderInterface) {
$this->outputBuilder = $outputBuilder;
} elseif (null === $outputBuilder) {
$this->outputBuilder = new UnifiedDiffOutputBuilder;
} elseif (\is_string($outputBuilder)) {
$this->outputBuilder = new UnifiedDiffOutputBuilder($outputBuilder);
} else {
throw new InvalidArgumentException(
\sprintf(
'Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got %s.',
\is_object($outputBuilder) ? 'instance of "' . \get_class($outputBuilder) . '"' : \gettype($outputBuilder) . ' "' . $outputBuilder . '"'
)
);
}
}
public function diff($from, $to, LongestCommonSubsequenceCalculator $lcs = null)
{
$from = $this->validateDiffInput($from);
$to = $this->validateDiffInput($to);
$diff = $this->diffToArray($from, $to, $lcs);
return $this->outputBuilder->getDiff($diff);
}
private function validateDiffInput($input)
{
if (!\is_array($input) && !\is_string($input)) {
return (string) $input;
}
return $input;
}
public function diffToArray($from, $to, LongestCommonSubsequenceCalculator $lcs = null)
{
if (\is_string($from)) {
$from = $this->splitStringByLines($from);
} elseif (!\is_array($from)) {
throw new \InvalidArgumentException('"from" must be an array or string.');
}
if (\is_string($to)) {
$to = $this->splitStringByLines($to);
} elseif (!\is_array($to)) {
throw new \InvalidArgumentException('"to" must be an array or string.');
}
list($from, $to, $start, $end) = self::getArrayDiffParted($from, $to);
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}
$common = $lcs->calculate(\array_values($from), \array_values($to));
$diff = [];
foreach ($start as $token) {
$diff[] = [$token, 0 ];
}
\reset($from);
\reset($to);
foreach ($common as $token) {
while (($fromToken = \reset($from)) !== $token) {
$diff[] = [\array_shift($from), 2 ];
}
while (($toToken = \reset($to)) !== $token) {
$diff[] = [\array_shift($to), 1 ];
}
$diff[] = [$token, 0 ];
\array_shift($from);
\array_shift($to);
}
while (($token = \array_shift($from)) !== null) {
$diff[] = [$token, 2 ];
}
while (($token = \array_shift($to)) !== null) {
$diff[] = [$token, 1 ];
}
foreach ($end as $token) {
$diff[] = [$token, 0 ];
}
if ($this->detectUnmatchedLineEndings($diff)) {
\array_unshift($diff, ["#Warnings contain different line endings!\n", 3]);
}
return $diff;
}
private function splitStringByLines($input)
{
return \preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
private function selectLcsImplementation(array $from, array $to)
{
$memoryLimit = 100 * 1024 * 1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientLongestCommonSubsequenceCalculator;
}
return new TimeEfficientLongestCommonSubsequenceCalculator;
}
private function calculateEstimatedFootprint(array $from, array $to)
{
$itemSize = PHP_INT_SIZE === 4 ? 76 : 144;
return $itemSize * \min(\count($from), \count($to)) ** 2;
}
private function detectUnmatchedLineEndings(array $diff)
{
$newLineBreaks = ['' => true];
$oldLineBreaks = ['' => true];
foreach ($diff as $entry) {
if (0 === $entry[1]) {
$ln = $this->getLinebreak($entry[0]);
$oldLineBreaks[$ln] = true;
$newLineBreaks[$ln] = true;
} elseif (1 === $entry[1]) {
$newLineBreaks[$this->getLinebreak($entry[0])] = true;
} elseif (2 === $entry[1]) {
$oldLineBreaks[$this->getLinebreak($entry[0])] = true;
}
}
if (['' => true] === $newLineBreaks || ['' => true] === $oldLineBreaks) {
return false;
}
foreach ($newLineBreaks as $break => $set) {
if (!isset($oldLineBreaks[$break])) {
return true;
}
}
foreach ($oldLineBreaks as $break => $set) {
if (!isset($newLineBreaks[$break])) {
return true;
}
}
return false;
}
private function getLinebreak($line)
{
if (!\is_string($line)) {
return '';
}
$lc = \substr($line, -1);
if ("\r" === $lc) {
return "\r";
}
if ("\n" !== $lc) {
return '';
}
if ("\r\n" === \substr($line, -2)) {
return "\r\n";
}
return "\n";
}
private static function getArrayDiffParted(array &$from, array &$to)
{
$start = [];
$end = [];
\reset($to);
foreach ($from as $k => $v) {
$toK = \key($to);
if ($toK === $k && $v === $to[$k]) {
$start[$k] = $v;
unset($from[$k], $to[$k]);
} else {
break;
}
}
\end($from);
\end($to);
do {
$fromK = \key($from);
$toK = \key($to);
if (null === $fromK || null === $toK || \current($from) !== \current($to)) {
break;
}
\prev($from);
\prev($to);
$end = [$fromK => $from[$fromK]] + $end;
unset($from[$fromK], $to[$toK]);
} while (true);
return [$from, $to, $start, $end];
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class Parser
{
public function parse($string)
{
$lines = \preg_split('(\r\n|\r|\n)', $string);
if (!empty($lines) && $lines[\count($lines) - 1] === '') {
\array_pop($lines);
}
$lineCount = \count($lines);
$diffs = [];
$diff = null;
$collected = [];
for ($i = 0; $i < $lineCount; ++$i) {
if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
\preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
if ($diff !== null) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
$collected = [];
}
$diff = new Diff($fromMatch['file'], $toMatch['file']);
++$i;
} else {
if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
continue;
}
$collected[] = $lines[$i];
}
}
if ($diff !== null && \count($collected)) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
}
return $diffs;
}
private function parseFileDiff(Diff $diff, array $lines)
{
$chunks = [];
$chunk = null;
foreach ($lines as $line) {
if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
$chunk = new Chunk(
(int) $match['start'],
isset($match['startrange']) ? \max(1, (int) $match['startrange']) : 1,
(int) $match['end'],
isset($match['endrange']) ? \max(1, (int) $match['endrange']) : 1
);
$chunks[] = $chunk;
$diffLines = [];
continue;
}
if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
$type = Line::UNCHANGED;
if ($match['type'] === '+') {
$type = Line::ADDED;
} elseif ($match['type'] === '-') {
$type = Line::REMOVED;
}
$diffLines[] = new Line($type, $match['line']);
if (null !== $chunk) {
$chunk->setLines($diffLines);
}
}
}
$diff->setChunks($chunks);
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to)
{
$common = [];
$fromLength = \count($from);
$toLength = \count($to);
$width = $fromLength + 1;
$matrix = new \SplFixedArray($width * ($toLength + 1));
for ($i = 0; $i <= $fromLength; ++$i) {
$matrix[$i] = 0;
}
for ($j = 0; $j <= $toLength; ++$j) {
$matrix[$j * $width] = 0;
}
for ($i = 1; $i <= $fromLength; ++$i) {
for ($j = 1; $j <= $toLength; ++$j) {
$o = ($j * $width) + $i;
$matrix[$o] = \max(
$matrix[$o - 1],
$matrix[$o - $width],
$from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
);
}
}
$i = $fromLength;
$j = $toLength;
while ($i > 0 && $j > 0) {
if ($from[$i - 1] === $to[$j - 1]) {
$common[] = $from[$i - 1];
--$i;
--$j;
} else {
$o = ($j * $width) + $i;
if ($matrix[$o - $width] > $matrix[$o - 1]) {
--$j;
} else {
--$i;
}
}
}
return \array_reverse($common);
}
}
<?php
namespace PhpCsFixer\Diff\v2_0\Output;
final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
{
private $header;
public function __construct($header = "--- Original\n+++ New\n")
{
$this->header = $header;
}
public function getDiff(array $diff)
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
foreach ($diff as $diffEntry) {
if ($diffEntry[1] === 1 ) {
\fwrite($buffer, '+' . $diffEntry[0]);
} elseif ($diffEntry[1] === 2 ) {
\fwrite($buffer, '-' . $diffEntry[0]);
} elseif ($diffEntry[1] === 3 ) {
\fwrite($buffer, ' ' . $diffEntry[0]);
continue;
} else {
continue;
}
$lc = \substr($diffEntry[0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($buffer, "\n");
}
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
}
}
<?php
namespace PhpCsFixer\Diff\v2_0\Output;
abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
{
protected function getCommonChunks(array $diff, $lineThreshold = 5)
{
$diffSize = \count($diff);
$capturing = false;
$chunkStart = 0;
$chunkSize = 0;
$commonChunks = [];
for ($i = 0; $i < $diffSize; ++$i) {
if ($diff[$i][1] === 0 ) {
if ($capturing === false) {
$capturing = true;
$chunkStart = $i;
$chunkSize = 0;
} else {
++$chunkSize;
}
} elseif ($capturing !== false) {
if ($chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
$capturing = false;
}
}
if ($capturing !== false && $chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
return $commonChunks;
}
}
<?php
namespace PhpCsFixer\Diff\v2_0\Output;
interface DiffOutputBuilderInterface
{
public function getDiff(array $diff);
}
<?php
namespace PhpCsFixer\Diff\v2_0\Output;
final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
private $header;
private $addLineNumbers;
public function __construct($header = "--- Original\n+++ New\n", $addLineNumbers = false)
{
$this->header = $header;
$this->addLineNumbers = $addLineNumbers;
}
public function getDiff(array $diff)
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
$this->writeDiffChunked($buffer, $diff, $this->getCommonChunks($diff));
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
}
private function writeDiffChunked($output, array $diff, array $old)
{
$upperLimit = \count($diff);
$start = 0;
$fromStart = 0;
$toStart = 0;
if (\count($old)) {
\reset($old);
do {
$commonStart = \key($old);
$commonEnd = \current($old);
if ($commonStart !== $start) {
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $commonStart);
$this->writeChunk($output, $diff, $start, $commonStart, $fromStart, $fromRange, $toStart, $toRange);
$fromStart += $fromRange;
$toStart += $toRange;
}
$start = $commonEnd + 1;
$commonLength = $commonEnd - $commonStart + 1;
$fromStart += $commonLength;
$toStart += $commonLength;
} while (false !== \next($old));
\end($old);
$tmp = \key($old);
\reset($old);
if ($old[$tmp] === $upperLimit - 1) {
$upperLimit = $tmp;
}
}
if ($start < $upperLimit - 1) {
do {
--$upperLimit;
} while (isset($diff[$upperLimit][1]) && $diff[$upperLimit][1] === 0);
++$upperLimit;
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $upperLimit);
$this->writeChunk($output, $diff, $start, $upperLimit, $fromStart, $fromRange, $toStart, $toRange);
}
}
private function writeChunk(
$output,
array $diff,
$diffStartIndex,
$diffEndIndex,
$fromStart,
$fromRange,
$toStart,
$toRange
) {
if ($this->addLineNumbers) {
\fwrite($output, '@@ -' . (1 + $fromStart));
if ($fromRange !== 1) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . (1 + $toStart));
if ($toRange !== 1) {
\fwrite($output, ',' . $toRange);
}
\fwrite($output, " @@\n");
} else {
\fwrite($output, "@@ @@\n");
}
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1 ) {
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === 2 ) {
\fwrite($output, '-' . $diff[$i][0]);
} else {
\fwrite($output, ' ' . $diff[$i][0]);
}
$lc = \substr($diff[$i][0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($output, "\n");
}
}
}
private function getChunkRange(array $diff, $diffStartIndex, $diffEndIndex)
{
$toRange = 0;
$fromRange = 0;
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1) {
++$toRange;
} elseif ($diff[$i][1] === 2) {
++$fromRange;
} elseif ($diff[$i][1] === 0) {
++$fromRange;
++$toRange;
}
}
return [$fromRange, $toRange];
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
interface LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to);
}
<?php
namespace PhpCsFixer\Diff\v2_0;
interface Exception
{
}
<?php
namespace PhpCsFixer\Diff\v2_0;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class Diff
{
private $from;
private $to;
private $chunks;
public function __construct($from, $to, array $chunks = [])
{
$this->from = $from;
$this->to = $to;
$this->chunks = $chunks;
}
public function getFrom()
{
return $this->from;
}
public function getTo()
{
return $this->to;
}
public function getChunks()
{
return $this->chunks;
}
public function setChunks(array $chunks)
{
$this->chunks = $chunks;
}
}
<?php
namespace PhpCsFixer\Diff\v2_0;
final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
public function calculate(array $from, array $to)
{
$cFrom = \count($from);
$cTo = \count($to);
if ($cFrom === 0) {
return [];
}
if ($cFrom === 1) {
if (\in_array($from[0], $to, true)) {
return [$from[0]];
}
return [];
}
$i = (int) ($cFrom / 2);
$fromStart = \array_slice($from, 0, $i);
$fromEnd = \array_slice($from, $i);
$llB = $this->length($fromStart, $to);
$llE = $this->length(\array_reverse($fromEnd), \array_reverse($to));
$jMax = 0;
$max = 0;
for ($j = 0; $j <= $cTo; $j++) {
$m = $llB[$j] + $llE[$cTo - $j];
if ($m >= $max) {
$max = $m;
$jMax = $j;
}
}
$toStart = \array_slice($to, 0, $jMax);
$toEnd = \array_slice($to, $jMax);
return \array_merge(
$this->calculate($fromStart, $toStart),
$this->calculate($fromEnd, $toEnd)
);
}
private function length(array $from, array $to)
{
$current = \array_fill(0, \count($to) + 1, 0);
$cFrom = \count($from);
$cTo = \count($to);
for ($i = 0; $i < $cFrom; $i++) {
$prev = $current;
for ($j = 0; $j < $cTo; $j++) {
if ($from[$i] === $to[$j]) {
$current[$j + 1] = $prev[$j] + 1;
} else {
$current[$j + 1] = \max($current[$j], $prev[$j + 1]);
}
}
}
return $current;
}
}
<?php
require_once __DIR__ . '/psalm-autoload.php';
if (PHP_VERSION_ID >= 50300) {
if (!class_exists('PHPUnit_Framework_TestCase')) {
require_once __DIR__ . '/other/phpunit-shim.php';
}
}
<?php
if (!is_callable('random_bytes')) {
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = '';
if (!class_exists('COM')) {
throw new Error(
'COM does not exist'
);
}
$util = new COM('CAPICOM.Utilities.1');
$execCount = 0;
do {
$buf .= base64_decode((string) $util->GetRandom($bytes, 0));
if (RandomCompat_strlen($buf) >= $bytes) {
return (string) RandomCompat_substr($buf, 0, $bytes);
}
++$execCount;
} while ($execCount < $bytes);
throw new Exception(
'Could not gather sufficient random data'
);
}
}
<?php
if (!is_callable('random_bytes')) {
/**
@ref
@ref
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM);
if (
is_string($buf)
&&
RandomCompat_strlen($buf) === $bytes
) {
return $buf;
}
throw new Exception(
'Could not gather sufficient random data'
);
}
}
<?php
if (!is_callable('RandomCompat_strlen')) {
if (
defined('MB_OVERLOAD_STRING')
&&
((int) ini_get('mbstring.func_overload')) & MB_OVERLOAD_STRING
) {
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) mb_strlen($binary_string, '8bit');
}
} else {
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) strlen($binary_string);
}
}
}
if (!is_callable('RandomCompat_substr')) {
if (
defined('MB_OVERLOAD_STRING')
&&
((int) ini_get('mbstring.func_overload')) & MB_OVERLOAD_STRING
) {
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length === null) {
$length = RandomCompat_strlen($binary_string) - $start;
} elseif (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
if ($start === RandomCompat_strlen($binary_string) && $length === 0) {
return '';
}
if ($start > RandomCompat_strlen($binary_string)) {
return '';
}
return (string) mb_substr(
(string) $binary_string,
(int) $start,
(int) $length,
'8bit'
);
}
} else {
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length !== null) {
if (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
return (string) substr(
(string )$binary_string,
(int) $start,
(int) $length
);
}
return (string) substr(
(string) $binary_string,
(int) $start
);
}
}
}
<?php
/**
@released
*/
if (!defined('PHP_VERSION_ID')) {
$RandomCompatversion = array_map('intval', explode('.', PHP_VERSION));
define(
'PHP_VERSION_ID',
$RandomCompatversion[0] * 10000
+ $RandomCompatversion[1] * 100
+ $RandomCompatversion[2]
);
$RandomCompatversion = null;
}
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
$RandomCompatDIR = dirname(__FILE__);
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'byte_safe_strings.php';
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'cast_to_int.php';
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'error_polyfill.php';
if (!is_callable('random_bytes')) {
if (extension_loaded('libsodium')) {
if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_libsodium.php';
} elseif (method_exists('Sodium', 'randombytes_buf')) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_libsodium_legacy.php';
}
}
if (DIRECTORY_SEPARATOR === '/') {
$RandomCompatUrandom = true;
$RandomCompat_basedir = ini_get('open_basedir');
if (!empty($RandomCompat_basedir)) {
$RandomCompat_open_basedir = explode(
PATH_SEPARATOR,
strtolower($RandomCompat_basedir)
);
$RandomCompatUrandom = (array() !== array_intersect(
array('/dev', '/dev/', '/dev/urandom'),
$RandomCompat_open_basedir
));
$RandomCompat_open_basedir = null;
}
if (
!is_callable('random_bytes')
&&
$RandomCompatUrandom
&&
@is_readable('/dev/urandom')
) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_dev_urandom.php';
}
$RandomCompat_basedir = null;
} else {
$RandomCompatUrandom = false;
}
if (
!is_callable('random_bytes')
&&
(DIRECTORY_SEPARATOR === '/' || PHP_VERSION_ID >= 50307)
&&
(
DIRECTORY_SEPARATOR !== '/' ||
(PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
)
&&
extension_loaded('mcrypt')
) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_mcrypt.php';
}
$RandomCompatUrandom = null;
if (
!is_callable('random_bytes')
&&
extension_loaded('com_dotnet')
&&
class_exists('COM')
) {
$RandomCompat_disabled_classes = preg_split(
'#\s*,\s*#',
strtolower(ini_get('disable_classes'))
);
if (!in_array('com', $RandomCompat_disabled_classes)) {
try {
$RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_bytes_com_dotnet.php';
}
} catch (com_exception $e) {
}
}
$RandomCompat_disabled_classes = null;
$RandomCompatCOMtest = null;
}
if (!is_callable('random_bytes')) {
/**
@psalm
*/
function random_bytes($length)
{
unset($length);
throw new Exception(
'There is no suitable CSPRNG installed on your system'
);
return '';
}
}
}
if (!is_callable('random_int')) {
require_once $RandomCompatDIR . DIRECTORY_SEPARATOR . 'random_int.php';
}
$RandomCompatDIR = null;
<?php
if (!is_callable('random_bytes')) {
/**
@ref
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
if ($bytes > 2147483647) {
$buf = '';
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= \Sodium\randombytes_buf($n);
}
} else {
$buf = \Sodium\randombytes_buf($bytes);
}
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
throw new Exception(
'Could not gather sufficient random data'
);
}
}
<?php
if (!class_exists('Error', false)) {
class Error extends Exception
{
}
}
if (!class_exists('TypeError', false)) {
if (is_subclass_of('Error', 'Exception')) {
class TypeError extends Error
{
}
} else {
class TypeError extends Exception
{
}
}
}
<?php
if (!is_callable('RandomCompat_intval')) {
/**
@psalm
*/
function RandomCompat_intval($number, $fail_open = false)
{
if (is_int($number) || is_float($number)) {
$number += 0;
} elseif (is_numeric($number)) {
/**
@psalm */
$number += 0;
}
if (
is_float($number)
&&
$number > ~PHP_INT_MAX
&&
$number < PHP_INT_MAX
) {
$number = (int) $number;
}
if (is_int($number)) {
return (int) $number;
} elseif (!$fail_open) {
throw new TypeError(
'Expected an integer.'
);
}
return $number;
}
}
<?php
if (!is_callable('random_bytes')) {
/**
@ref
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = '';
if ($bytes > 2147483647) {
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= Sodium::randombytes_buf((int) $n);
}
} else {
$buf .= Sodium::randombytes_buf((int) $bytes);
}
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
throw new Exception(
'Could not gather sufficient random data'
);
}
}
<?php
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
if (!is_callable('random_bytes')) {
/**
@ref
@ref
*/
function random_bytes($bytes)
{
static $fp = null;
if (empty($fp)) {
if (DIRECTORY_SEPARATOR === '/') {
if (!is_readable('/dev/urandom')) {
throw new Exception(
'Environment misconfiguration: ' .
'/dev/urandom cannot be read.'
);
}
$fp = fopen('/dev/urandom', 'rb');
if (is_resource($fp)) {
$st = fstat($fp);
if (($st['mode'] & 0170000) !== 020000) {
fclose($fp);
$fp = false;
}
}
}
if (is_resource($fp)) {
if (is_callable('stream_set_read_buffer')) {
stream_set_read_buffer($fp, RANDOM_COMPAT_READ_BUFFER);
}
if (is_callable('stream_set_chunk_size')) {
stream_set_chunk_size($fp, RANDOM_COMPAT_READ_BUFFER);
}
}
}
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
if (is_resource($fp)) {
$remaining = $bytes;
$buf = '';
do {
$read = fread($fp, $remaining);
if (!is_string($read)) {
$buf = false;
break;
}
$remaining -= RandomCompat_strlen($read);
$buf .= $read;
} while ($remaining > 0);
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
}
throw new Exception(
'Error reading from source device'
);
}
}
<?php
if (!is_callable('random_int')) {
function random_int($min, $max)
{
try {
$min = RandomCompat_intval($min);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $min must be an integer'
);
}
try {
$max = RandomCompat_intval($max);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $max must be an integer'
);
}
if ($min > $max) {
throw new Error(
'Minimum value must be less than or equal to the maximum value'
);
}
if ($max === $min) {
return (int) $min;
}
$attempts = $bits = $bytes = $mask = $valueShift = 0;
$range = $max - $min;
if (!is_int($range)) {
/**
@CodesInChaos
@oittaa
@ref
@ref
@ref
*/
$bytes = PHP_INT_SIZE;
$mask = ~0;
} else {
while ($range > 0) {
if ($bits % 8 === 0) {
++$bytes;
}
++$bits;
$range >>= 1;
$mask = $mask << 1 | 1;
}
$valueShift = $min;
}
$val = 0;
/**
@psalm */
do {
if ($attempts > 128) {
throw new Exception(
'random_int: RNG is broken - too many rejections'
);
}
$randomByteString = random_bytes($bytes);
$val &= 0;
for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8);
}
$val &= $mask;
$val += $valueShift;
++$attempts;
} while (!is_int($val) || $val > $max || $val < $min);
return (int) $val;
}
}
Copyright (c) 2012-2021 Fabien Potencier
Dariusz Rumiński
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* 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 === 80000
|| \PHP_VERSION_ID < 50600
|| \PHP_VERSION_ID >= 80100
) {
fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 8.0.*.\n");
fwrite(STDERR, 'Current PHP version: '.PHP_VERSION.".\n");
if (defined('PHP_VERSION_ID') && \PHP_VERSION_ID === 80000) {
fwrite(STDERR, "PHP CS Fixer is not able run on PHP 8.0.0 due to bug in PHP tokenizer (https://bugs.php.net/bug.php?id=80462).\n");
fwrite(STDERR, "Update PHP version to unblock execution.\n");
exit(1);
}
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 {
fwrite(STDERR, "To ignore this requirement please set `PHP_CS_FIXER_IGNORE_ENV`.\n");
fwrite(STDERR, "If you use PHP version higher than supported, you may experience code modified in a wrong way.\n");
fwrite(STDERR, "Please report such cases at https://github.com/FriendsOfPHP/PHP-CS-Fixer .\n");
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();
\7LÕK֯`<60><>+c<>{LcGBMB